introduction to the python programming

42
Slide #1 CPS118 – Lesson #12 – Introduction to Python Introduction to the Python Programming Language Lesson #12

Upload: others

Post on 18-Mar-2022

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to the Python Programming

Slide #1 CPS118 – Lesson #12 – Introduction to Python

Introduction to the Python Programming

Language

Lesson #12

Page 2: Introduction to the Python Programming

Slide #2 CPS118 – Lesson #12 – Introduction to Python

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)

Page 3: Introduction to the Python Programming

Slide #3 CPS118 – Lesson #12 – Introduction to Python

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/b1jUsH

Page 4: Introduction to the Python Programming

Slide #4 CPS118 – Lesson #12 – Introduction to Python

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

Page 5: Introduction to the Python Programming

Slide #5 CPS118 – Lesson #12 – Introduction to Python

• 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>>>

Python Interactive Mode

Page 6: Introduction to the Python Programming

Slide #6 CPS118 – Lesson #12 – Introduction to Python

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

>>> x = 3 + 4

• To output the value in x type:

>>> print(x)

7

>>>

Python Variables

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!

Page 7: Introduction to the Python Programming

Slide #7 CPS118 – Lesson #12 – Introduction to Python

• 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!):y = 3 + 5print (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.

Python Batch Mode

or y = 3 + 5; print (y) Unlike in MATLAB the semi-colon doesn’t suppress output but is a delimiter between statements to put multiple statements on the same line.

Page 8: Introduction to the Python Programming

Slide #8 CPS118 – Lesson #12 – Introduction to Python

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).

Import sys

Page 9: Introduction to the Python Programming

Slide #9 CPS118 – Lesson #12 – Introduction to Python

• 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 xpow (x,y): x to the power of yceil (x), floor(x), sqrt(x), sin(x), cos(x): like MATLAB and a few more

• Like in MATLAB, pi and e are also predefined.

Python Functions

Page 10: Introduction to the Python Programming

Slide #10 CPS118 – Lesson #12 – Introduction to Python

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)

Data Types and Variables

Page 11: Introduction to the Python Programming

Slide #11 CPS118 – Lesson #12 – Introduction to Python

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

Simple Strings

Page 12: Introduction to the Python Programming

Slide #12 CPS118 – Lesson #12 – Introduction to Python

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?

Print statement

Page 13: Introduction to the Python Programming

Slide #13 CPS118 – Lesson #12 – Introduction to Python

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('%.3f' % 7.8) 7.800

print('%9.3f' % 7.8) ####7.800

print('%5.1f' % 7.86) ##7.9

x = 'hello ' + 'how are you'

print(x) hello how are you

print('%5.1f%5.2f' % (7.86, 6.2))

##7.9#6.20

Formatted print statement

Page 14: Introduction to the Python Programming

Slide #14 CPS118 – Lesson #12 – Introduction to Python

The arithmetic operators + - * / are the same as in MATLAB. Exponentiation is ** (instead of ^). They can form expressions as in MATLAB.

x = 7

y = 8

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

Arithmetic Operators

Notice the comma and the absence of placeholders!

Page 15: Introduction to the Python Programming

Slide #15 CPS118 – Lesson #12 – Introduction to Python

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 8the remainder of x divided by y is 3the number of times y goes into x is 2

Arithmetic Operators

Page 16: Introduction to the Python Programming

Slide #16 CPS118 – Lesson #12 – Introduction to Python

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

Operator Precedence

Page 17: Introduction to the Python Programming

Slide #17 CPS118 – Lesson #12 – Introduction to Python

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' ]

Arrays in Python: Lists, Tuples

See? Just like MATLAB vectors!

Page 18: Introduction to the Python Programming

Slide #18 CPS118 – Lesson #12 – Introduction to Python

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]) monkeysprint (mixed [2], mixed [0]) 12 monkeyszoo[2] = 'hippopotami'print (zoo)

['lions', 'tigers', 'hippopotami']

Arrays in Python: Lists

You can also assign a single element.

Page 19: Introduction to the Python Programming

