Lesson 12 Introduction to the Python Programming Language

  • Slides: 42
Download presentation
Lesson #12 Introduction to the Python Programming Language Slide #1 CPS 118 – Lesson

Lesson #12 Introduction to the Python Programming Language Slide #1 CPS 118 – Lesson #12 – Introduction to Python

What Is Python? Python is an up and coming general purpose object-oriented language, widely

What Is Python? Python is an up and coming general purpose object-oriented language, widely used in the scientific community. • It is free and open source and comes with an Integrated Development Environment (IDE) named IDLE. • It has both interactive vs. batch mode capability, just like MATLAB (command window vs. scripts) Slide #2 CPS 118 – Lesson #12 – Introduction to Python

What Is Python? Python was first released in an early form by Guido van

What Is Python? Python was first released in an early form by Guido van Rossum from The Netherlands in 1991. It was named after the British comedy group Monty Python's Flying Circus. • To get a general introduction, watch the Youtube video by Derek Banas "Python Programming, Learn Python in One Video" : goo. gl/b 1 j. Us. H Slide #3 CPS 118 – Lesson #12 – Introduction to Python

How to Get Python Mac computers come with Python already installed. • To obtain

How to Get Python Mac computers come with Python already installed. • To obtain Python for Windows or other machines, go to www. python. org/downloads Slide #4 CPS 118 – Lesson #12 – Introduction to Python

Python Interactive Mode • As already mentioned, Python like MATLAB can be used in

Python Interactive Mode • As already mentioned, Python like MATLAB can be used in interactive or batch mode. For the interactive mode, we use the IDLE window akin to MATLAB’s command window. • Start IDLE, wait for the >>> prompt and type 3 + 4 and press ENTER to execute the line >>> 3 + 4 Note that this may not be indented beyond the 1 space IDLE gives after >>>. Indenting will be important in Python! • That is a valid Python expression (as in MATLAB) and IDLE answers (followed by a new prompt) 7 >>> Slide #5 CPS 118 – Lesson #12 – Introduction to Python

Python Variables • You can set a variable at the prompt as in MATLAB

Python Variables • You can set a variable at the prompt as in MATLAB >>> x = 3 + 4 • To output the value in x type: >>> print(x) 7 >>> Slide #6 You notice that print is pretty much like MATLAB’s disp command. We will see later that with extra attributes it can behave like the fprintf command too! CPS 118 – Lesson #12 – Introduction to Python

Python Batch Mode • A program, analogous to a MATLAB script, can be created

Python Batch Mode • A program, analogous to a MATLAB script, can be created in IDLE by selecting File > New File from the top menu line. A new file window appears. • Type the following two lines into that new window (but do not indent either line!): or y = 3 + 5; print (y) y=3+5 Unlike in MATLAB the semi-colon doesn’t suppress output but is a delimiter between statements to put multiple statements on the same line. print (y) • Save the program with File > Save As and give it a name such as my_prog (it will be stored as my_prog. py). • Run the program with Run > Run Module. You will see the answer 8 in the IDLE window. Slide #7 CPS 118 – Lesson #12 – Introduction to Python

Import sys At the top of your program code add import sys This provides

Import sys At the top of your program code add import sys This provides various constants, functions, etc to the program that the interpreter might need. Simple programs (like my_prog so far, do not need import sys but it costs nothing to add it and if it is needed, annoying errors popping up will be avoided). Slide #8 CPS 118 – Lesson #12 – Introduction to Python

