Python Chapter 2 © Samuel Marateck, 2010 1 After you install the compiler, an icon labeled IDLE (Python GUI) will appear on the screen. If you click it, a window will appear on the screen with some copyright information. This window is called the shell. IDLE is an acronym for Integrated DeveLopment Environment which allows you to write, edit and run a program. 2 Under that a prompt indicated by >>> will appear. This prompts you to type some Instruction. For instance, >>> 3*4 This instructs the computer to multiply 3 times 4. The computer responds with the product, 12. So you see: 3 >>>3*4 12 There are two types of numbers we will be working with, integers and floats. Let’s discuss integers first. 4 An integer has no decimal point. Examples 3, 456, -12. These are called integer literals We first list symbols that you are familiar with: + (addition), - (subtraction), * (multiplication), and / (division). 5 We first list symbols that you are familiar with: + (addition), - (subtraction), * (multiplication), and / (division). The first three produce an integer; but the / produces a number with a decimal point. 6 The / produces a number with a decimal point. So for instance typing 4/2 we get >>> 4/2 2.0 The number 2.0 in called a floating point number or simply, a float. It is an example of a float literal. 7 There are three other operations you can use with integers. Let’s try “//”, integer division: >>> 7//2 3 Now 7/2 produces 3.5. The // operator instructs the compiler to truncate the results, i.e., lops off the part of the number to the right of the decimal point. So 3.5 becomes 3 8 The second operator is %, the remainder operator. >>>7%2 1 Think of it this way, after 7//2 is performed, the reminder is 1. 9 The third operator is ** which indicates exponentiation, so >>> 2**3 8 10 As oppose to other languages , there is no limit to the number of digits in an integer. So >>>2**300 20370359763344860862684456884093781 61051468393665936250636140449354381 299763336706183397376 11 The operators have a precedence. the operator with the highest precedence is ** , then comes *, /, //, and %. These all have the same precedence. Finally comes +, -. 12 So 3*4 + 5 evaluates as 12+5 or 17. How do you change the precedence, so that the addition is done before the multiplication? . 13 .How do you change the precedence, so that the addition is done before the multiplication? Use (). So: >>> 3*(4+5) 27 The operations in the () are always done first. 14 Similarly >>> 3+2**4 19 How do you have the addition done before the exponentiation? 15 To have the addition done before the exponentiation, use (): >>>(3+2)**4 625 or 5**4 16 Order of Operations Operator () ** * / // Operation parentheses exponentiation multiplication division int division Precedence 0 1 2 2 2 % + - remainder addition subtraction 2 3 3 17 The computer scans the expression from left to right, first clearing parentheses, second, evaluating exponentiations from left to right in the order they are encountered third, evaluating *, /, //, % from left to right in the order they are encountered, fourth, evaluating +, - from left to right in the order they are encountered 18 How would you evaluate (3+3*5)/2*3? Is it 18/6 i.e, 3 or is it 9*3? 19 These are the steps in evaluating the Expression (3+3*5)/2*3 1.(3 + 15)/2*3 2. 18/2*3 3. 9*3 4. 27 20 The same operators that apply to integers apply to floats. For instance. In 5.2//2.1 python first uses regular division, 5.2/2.1 getting 2.4761904761904763 and truncates the answer to 2. 21 Let’s do 6.3//2.1. You might expect to get 3.0 but you get 2.0. Why? 22 First, let’s calculate 6.3/2.1 using regular division, the answer is 3.0 . But floats are only approximations. The answer that’s stored in memory is 2.999999 but is printed as 3.0. The // operation truncates the results. So 6.3//2.1 is 2.99999 truncated to 2.0 23 So we’d expect 6.4//2.1 to produce 3.0 and it does. 24 Integers are stored in the memory exactly; whereas stored floats are only approximations. 25 There are math functions that can be Imported. To do this, type import math. If you then type help(math), the computer will type all the math functions and what they do: >>>import math >>help(math) 26 Then if you want to find the √5, you type >>>math.sqrt(5) and you get 2.2360679774997898 27 If you don’t want to type math each time you use a function, type: >>>from math import * Then you can simply write: >>>sqrt(5) 2.2360679774997898 28 If you just want to see the functions in the math module, type >>>dir(math) and you get: 29 ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] 30 If you want to see the meaning of a function, place the function name in the () in help. Example: >>>help(hypot) This gives: 31 >>> help(hypot) Help on built-in function hypot in module math: hypot(...) hypot(x,y) Return the Euclidean distance, sqrt(x*x + y*y). 32 What does >>> hypot(3,4) give you? 33 >>> hypot(3,4) 5.0 34 Strings A string is a group of one or more characters sandwiched between “ or ‘. So “123sd” and ‘sde’ are strings. The characters “ and ‘ are called delimiters. If the string starts with a “, it must end with a “; if it starts with a ‘ it must end with a ‘. 35 The + operator is overloaded. This means it use depends upon context. We have seen its use with floats and integers. It can also be used with strings. 36 When used with strings, it joins them creating a new string. So >>>’abc’ + “123” ‘abc123’ 37 To get the number of characters in a string Use the len function. >>>len(’abc’ + “123”) 6 38 Using Variables A variable is a name associated with a memory location. Examples one = 12 two = 12.5 st = ‘123as’ One, two and s are variable names. The type of the literal determines the variable type. So one is an integer, two a float, and st a string. 39 Variable names are case sensitive, so one and One are two different variables (since One is capitalized and one is not) and describe two different memory locations. 40 Conversion functions You can’t concatenate a string with another type. So >>> 'anc' + 3 produces Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> 'anc' + 3 TypeError: Can't convert 'int' object to str implicitly 41 The error message: TypeError: Can't convert 'int' object to str implicitly means that we have to explicitly make 3 in: 'anc' + 3 a string. The function str does this: >>> 'anc' + str(3) 'anc3‘ The error is an example of a syntax error since it doesn’t follow the grammatical rules of Python. 42 The following table show the conversion functions. 43 function use Str() Converts a number to a string Converts an object to an integer and truncates. Converts an object to an integer and rounds. Converts an object to a 44 float. int() round() float Examples: >>>int(‘1234’) 1234 >>>float(‘1234’) 1234.0 >>>round(12.56) 13 >>>str(12.34) ’12.34’ 45 When int() operates on a string, what is embedded between the quotes must be an integer, so >>>int(’1.234’) because 1.234 is a float, produces: int('1.234') ValueError: invalid literal for int() with base 10: '1.234' 46 When an integer is used in an expression containing a float, the result is also a float: >>12 + 3.0 15.0 47