Slide #19 CPS118 – Lesson #12 – Introduction to Python

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.

numbers = [ -3, 6, 8 , 22, -318, 8 ]

print(numbers[2:5]) [8, 22, -318]print(numbers[4:]) [-318, 8]print(numbers[:3]) [-3, 6, 8]

Arrays in Python: List Operations

Indexes start at 0, remember?

Page 20: Introduction to the Python Programming

Slide #20 CPS118 – Lesson #12 – Introduction to Python

● 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.

Object Orientation

Page 21: Introduction to the Python Programming

Slide #21 CPS118 – Lesson #12 – Introduction to Python

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')

print(mammal_list)['cows', 'horse', 'goat', 'sheep', 'hippopotamus']

Appending to a List

Notice the dot!

Maybe you want an hippopotamus for Christmas?goo.gl/dzVfvV

Page 22: Introduction to the Python Programming

Slide #22 CPS118 – Lesson #12 – Introduction to Python

bird_list = ['robin', 'sparrow', 'jay', 'cardinal']

bird_list.insert(1, 'duck')

print (bird_list)

['robin', 'duck', 'sparrow', 'jay', 'cardinal']

del bird_list[2]

print (bird_list)

['robin', 'duck', 'jay', 'cardinal']

bird_list.remove('cardinal')

['robin', 'duck', 'jay']

Other List Operations

the insert method: Inserts duck after item #1 (remember numbering starts at 0)

the del operator deletes bird #2

the remove method: removes cardinal from the list

Can you spot the methods? Look at the previous slide for the hint.

Page 23: Introduction to the Python Programming

Slide #23 CPS118 – Lesson #12 – Introduction to Python

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)); bassprint (max(fish_list)); tuna

More List Operations

sorts the list in alphabetical order

reverses the list order