Python Functions • As in most programming languages, Python employs functions (as seen, for

Python Functions • As in most programming languages, Python employs functions (as seen, for example, in MATLAB). As you already know, these are named pieces of code which perform some task. Python, like MATLAB has quite a number of built-in functions. Note that before using the math functions you need to import the math module with from math import * • Examples: fabs (x): absolute value of x pow (x, y): x to the power of y ceil (x), floor(x), sqrt(x), sin(x), cos(x): like MATLAB and a few more • Like in MATLAB, pi and e are also predefined. Slide #9 CPS 118 – Lesson #12 – Introduction to Python

Data Types and Variables Python has five main types numbers, strings, lists, tuples, and

Data Types and Variables Python has five main types numbers, strings, lists, tuples, and dictionaries. Variables can have any of these types assigned to them (same as MATLAB). y=3+5 A variable can be displayed on the environment's display by invoking the print statement. print (y) Slide #10 CPS 118 – Lesson #12 – Introduction to Python

Simple Strings, like in MATLAB are simply arrays of characters, but can have single

Simple Strings, like in MATLAB are simply arrays of characters, but can have single or double quotes. >>> y = "Hello World" >>> print(y) Hello World >>> z = 'Hello' >>> print(z) Hello >>> print ('This is my first Python program') This is my first Python program Slide #11 CPS 118 – Lesson #12 – Introduction to Python

Print statement Special characters inside quotes are 'escaped' by preceding with a backslash, another

Print statement Special characters inside quotes are 'escaped' by preceding with a backslash, another standard computing language feature. Add this line to my_prog (or use interactively, but easier to repeatedly see in your program's output when run). print('How is Henry's hamburger? ') How is Henry's hamburger? Since both " and ' work for quoting, could have also used print("How is Henry's hamburger? ") How is Henry's hamburger? Slide #12 CPS 118 – Lesson #12 – Introduction to Python

Formatted print statements can be formatted similarly to what is done in MATLAB’s fprintf.

Formatted print statements can be formatted similarly to what is done in MATLAB’s fprintf. See the different way variables are placed though with % instead of a comma. Note: An alternate version exists which we will not cover here. # are spaces. print('%s' % 'a') a print('%s' % 'abc') abc print('%d' % 7) 7 print('%. 3 f' % 7. 8) print('%9. 3 f' % 7. 8) print('%5. 1 f' % 7. 86) x = 7. 800 ####7. 800 ##7. 9 'hello ' + 'how are you' print(x) hello how are you print('%5. 1 f%5. 2 f' % (7. 86, 6. 2)) ##7. 9#6. 20 Slide #13 CPS 118 – Lesson #12 – Introduction to Python

Arithmetic Operators The arithmetic operators + - * / are the same as in

Arithmetic Operators The arithmetic operators + - * / are the same as in MATLAB. Exponentiation is ** (instead of ^). They can form expressions as in MATLAB. x = 7 y = 8 Notice the comma and the absence of placeholders! print('x + y = ', x+y) x + y = 15 print('x - y = ', x-y) x – y = -1 print('x * y = ', x*y) x * y = 56 print('x / y = ', x/y) x / y = 0. 875 print('x raised to the power of y = ', x**y) x raised to the power of y = 5764801 Slide #14 CPS 118 – Lesson #12 – Introduction to Python

Arithmetic Operators Two additional operations are modulo % (like the rem command in MATLAB)

Arithmetic Operators Two additional operations are modulo % (like the rem command in MATLAB) and integer division //. Notice that n is a new line like in MATLAB. m = 19 n = 8 print("nm and n are", m, n) print("the remainder of x divided by y is ", m%n) print("the number of times y goes into x is ", m//n) m and n are 19 8 the remainder of x divided by y is 3 the number of times y goes into x is 2 Slide #15 CPS 118 – Lesson #12 – Introduction to Python

Operator Precedence The rules are the same as in MATLAB. The only difference is

Operator Precedence The rules are the same as in MATLAB. The only difference is the exponentiation operator (**) that is evaluated from right-to-left instead of MATLAB’s (^) left-to-right evaluation. In Python: 2 ** 3 ** 2 gives 512 In MATLAB: 2 ^ 3 ^ 2 gives 64 Slide #16 CPS 118 – Lesson #12 – Introduction to Python

Arrays in Python: Lists, Tuples In Python, arrays are represented in two ways: with

Arrays in Python: Lists, Tuples In Python, arrays are represented in two ways: with Lists and Tuples. List are "mutable", that is their elements can be changed. Tuples are "immutable", their elements are unchangeable. Let’s see lists first. List elements have indexes like an array (MATLAB vector) but start at 0 instead of 1 (as for most languages other than MATLAB). zoo = [ 'lions', 'tigers', 'elephants' ] numbers = [ -3, 6, 8, 22, -318, 8 ] mixed = [ 'monkeys', 7, 12, 'gorillas' ] Slide #17 See? Just like MATLAB vectors! CPS 118 – Lesson #12 – Introduction to Python

Arrays in Python: Lists Just as with a MATLAB array, you can access one

Arrays in Python: Lists Just as with a MATLAB array, you can access one element or more of a list. zoo = [ 'lions', 'tigers', 'elephants' ] numbers = [ -3, 6, 8 , 22, -318, 8 ] mixed = [ 'monkeys', 7, 12, 'gorillas' ] print (mixed[0]) monkeys print (mixed [2], mixed [0]) 12 monkeys zoo[2] = 'hippopotami' You can also print (zoo) ['lions', 'tigers', 'hippopotami'] Slide #18 assign a single element. CPS 118 – Lesson #12 – Introduction to Python

Arrays in Python: List Operations Just as with a MATLAB vector, you can access

Arrays in Python: List Operations Just as with a MATLAB vector, you can access just a part of a list (known as slicing the list). Unlike MATLAB, however, it does not include the upper range index. Indexes start at 0, remember? numbers = [ -3, 6, 8 , 22, -318, 8 ] print(numbers[2: 5]) print(numbers[4: ]) print(numbers[: 3]) Slide #19 [8, 22, -318] [-318, 8] [-3, 6, 8] CPS 118 – Lesson #12 – Introduction to Python

Object Orientation You can also append (add on) to a list, but need a

Object Orientation You can also append (add on) to a list, but need a new concept: Object-Orientation. A list variable is known as an object in Python. Variables zoo, numbers, mixed seen before are three objects. We call them list objects because they are all lists. In Python, with Object-Orientation you make objects DO THINGS; but ONLY things they know how to do. What an object knows how to do, comes from its class: zoo, numbers, and mixed are all list objects and get what they can do from their common list class. Slide #20 CPS 118 – Lesson #12 – Introduction to Python

Appending to a List mammal_list = ['cow', 'horse', 'goat', 'sheep'] One thing a list

Appending to a List mammal_list = ['cow', 'horse', 'goat', 'sheep'] One thing a list can do is append to itself (add an element to its right hand end) To do this we need to use the append method of the list class. mammal_list. append('hippopotamus') Notice the dot! Maybe you want an hippopotamus for Christmas? goo. gl/dz. Vfv. V print(mammal_list) ['cows', 'horse', 'goat', 'sheep', 'hippopotamus'] Slide #21 CPS 118 – Lesson #12 – Introduction to Python

Other List Operations bird_list = ['robin', 'sparrow', 'jay', 'cardinal'] bird_list. insert(1, 'duck') print (bird_list)

Other List Operations bird_list = ['robin', 'sparrow', 'jay', 'cardinal'] bird_list. insert(1, 'duck') print (bird_list) ['robin', 'duck', 'sparrow', 'jay', 'cardinal'] del bird_list[2] the insert method: Inserts duck after item #1 (remember numbering starts at 0) the del operator deletes bird #2 print (bird_list) ['robin', 'duck', 'jay', 'cardinal'] bird_list. remove('cardinal') ['robin', 'duck', 'jay'] the remove method: removes cardinal from the list Can you spot the methods? Look at the previous slide for the hint. Slide #22 CPS 118 – Lesson #12 – Introduction to Python

More List Operations There are methods, which like for MATLAB arrays, perform operations on

More List Operations There are methods, which like for MATLAB arrays, perform operations on entire lists: fish_list = ['trout', 'bass', 'tuna', 'mackerel'] fish_list. sort( ); print (fish_list) ['bass', 'mackerel', 'trout', 'tuna'] fish_list. reverse(); print (fish_list) ['tuna', 'trout', 'mackerel', 'bass'] print (len(fish_list)) 4 print (min(fish_list)); print (max(fish_list)); Slide #23 sorts the list in alphabetical order reverses the list order length of the list (# of elements) bass tuna Can you spot which are methods and which are functions on this slide? CPS 118 – Lesson #12 – Introduction to Python

Lists of Lists (2 -D Arrays) You can create a two dimensional array (a

Lists of Lists (2 -D Arrays) You can create a two dimensional array (a matrix) by having lists as the elements of another list. It is not really a matrix at all but a list of lists, which is similar. mammal_list = ['cow', 'horse', 'goat', 'sheep'] fish_list = ['trout', 'bass', 'tuna', 'mackerel'] bird_list = ['robin', 'sparrow', 'jay', 'cardinal', 'owl'] creatures_list = [mammal_list, fish_list] print(creatures_list) [['cow', 'horse', 'goat', 'sheep'], ['trout', 'bass', 'tuna', 'mackerel']] kind of like a 2 x 4 matrix! Rows of different sizes are ok! creatures_list 2 = [mammal_list, fish_list, bird_list] print(creatures_list 2) [['cow', 'horse', 'goat', 'sheep'], ['trout', 'bass', 'tuna', 'mackerel'], ['robin', 'sparrow', 'jay', 'cardinal', 'owl']] Accessing an element is similar to what is done in MATLAB: print(creatures_list 2[2][4]) remember index counting starts at 0! owl Slide #24 CPS 118 – Lesson #12 – Introduction to Python

Tuples are created like lists except they are defined with parentheses instead of square

Tuples are created like lists except they are defined with parentheses instead of square brackets. Tuples exist for much faster execution in some situations. crustacean_tuple = ('shrimp', 'lobster', 'crab') A tuple is like a list except that it is immutable; elements cannot be changed nor can the tuple be extended. print(crustacean_tuple[1]) lobster crustacean_tuple[1] = 'barnacle' Type. Error: 'tuple' object does not support item assignment crustacean_tuple. append('barnacle') Attribute. Error: 'tuple' object has no attribute 'append' Simply means that there is no append method for tuples. Slide #25 CPS 118 – Lesson #12 – Introduction to Python

Dictionaries A structure found in many programming languages is the dictionary. Dictionaries are also

Dictionaries A structure found in many programming languages is the dictionary. Dictionaries are also known as maps, hashes, and associative arrays. A dictionary is composed of pairs of identifiers, a key identifier separated from its corresponding value identifier by a colon (: ). Key-value pairs are separated by commas (, ) all enclosed in curly braces { }. The usual way to use these is to specify the key identifier and get the corresponding value identifier. A sample dictionary: zoo = { 'jay' : 'bird' , 'cow' : 'mammal' , 'robin' : 'bird' , 'bass' : 'fish' , 'sheep' : 'mammal' } Slide #26 CPS 118 – Lesson #12 – Introduction to Python

Dictionaries A common use: tiger = { 'name' : 'tiger' , 'latin_name' : 'panthera

Dictionaries A common use: tiger = { 'name' : 'tiger' , 'latin_name' : 'panthera tigris' , 'origin' : 'India' , 'status' : 'endangered'} With this, a key can be given and the corresponding value is the result. The value can also be obtained with the get method. print(tiger['origin']) India print(tiger. get('status')) endangered Prints all the keys print(tiger. keys()) dict_keys(['name', 'latin_name', 'origin', 'status']) Slide #27 CPS 118 – Lesson #12 – Introduction to Python

String Methods The string class has several built-in methods that can be applied to

String Methods The string class has several built-in methods that can be applied to change case, located offsets of substrings, substitute characters in a string, check the type (alphabetic, numeric, alphanumeric), and remove blanks. str = "this is my string" print(str. capitalize( )) print(str. isalnum( )) print(str. replace("is", "are")) print(str. find('my')) str_list = str. split(" ") print(str_list) str_list = str. split("is") print(str_list) Slide #28 THIS IS MY STRING False Thare my string 8 ['this', 'my', 'string'] ['th', ' my string'] CPS 118 – Lesson #12 – Introduction to Python

Using Files - Writing Like MATLAB: open the file, write to / read from

Using Files - Writing Like MATLAB: open the file, write to / read from the file, close the file. Write to a new file: Modes are ‘r’, ‘w’, or ‘a’ like in MATLAB. fid = open('data. txt', 'w') distance = 8000 distance = distance / 2 fid. write('%d' % distance) fid. close( ) Slide #29 Puts 4000 in the file. (Same syntax as Python’s print command) CPS 118 – Lesson #12 – Introduction to Python

Using Files - Reading Like MATLAB, you can, of course, read data from an

Using Files - Reading Like MATLAB, you can, of course, read data from an existing file. You can read characters, lines, and even the whole file at once. fid = open('data. txt', 'r') print (fid. read (5)) #reads/prints 5 characters rec = fid. readline () #line into rec variable all 2 = fid. readlines() #whole file into all 2 list. fid. close() Note: all = fid. read () would read the whole file into a string named all. Slide #30 CPS 118 – Lesson #12 – Introduction to Python

Control Structures – Comparison and Logic Operators They are the same as in MATLAB

Control Structures – Comparison and Logic Operators They are the same as in MATLAB and any other language: sequence, selection (branch), and repetition (loop). Relational operators are the same as MATLAB’s: <, <=, >, >=, == plus two more: in, and not in. in checks if a value is part of a list or tuple, and not in checks if a value is absent from a list or tuple. Note that not equal is != instead of ~=. print('palm' in ['fir', 'pine', 'spruce']) print('palm' not in ['fir', 'pine', 'spruce']) print('Rigel' in ('Rigel', 'Sirius', 'Antares')) False True Logic operators work the same as in MATLAB but use keywords instead of symbols: and, or, not. Slide #31 CPS 118 – Lesson #12 – Introduction to Python

Selection The if statement works the same way as in MATLAB except the syntax

Selection The if statement works the same way as in MATLAB except the syntax is a bit different and there is no end keyword (indentation is used instead). if temp >= 100 : print ('WARNING! Boiling watern') if temp >= 20 : print ('Temperature is warm. n') else : print ('Temperature is cool. n') print ('Let's put a jacket on. n') One alternative Two alternatives print ('Not indented means not part of the if') Slide #32 CPS 118 – Lesson #12 – Introduction to Python

Selection – Nested ifs As in MATLAB, we can use nested ifs if we

Selection – Nested ifs As in MATLAB, we can use nested ifs if we have more than two alternatives. temperature = 28 if temperature < 15 : print('It is cold') elif temperature > 20 : print('It is warm') NOTE: Python: elif MATLAB: elseif else : print('It is moderate') print('This statement is not in the branch!') Slide #33 CPS 118 – Lesson #12 – Introduction to Python

Loops: Counting Loops For counting loops, Python uses the for statement. Very similar to

Loops: Counting Loops For counting loops, Python uses the for statement. Very similar to MATLAB’s for-end command. for x in range(1, 10) : print(x) Upper range not included. Goes from 1 to 9. for x in range(1, 10) : print(x, ' ', end=' ') No end keyword, we use indentation. Slide #34 Just inserts spacing between values, could have used a formatted placeholder as well. Unlike MATLAB’s, Python’s print command automatically adds a n at the end. This is to suppress it. CPS 118 – Lesson #12 – Introduction to Python

Loops: while Statement For loops with an undetermined number of iterations, Python uses the

Loops: while Statement For loops with an undetermined number of iterations, Python uses the while statement. Very similar to MATLAB’s while-end command. n=7 while n >= 0 : print(n, ' ', end=' ') n=n-1 Initialization Condition Body Update No end keyword, we use indentation. Slide #35 6 5 4 3 2 1 0 CPS 118 – Lesson #12 – Introduction to Python

Sentinel Controlled Loop An example of a sentinel controlled loop that calculates the average

Sentinel Controlled Loop An example of a sentinel controlled loop that calculates the average of all values entered: sum = 0; c = 0; n = float (input("Enter a value: ")) while n != -999 : sum = sum + n # sums the values c=c+1 # counts the values n = float (input("Enter a value: ")) Input statement reads values as strings, need to convert to float (could use int as well). average = sum / c print ('The average is: %f. n' % average) Slide #36 CPS 118 – Lesson #12 – Introduction to Python

List Comprehension You can use a for loop to create a list dynamically. mylist

List Comprehension You can use a for loop to create a list dynamically. mylist 1 = [] #create an empty list for k in range (1, 10) : mylist 1. append (k) print (mylist 1) [1, 2, 3, 4, 5, 6, 7, 8, 9] An easier way to create a list is called list comprehension. It mimics a mathematician's syntax for comprehending (seeing/understanding) what goes into creating a list. mylist 2 = [ (x) for x in range (1, 10) ] print (mylist 2) [1, 2, 3, 4, 5, 6, 7, 8, 9] Easier to read! "mylist 2 is a list of all x, for x in the range 1 to 9" Slide #37 CPS 118 – Lesson #12 – Introduction to Python

Selective List Comprehension The list comprehension form also allows a much simpler way of

Selective List Comprehension The list comprehension form also allows a much simpler way of having a selection inside a loop: my_list = [ ( x ) for x in range(1, 10) if x%2 == 0] print(my_list) [2, 4, 6, 8] This reads as: "my_list is a list of all x, for x in the range 1 to 9, if x is even" As you see, a lot shorter than the for loop version: my_list = [] for k in range (1, 10) : if k %2 == 0: my_list. append (k) print(my_list) Slide #38 CPS 118 – Lesson #12 – Introduction to Python

Functions To define a function in Python the def keyword is used. def twice

Functions To define a function in Python the def keyword is used. def twice (x, y) : print(2 * x) print(2 * y) return (2 *x + 2 * y) print (twice (7, 8)) 14 16 30 Slide #39 CPS 118 – Lesson #12 – Introduction to Python

Functions Another well known example that combines a function with a sentinel loop. It

Functions Another well known example that combines a function with a sentinel loop. It keeps converting miles to kilometers until the user enters -1. def mk (m) : k = m * 1. 61 return (k) distm = int (input('Enter a distance: ')) while distm != -1 : distk = mk (distm) print ('%d miles is %d kilometers. n' % (distm, distk)) distm = int (input('Enter a distance: ')) Slide #40 CPS 118 – Lesson #12 – Introduction to Python

Functions Like in MATLAB, you can have a function that returns multiple results. In

Functions Like in MATLAB, you can have a function that returns multiple results. In Python, the easiest way is to return a tuple (you could also return a list or a dictionary). Let’s see a Python version of this example already seen in MATLAB. def ftokc (f) : c = (f - 32) * 5/9 k = c + 273. 15 return (k, c) Remember tuples have round parentheses! fahrenheit = float (input('Temperature in Fahrenheit: ')) (kelvin, celcius) = ftokc (fahrenheit) print ('%. 1 f F is %. 1 f K and %. 1 f C. n' % (fahrenheit, kelvin, celcius)) Slide #41 CPS 118 – Lesson #12 – Introduction to Python

Slide #42 CPS 118 – Lesson #12 – Introduction to Python

Slide #42 CPS 118 – Lesson #12 – Introduction to Python