COMP519 Web Programming Lecture 17: Python (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool
Contents 1 Python Overview Example Basic Syntax Type System 2 Primitive Data Types Integers Floating-Point Numbers Complex Numbers Strings Booleans 3 Further Reading COMP519 Web Programming Lecture 17 Slide L17 1
Python Python: History Overview The implementation of Python was started in December 1989 by Guido van Rossum at CWI in the Netherlands The name Python is a reference to Monty Python s Flying Circus In 2001 the Python Software Foundation took over the development of Python; it maintans the CPython reference implementation of Python Python 2.0 was released in October 2000 Python 3.0 was released in October 2008 with major imcompatibilities to Python 2.0 Python 3.7, released 27 June 2018, is the current version Python is described as a multi-paradigm programming language, including support for functional programming, object-oriented programming, design by contract, and logic programming There exist interpreters as well as compilers for Python COMP519 Web Programming Lecture 17 Slide L17 2
Python Python: Hello World Example 1 #!/ usr / bin / python3 2 # HelloWorld. py 3 # Our first Python script 4 5 print (" Hello World ") On Unix/Linux systems, Python scripts begin with #! (called hash bang or she bang ) and the location of the Python interpreter/compiler If not intended to be web-accessible, the script can be stored anywhere, for example, in a file HellowWorld.py The script HellowWorld.py must be executable The script can then be executed using bash$./ HelloWorld. py assuming that the script is stored in the current working directory COMP519 Web Programming Lecture 17 Slide L17 3
Python Basic Python Syntax Basic Syntax A Python program/script consists of one or more statements and comments One-line comments start with # and run to the end of the line Multi-line comments simply consist of several one-line comments Statements are delimited by newlines except where a newline is escaped (by a backslash \) print \ (" Hello World ") COMP519 Web Programming Lecture 17 Slide L17 4
Python Basic Python Syntax Basic Syntax Blocks of statements, called suites are delimited with indentation each time the level of indentation is increased, a new block starts each time the level of indentation is decreased, a block has ended A colon : separates the header of block from the rest of the suite i = 0 while (i <3): i += 1 print ( i) # prints 1, 2, 3 ( on separate lines ) j = 0 while (j <3): j += 1 print ( j) # prints 3 k = 0 while (k <3): k += 1 print ( k) # IndentationError, # whole program does not run COMP519 Web Programming Lecture 17 Slide L17 5
Python Python: Type System Type System Python is both a dynamically typed language: a variable declaration does not include a type and a variable can hold values of different types over time x = " Hello " x = 42 is a valid sequence of statements a (mostly) strongly typed language: values are not automatically converted from unrelated types y = " Hello " + 42 will cause an error in Python However, quite a number of types are considered to be related z = 42 and True # z --> True will not cause an error in Python although a boolean operator is applied to a number COMP519 Web Programming Lecture 17 Slide L17 6
Python Types Type System Data Type / Datatype / Type A set of computer represented values together with a set of operations that can be performed on those values Python distinguished a lot more types than JavaScript, including int float complex str bool integers floating-point numbers complex numbers strings booleans list lists Types are classified into immutable mutable value is unchangeable once created value is changeable afer creation COMP519 Web Programming Lecture 17 Slide L17 7
Integers Integers The Python immutable datatype int covers the integers Positive integers can be written in various ways Decimal literals (base 10): A sequence of digits 0 9 not starting with 0 0 2012 40 1263978 Binary literals (base 2): A sequence of digits 0 1 prefixed by 0b or 0B 0b10 0b01 0b0 0b11011011 Octal literals (base 8): A sequence of digits 0 7 prefixed by 0o or 0O 0o10 0O20 0o40 0o1263978 Hexadecimal literals (base 16): A sequence of characters A F and digits 0 9 prefixed by 0x or 0X 0x10 0X20-0xFF -0x1236A7F Negative integers are obtained by applying the unary - operation to a positive integer COMP519 Web Programming Lecture 17 Slide L17 8
Integers Integers Python 2 distinguishes between int (32-bit integers) and long (arbitrary length) Elements of long are suffixed with the character l or L Python 3 only has the type int but it now stands for integers of arbitrary length (only limited by memory) there are elements of int that are bigger than any element of float Python 3.6 allows to separate groups of digits by an underscore _ to improve readability of long numbers 10 _000_000 0 xcafe_f00d 0 b_0011_1111_0100 1 _2_3_4_50 0 xc0_f_f_ee 0 b_00_11_1_0_01_0 Python has no auto-increment ++ nor auto-decrement -- operator COMP519 Web Programming Lecture 17 Slide L17 9
Floating-Point Numbers Floating-point Numbers and Arithmetic Operators The Python immutable datatype float covers (64-bit) floating-point numbers 1.25 256.0-12e19 2.4e-10 1.7976931348623157e+308 Python has no auto-increment ++ nor auto-decrement -- operator Python supports a wide range of arithmetic operators +, *, -, ** applied to two integers produce an int // (integer division) applied to a float produce a float % (modulo) / always produces a float round(number,prec) round fractions Peculiarities: round(2.5) returns 3 as int round(2.5,0) returns 3.0 as float round(-2.5) returns -2 as int COMP519 Web Programming Lecture 17 Slide L17 10
Modules Floating-Point Numbers A lot of functionality of Python is contained in modules The statement import module1 [, module2 [,... modulen ]] makes all functions from modules module1, module2 available, but all function names must be prefixed by the module name import math print math. factorial (5) The statement from module1 import fun1 [, fun2 [,... funn ]] imports the named functions from module module1 and makes them available without the need for a prefix from math import factorial print factorial (5) COMP519 Web Programming Lecture 17 Slide L17 11
Additional Arithmetic Operators Floating-Point Numbers Additional arithmetic operators are available from the math module: math.fabs(number) absolute value math.ceil(number) round fractions up math.floor(number) round fractions down math.log(number) natural logarithm math.sqrt(number) square root Interesting instances: math.sqrt(-1) returns ValueError: math domain error math.log(0) 1/0 0/0 returns ValueError: math domain error returns ZeroDivisionError: division by zero returns ZeroDivisionError: division by zero Random number operators are available from the random module random.uniform(low, high) random float between low and high random.randint(low, high) random int between low and high COMP519 Web Programming Lecture 17 Slide L17 12
Complex Numbers Complex Numbers The Python immutable datatype complex covers complex numbers of the form real + imagj where real and imag are floating-point numbers and J (or j) represents the square root of -1 The cmath module provides additional arithmetic operators including math.log(number) natural logarithm math.sqrt(number) square root Interesting instances: cmath.sqrt(-1) returns 1j cmath.log(0) returns ValueError: math domain error COMP519 Web Programming Lecture 17 Slide L17 13
Strings Strings String literals are elements of the immutable type str A string literal is a sequence of characters surrounded by single-quotes, double-quotes, or triple-quotes chars single-quoted string "chars" double-quoted string chars """chars""" triple-quoted string, can span several lines and contain single and double quotes, but not at the start or end This is a triple - quoted string containing " quotes " and spanning more than one line In all these forms \ acts as escape character Each character in a string has an (index) position given by the number of preceding characters " university " 0123456789 COMP519 Web Programming Lecture 17 Slide L17 14
Strings Strings Escape sequences have the same meaning as in JavaScript: \ (single quote) \" (double quote) \\ (backslash) \b (backspace) \f (form feed) \n (newline) \r (carriage return) \t (tab) Prefixing a string literal with the character r turns \ into an ordinary character "\" COMP519 \"" # " COMP519 " r "\" COMP519 \"" # \" COMP519 \" Python uses + for string concatenation " COMP " + 519 # returns " COMP519 " the + end # returns " the end " but does not automatically convert values of other types to strings " COMP " + 519 # results in TypeError : must be str, not int COMP519 Web Programming Lecture 17 Slide L17 15
Strings Strings There are a range of additional string operators, for example: len(string) Returns the length of a string as integer len("university") # returns 10 string.lower() Returns a copy of string with all characters lower-cased "abacus".lower() # returns "abacus" string.upper() Returns a copy of string with all characters upper-cased "abacus".upper() # returns "ABACUS" COMP519 Web Programming Lecture 17 Slide L17 16
Strings Strings There are a range of additional string operators, for example: string[start:after] Returns the substring of string starting at start and ending at after-1 "university"[3:5] # returns "ve" string.find(str, [start]) Returns the position at which str starts in string after start "university".find("i",3) # returns 7 (count starts at 0) "university".find("z",0) # returns -1 (not found) string.split(str) Split string along occurrences of str into a list of substrings "university".split("i") "university".split("a") "jabbaba".split("b") # returns ["un","vers","ty"] # returns ["university"] # returns ["ja","","a", "a"] COMP519 Web Programming Lecture 17 Slide L17 17
Booleans Booleans Python has an immutable datatype bool with constants True and False (case sensitive) Python offers the following short-circuit boolean operators: and (conjunction) or (disjunction) not (negation) The following objects are evaluated by Python as False: numerical zero values (0, 0.0, 0.0+0.0j) the Boolean value False empty strings (but not the string "0") empty lists, empty tuples, empty dictionaries, the special value None all other objects are evaluated as True (truth testing procedure) COMP519 Web Programming Lecture 17 Slide L17 18
Further Reading Revision and Further Reading Read Chapter 26: The Python Language: The History of Python to Chapter 26: The Python Language: Calculations and Operators of S. Schafer: Web Standards Programmer s Reference. Wiley Publishing, 2005. Harold Cohen Library 518.532.S29 or E-book http://library.liv.ac.uk/record=b2174141 COMP519 Web Programming Lecture 17 Slide L17 19