length of the list (# of elements)

Can you spot which are methods and which are functions on this slide?

Page 24: Introduction to the Python Programming

Slide #24 CPS118 – Lesson #12 – Introduction to Python

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']]

creatures_list2 = [mammal_list, fish_list, bird_list]print(creatures_list2)[['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_list2[2][4])owl

Lists of Lists (2-D Arrays)

kind of like a 2 x 4 matrix!

remember index counting starts at 0!

Rows of different sizes are ok!

Page 25: Introduction to the Python Programming

Slide #25 CPS118 – Lesson #12 – Introduction to Python

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'TypeError: 'tuple' object does not support item assignment

crustacean_tuple.append('barnacle')AttributeError: 'tuple' object has no attribute 'append'

Tuples

Simply means that there is no append method for tuples.

Page 26: Introduction to the Python Programming

Slide #26 CPS118 – Lesson #12 – Introduction to Python

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' }

Dictionaries

Page 27: Introduction to the Python Programming

Slide #27 CPS118 – Lesson #12 – Introduction to Python

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

print(tiger.keys())dict_keys(['name', 'latin_name', 'origin', 'status'])

Dictionaries

Prints all the keys

Page 28: Introduction to the Python Programming

Slide #28 CPS118 – Lesson #12 – Introduction to Python

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( )) THIS IS MY STRINGprint(str.isalnum( )) Falseprint(str.replace("is", "are")) Thare are my stringprint(str.find('my')) 8

str_list = str.split(" ")print(str_list) ['this','is','my','string']str_list = str.split("is") print(str_list) ['th', ' ', ' my string']

String Methods

Page 29: Introduction to the Python Programming

Slide #29 CPS118 – Lesson #12 – Introduction to Python

Using Files - Writing

Like MATLAB: open the file, write to / read from the file, close the file.

Write to a new file:

fid = open('data.txt', 'w')

distance = 8000distance = distance / 2fid.write('%d' % distance)fid.close( )

Modes are ‘r’, ‘w’, or ‘a’ like in MATLAB.

Puts 4000 in the file. (Same syntax as Python’s print command)

Page 30: Introduction to the Python Programming

Slide #30 CPS118 – Lesson #12 – Introduction to Python

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 charactersrec = fid.readline () #line into rec variableall2 = fid.readlines() #whole file into all2 list.fid.close()

Note: all = fid.read () would read the whole file into a string named all.

Page 31: Introduction to the Python Programming

Slide #31 CPS118 – Lesson #12 – Introduction to Python

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']) Falseprint('palm' not in ['fir', 'pine', 'spruce']) Trueprint('Rigel' in ('Rigel', 'Sirius', 'Antares')) True

● Logic operators work the same as in MATLAB but use keywords instead of symbols: and, or, not.

Page 32: Introduction to the Python Programming

Slide #32 CPS118 – Lesson #12 – Introduction to Python

SelectionThe 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 water\n')

if temp >= 20 : print ('Temperature is warm.\n')else : print ('Temperature is cool.\n') print ('Let\'s put a jacket on.\n')

print ('Not indented means not part of the if')

One alternative

Two alternatives

Page 33: Introduction to the Python Programming

Slide #33 CPS118 – Lesson #12 – Introduction to Python

Selection – Nested ifsAs in MATLAB, we can use nested ifs if we have more than two alternatives.

temperature = 28if temperature < 15 : print('It is cold')

elif temperature > 20 : print('It is warm')

else : print('It is moderate')

print('This statement is not in the branch!')

NOTE:Python: elifMATLAB: elseif

Page 34: Introduction to the Python Programming

Slide #34 CPS118 – Lesson #12 – Introduction to Python

Loops: Counting LoopsFor counting loops, Python uses the for statement. Very similar to MATLAB’s for-end command.

for x in range(1,10) : print(x)

for x in range(1,10) : print(x, ' ', end=' ')

Unlike MATLAB’s, Python’s print command automatically adds a \n at the end. This is to suppress it.

Just inserts spacing between values, could have used a formatted placeholder as well.

Upper range not included. Goes from 1 to 9.

No end keyword, we use indentation.

Page 35: Introduction to the Python Programming

Slide #35 CPS118 – Lesson #12 – Introduction to Python

Loops: while StatementFor loops with an undetermined number of iterations, Python uses the while statement. Very similar to MATLAB’s while-end command.

n = 7while n >= 0 : print(n, ' ', end=' ') n = n - 1

Initialization

Condition

Body

Update

No end keyword, we use indentation.

6 5 4 3 2 1 0

Page 36: Introduction to the Python Programming

Slide #36 CPS118 – Lesson #12 – Introduction to Python

Sentinel Controlled LoopAn 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: "))

average = sum / c

print ('The average is: %f.\n' % average)

Input statement reads values as strings, need to convert to float (could use int as well).

Page 37: Introduction to the Python Programming

Slide #37 CPS118 – Lesson #12 – Introduction to Python

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

mylist1 = [] #create an empty listfor k in range (1, 10) : mylist1.append (k)print (mylist1)[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.

mylist2 = [ (x) for x in range (1, 10) ]print (mylist2)[1, 2, 3, 4, 5, 6, 7, 8, 9] Easier to read!

"mylist2 is a list of all x, for x in the range 1 to 9"

Page 38: Introduction to the Python Programming

Slide #38 CPS118 – Lesson #12 – Introduction to Python

Selective List ComprehensionThe 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)

Page 39: Introduction to the Python Programming

Slide #39 CPS118 – Lesson #12 – Introduction to Python

FunctionsTo 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))

141630

Page 40: Introduction to the Python Programming

Slide #40 CPS118 – Lesson #12 – Introduction to Python

FunctionsAnother 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: '))

Page 41: Introduction to the Python Programming

Slide #41 CPS118 – Lesson #12 – Introduction to Python

FunctionsLike 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)

fahrenheit = float (input('Temperature in Fahrenheit: '))(kelvin, celcius) = ftokc (fahrenheit)print ('%.1f F is %.1f K and %.1f C.\n' % (fahrenheit, kelvin, celcius))

Remember tuples have round parentheses!

Page 42: Introduction to the Python Programming

Slide #42 CPS118 – Lesson #12 – Introduction to Python