0% found this document useful (0 votes)
95 views

Python Mod1 PPT

Uploaded by

adfqadsf
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views

Python Mod1 PPT

Uploaded by

adfqadsf
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 141

Python

Programming

1
Welcome
To
Python Programming

2
Course Objectives
 To Learn Syntax and Semantics and create Functions
in Python.
 To Handle Strings and Files in Python.
 To Understand Lists, Dictionaries and Regular
expressions in Python.
 To Implement Object Oriented Programming
concepts in Python
 To Build Web Services and Introduction to Network
Programming in Python.

3
Course Outcomes
 CO1: Examine Python syntax and semantics and be fluent in the
use of Python flow control and functions.
 CO2: Demonstrate proficiency in handling Strings and File
Systems.
 CO3: Create, run and manipulate Python Programs using core data
structures like Lists, Dictionaries and use Regular Expressions.
 CO4: Interpret the concepts of Object-Oriented Programming as
used in Python.
 CO5: Implement exemplary applications related to Network
Programming and Web Services in Python.

4
Course Textbook
 Charles R. Severance, “Python for Everybody:
Exploring Data Using Python 3”, 1st Edition,
CreateSpace Independent Publishing Platform, 2016.
(http://do1.dr-chuck.com/pythonlearn/EN_us/pythonlear
n.pdf )
 Allen B. Downey, "Think Python: How to Think
Like a Computer Scientist, 2nd Edition, Green Tea
Press, 2015.
(http://greenteapress.com/thinkpython2/thinkpython2.p
df)

5
Class Format
 Lots of Code to Write (You and Me).
 Keep a Separate Book. You need to check the
contents back and forth as Class progresses.
 You need to make note of points written on slides
 Q & A sessions at the end of each chapter.
 This gives you confidence to face campus
interviews.

6
Pre-Requisite: Please Install Python
Unit 1 Review
 Why should you learn to write programs
 Variables, expressions and statements
 Conditional execution
 Functions

8
Computers want to be helpful...
What
• Computers are built for one purpose Next?
- to do things for us
• But we need to speak their language
to describe what we want done
• Users have it easy - someone already
What What What
put many different programs Next? Next? Next?
(instructions) into the computer and
users just pick the ones we want to What What What
Next? Next? Next?
use
Users .vs. Programmers
 Users see computers as a set of tools - word
processor, spreadsheet, map, todo list, etc.
 Programmers learn the computer “ways” and the
computer language
 Programmers have some tools that allow them to
build new tools
 Programmers sometimes write tools for lots of
users and sometimes programmers write little
“helpers” for themselves to automate a task
Why be a programer?
• To get some task done - we are the user and
programmer
• Clean up survey data
• To produce something for others to use - a
programming job
• Fix a performance problem in the software
• Add guestbook to a web site
What is Code? Software? A Program?
• A sequence of stored instructions
• It is a little piece of our intelligence in the computer
• It is a little piece of our intelligence we can give to
others - we figure something out and then we encode
it and then give it to someone else to save them the
time and energy of figuring it out
• A piece of creative art - particularly when we do a
good job on user experience
Hardware Architecture
http://upload.wikimedia.org/wikipedia/commons/3/3d/RaspberryPi.jpg
Generic
Software What
Next? Computer
Input Central
and Output Processing
Devices Unit
Secondary
Memory

Main
Memory
Definitions
What
 Central Processing Unit: Runs the Program - The CPU is Next?
always wondering “what to do next”? Not the brains
exactly - very dumb but very very fast
 Input Devices: Keyboard, Mouse, Touch Screen
 Output Devices: Screen, Speakers, Printer, DVD Burner
 Main Memory: Fast small temporary storage - lost on reboot
- aka RAM
 Secondary Memory: Slower large permanent storage - lasts
until deleted - disk drive / memory stick
Generic
Software What
Next? Computer
Input Central
and Output Processing
Devices Unit
Secondary
if x< 3: print Memory

Main
Memory
Software What
Next?

Input Central
and Output Processing
Devices Unit
Secondary
01001001 Memory
00111001

Main
Memory

Machine
Language
Totally Hot CPU
What
Next?

http://www.youtube.com/watch?v=y39D4529FM4
Hard Disk in Action

http://www.youtube.com/watch?v=9eMWG3fwiEU
Python as a Language
Python is the language of the Python Interpreter
and those who can converse with it. An
individual who can speak Python is known as a
Pythonista. It is a very uncommon skill, and may
be hereditary. Nearly all known Pythonistas use
software inititially developed by Guido van
Rossum.
Early Learner: Syntax Errors
 We need to learn the Python language so we can communicate
our instructions to Python. In the beginning we will make lots
of mistakes and speak gibberish like small children.
 When you make a mistake, the computer does not think you
are “cute”. It says “syntax error” - given that it *knows* the
language and you are just learning it. It seems like Python is
cruel and unfeeling.
 You must remember that *you* are intelligent and *can* learn
- the computer is simple and very fast - but cannot learn - so it
is easier for you to learn Python than for the computer to learn
English...
Talking to Python
csev$ python
Python 3.5.2 |Anaconda 4.1.1 (64-bit)|(default, Jul 5 2016, 11:41:13)
[MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
What next?
csev$ python
Python 3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul 5 2016, 11:41:13)
[MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> x = 1
>>> print(x)
1
>>> x = x + 1
>>> print(x)
2 This is a good test to make sure that you have
>>> exit() Python correctly installed. Note that quit() also
works to end the interactive session.
Lets Talk to Python...
Elements of Python
• Vocabulary / Words - Variables and Reserved
words
• Sentence structure - valid syntax patterns
Reserved Words
• You can not use reserved words as variable names /
identifiers

and del for is raise assert elif


from lambda return break else
global not try class except if or
while continue exec import pass
yield def finally in print
Sentences or Lines

x=2 Assignment Statement


x=x+2 Assignment with expression
print(x) Print statement

Variable Operator Constant Reserved Word


Programming Paragraphs
Python Scripts
 InteractivePython is good for experiments and
programs of 3-4 lines long
 But most programs are much longer so we type
them into a file and tell python to run the
commands in the file.
 In a sense we are “giving Python a script”
 As convention, we add “.py” as the suffix on the
end of these files to indicate they contain Python
Writing a Simple Program
Interactive versus Script
• Interactive
• You type directly to Python one line at a time and it
responds
• Script
• You enter a sequence of statements (lines) into a file
using a text editor and tell Python to execut the
statements in the file
Program Steps or Program Flow
• Like a recipe or installation instructions, a
program is a sequence of steps to be done in order
• Some steps are conditional - they may be skipped
• Sometimes a step or group of steps are to be
repeated
• Sometimes we store a set of steps to be used over
and over as needed several places throughout the
program
Sequential Steps
x=1 Program:
Output:
print(x) x=2
print(x) 2
x=x+1 x=x+2 4
print(x)
print(x)

When a program is running, it flows from one step to the next. We as


programmers set up “paths” for the program to follow.
Conditional Steps
x=5

Yes
X < 10 ?
Program:
print('Smaller‘) Output:
x=5
if x < 10: Smaller
Yes print('Smaller’)
X > 20 ? Finish
if x > 20:
print('Bigger‘) print('Bigger‘)

print('Finish‘)
print('Finish‘)
Variables, Expressions, and Statements
 Fixed values such as numbers, letters, and strings are
Constants
called “constants” - because their value does not change
 Numeric constants are as you expect
 String constants use single-quotes (')
or double-quotes (")

>>> print(123)
123
>>> print(98.6)
98.6
>>> print(‘Hello world‘)
Hello world
 A variable is a named place in the memory where a programmer can
Variables
store data and later retrieve the data using the variable “name”
 Programmers get to choose the names of the variables
 You can change the contents of a variable in a later statement

x = 12.2 x 12.2 100


y = 14
x = 100 y 14
Python Variable Name Rules
• Must start with a letter or underscore _
• Must consist of letters and numbers and
underscores
• Case Sensitive
• Good: spam eggs spam23 _speed
• Bad: 23spam #sign var.12
• Different: spam Spam SPAM
Reserved Words
• You can not use reserved words as variable names /
identifiers
and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print
Sentences or Lines

x=2 Assignment Statement


x=x+2 Assignment with expression
print(x) Print statement

Variable Operator Constant Reserved Word


Assignment Statements
• We assign a value to a variable using the assignment
statement (=)
• An assignment statement consists of an expression on the
right hand side and a variable to store the result

x = 3.9 * x * ( 1 - x )
A variable is a memory location x 0.6
used to store a value (0.6).

0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4

Right side is an expression. Once 0.93


expression is evaluated, the result
is placed in (assigned to) x.
A variable is a memory location
used to store a value. The value
stored in a variable can be updated x 0.6 0.93
by replacing the old value (0.6)
with a new value (0.93).

x = 3.9 * x * ( 1 - x )

Right side is an expression. Once


expression is evaluated, the result 0.93
is placed in (assigned to) the
variable on the left side (i.e. x).
Numeric Expressions
Operator Operation
 Because of the lack of
mathematical symbols on + Addition

computer keyboards - we use - Subtraction


“computer-speak” to express the * Multiplication
classic math operations
 Asterisk is multiplication / Division

 Exponentiation (raise to a power) ** Power

looks different from in math. % Remainder


Numeric Expressions

>>> xx = 2 >>> jj = 23 Operator Operation

>>> xx = xx + 2 >>> kk = jj % 5 + Addition

>>> print(xx) >>> print(kk) - Subtraction

4 3
* Multiplication
>>> yy = 440 * 12 >>> print(4 ** 3)
>>> print(yy) 64 / Division

** Power
5280 4R3
>>> zz = yy / 1000 5 23
% Remainder

>>> print(zz) 20
5.28
3
Order of Evaluation
 When we string operators together - Python must know
which one to do first
 This is called “operator precedence”
 Which operator “takes precedence” over the others

x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
• Highest precedence rule to lowest precedence rule
• Parenthesis are always respected
• Exponentiation (raise to a power)
Parenthesis
• Multiplication, Division, and Remainder
Power
• Addition and Subtraction Multiplication
• Left to right Addition
Left to Right
>>> x = 1 + 2 ** 3 / 4 * 5 1 + 2 ** 3 / 4 * 5
>>> print(x)
11 1+8/4*5
>>>
1+2*5

Parenthesis
Power 1 + 10
Multiplication
Addition
Left to Right
11
>>> x = 1 + 2 ** 3 / 4 * 5 1 + 2 ** 3 / 4 * 5
>>> print(x)
11 1+8/4*5
>>> Note 8/4 goes before 4*5 1+2*5
because of the left-right
rule.
Parenthesis 1 + 10
Power
Multiplication
Addition 11
Left to Right
Operator Precedence

Parenthesis
• Remember the rules top to bottom Power
Multiplication
• When writing code - use parenthesis Addition
Left to Right
• When writing code - keep mathematical expressions simple
enough that they are easy to understand
• Break long series of mathematical operations up to make them
more clear

Question: x = 1 + 2 * 3 - 4 / 5
Python Integer Division is Weird!
• Integer division yield float >>> print(10 / 2)
5.0
• Floating point division >>> print(9 / 2)
produces floating point 4.5
numbers >>> print(99 / 100)
0.99
>>> print(10.0 / 2.0)
5.0
>>> print(99.0 / 100.0)
0.99
• When you perform an >>> print(99 / 100)
Mixing Integer and Floating
operation where one 0.99
>>> print(99 / 100.0)
operand is an integer 0.99
and the other operand is >>> print(99.0 / 100)
a floating point the 0.99
result is a floating point >>> print 1 + 2 * 3 / 4.0 - 5
-2.5
>>>
 In Python variables, literals, >>> ddd = 1 + 4
What does “Type” Mean?
and constants have a “type”
 Python knows the difference
>>> print(ddd)
5
between an integer number and >>> eee = 'hello ' + 'there'
a string >>> print(eee)
 For example “+” means hellothere
“addition” if something is a
number and “concatenate” if
something is a string

concatenate = put together


Type Matters
 Python knows what “type”
everything is >>> eee = 'hello ' + 'there'
 Some operations are prohibited
>>> eee = eee + 1
Traceback (most recent call last):
 You cannot “add 1” to a string File "<stdin>", line 1, in <module>
 We can ask Python what type TypeError: Can't convert 'int' object
something is by using the to str implicitly
type() function. >>> type(eee)
<class 'str'>
>>> type('hello')
<class 'str'>
>>> type(1)
<class 'int'>
>>>
Several Types of Numbers
>>> xx = 1
• Numbers have two main types >>> type (xx)
• Integers are whole numbers: -14, -2, <class 'int'>
0, 1, 100, 401233 >>> temp = 98.6
• Floating Point Numbers have >>> type(temp)
decimal parts: -2.5 , 0.0, 98.6, 14.0 <class 'float'>
>>> type(1)
• There are other number types -
<class 'int'>
they are variations on float and >>> type(1.0)
integer <class 'float'>
>>>
Type Conversions
• When you put an integer >>> print(float(99) / 100)
and floating point in an 0.99
>>> i = 42
expression the integer is >>> type(i)
implicitly converted to a <class 'int'>
float >>> f = float(i)
• You can control this with >>> print(f)
42.0
the built in functions int() >>> type(f)
and float() <type 'float'>
>>> print(1 + 2 * float(3) / 4 – 5)
-2.5
>>>
String Conversions
>>> sval = '123'
>>> type(sval)
<class 'str'>
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
• You can also use int() TypeError: Can't convert 'int' object to str
and float() to convert implicitly
between strings and >>> ival = int(sval)
integers >>> type(ival)
<class 'int'>
• You will get an error if >>> print(ival + 1)
the string does not 124
contain numeric >>> nsv = 'hello bob'
>>> niv = int(nsv)
characters Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base
10: 'hello bob'
User Input
Even If you enter a
• We can instruct number input considers
it as string by default
Python to pause and
read data from the
user using the input >>>name = input(‘Who are you?’)
function Who are you? Chuck
>>>print('Welcome', name)
• The input function
Welcome Chuck
returns a string
Converting User Input

• If we want to read a
number from the user, >>>inp = input(‘Europe floor?’)
we must convert it Europe floor? 0
from a string to a >>>usf = int(inp) + 1
>>>print('US floor', usf)
number using a type
US floor 1
conversion function
• Later we will deal with
bad input data
Comments in Python
• Anything after a # is ignored by Python
• Why comment?
• Describe what is going to happen in a sequence of
code
• Document who wrote the code or other ancillary
information
• Turn off a line of code - perhaps temporarily
String Operations
 Some operators apply to strings
 + implies “concatenation” >>> print('abc' + '123’)
 * implies “multiple concatenation” abc123
 Python knows when it is dealing >>> print('Hi' * 5)
with a string or a number and HiHiHiHiHi
behaves appropriately >>>
Mnemonic Variable Names
 Since we programmers are given a choice in
how we choose our variable names, there is a bit
of “best practice”
 We name variables to help us remember what
we intend to store in them (“mnemonic” =
“memory aid”)
 This can confuse beginning students because
well named variables often “sound” so good that
they must be keywords
http://en.wikipedia.org/wiki/Mnemonic
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c=a*b
print(x1q3p9afd) print(c)

hours = 35.0
What is this rate = 12.50
code doing? pay = hours * rate
print(pay)
Exercise

Write a program to prompt the user for hours and rate


per hour to compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
Summary
• Type
• Resrved words
• Variables (mnemonic)
• Operators
• Operator precedence

• Integer Division
• Conversion between types
• User input
• Comments (#)
Conditional Execution
Conditional Steps
x=5

Yes
X < 10 ? Program:
print('Smaller‘) x=5 Output:
if x < 10:
print('Smaller’) Smaller
Yes
X > 20 ? Finish
if x > 20:
print('Bigger‘) print('Bigger‘)

print('Finish‘) print('Finish‘)
Comparison Operators

• Boolean expressions ask a


Python Meaning
question and produce a Yes or
< Less than
No result which we use to
<= Less than or Equal
control program flow
== Equal to
• Boolean expressions using
comparison operators evaluate >= Greater than or Equal
to - True / False - Yes / No > Greater than
• Comparison operators look at != Not equal
variables but do not change the
variables
Remember: “=” is used for assignment.

http://en.wikipedia.org/wiki/George_Boole
Comparison Operators
x=5
if x == 5 :
print('Equals 5‘)
if x > 4 :
print('Greater than 4’)
if x >= 5 : Equals 5
print('Greater than or Equal 5‘) Greater than 4
if x < 6 : Greater than or Equal 5
print('Less than 6‘) Less than 6
if x <= 5 : Less than or Equal 5
print('Less than or Equal 5’) Not equal 6
if x != 6 :
print('Not equal 6‘)
One-Way Decisions
x=5 Yes
print('Before 5’) X == 5 ?

if x == 5 :
Before 5 No print('Is 5‘)
print('Is 5’)
Is 5
print('Is Still 5’)
Is Still 5 print('Still 5‘)
print('Third 5’)
Third 5
print('Afterwards 5’)
Afterwards 5 print('Third 5‘)
print('Before 6’)
Before 6
if x == 6 :
Afterwards 6
print('Is 6’)
print('Is Still 6’)
print('Third 6’)
print('Afterwards 6‘)
Indentation
• Increase indent indent after an if statement or for
statement (after : )
• Maintain indent to indicate the scope of the block
(which lines are affected by the if/for)
• Reduce indent to back to the level of the if
statement or for statement to indicate the end of
the block
• Blank lines are ignored - they do not affect
indentation
• Comments on a line by themselves are ignored
w.r.t. indentation
increase / maintain after if or for
decrease to indicate end of block
blank lines and comment lines ignored
x=5
x=5 if x > 2 :
if x > 2 : # comments
print('Bigger than 2‘)
print('Still bigger‘) print(‘Bigger than 2’)
print('Done with 2‘) # don’t matter
print(‘Still bigger’)
# but can confuse you

print('Done with 2‘)


# if you don’t line
# them up
Nested Decisions
yes
x>1

no print(‘More than one’)


x = 42
yes
if x > 1 : x < 100

print(‘More than one’) no


if x < 100 : print(‘Less than 100’)

print(‘Less than 100’)

print 'All done'


print('All Done‘)
Nested Decisions
yes
x>1

no print('More than one‘)


x = 42
yes
if x > 1 : x < 100

print('More than one‘) no


if x < 100 : print('Less than 100‘)

print('Less than 100‘)

print 'All done'


print('All Done‘)
Nested Decisions
yes
x>1

no print('More than one‘)


x = 42
yes
if x > 1 : x < 100

print('More than one‘)


no
if x < 100 : print('Less than 100‘)

print('Less than 100‘)

print 'All done'


print('All Done‘)
Two Way Decisions
• Sometimes we want to
do one thing if a logical X=4
expression is true and
something else if the
expression is false no yes
x>2
• It is like a fork in the
road - we must choose
one or the other path print('Not bigger‘) print('Bigger‘)
but not both

print('All Done‘)
Two-way using else :

X=4

x=4 no yes
x>2

if x > 2 :
print('Smaller‘) print('Bigger‘)
print('Bigger‘)
else :
print('Smaller‘)
print('All Done‘)
print('All done‘)
Two-way using else :

X=4

x=4 no yes
x>2

if x > 2 :
print('Smaller‘) Print('Bigger‘)
print('Bigger‘)
else :
print('Smaller‘)
print('All Done‘)
print 'All done'
Multi-way

yes
x<2 print('Small‘)
if x < 2 :
no
print('Small‘)
elif x < 10 : yes
x<10 Print('Medium‘)
print('Medium‘) no
else:
print('LARGE‘) print('LARGE‘)
print('All done‘)

print('All Done‘)
Multi-way
X=0

yes
x<2 print('Small‘)
x=0 no
if x < 2 :
yes
print('Small‘) x<10 print('Medium‘)
elif x < 10 : no
print('Medium‘)
else : print('LARGE‘)
print('LARGE‘)
Print('All done‘)
print('All Done‘)
Multi-way
X=5

yes
x<2 print('Small‘)
x=5 no
if x < 2:
yes
print 'Small' x<10 print('Medium‘)
elif x < 10 : no
print('Medium‘)
else : print('LARGE‘)
print('LARGE‘)
print('All done‘)
print('All Done‘)
Multi-way
X = 20

yes
x<2 print('Small‘)
x = 20 no
if x < 2 :
yes
print('Small‘) x<10 print('Medium‘)
elif x < 10 : no
print('Medium‘)
else : print('LARGE‘)
print('LARGE‘)
Print('All done‘)
print('All Done‘)
Boolean Expressions
 A boolean expression is an expression that is either
true or false.
 The following examples use the operator == ,
which compares two operands and produces True
if they are equal and False otherwise:

8
6
Boolean Expressions
 Trueand False are special values that belong to the
type bool ; they are not strings:

8
7
Logical Operators
 There are three logical operators: and , or , and not . The semantics (meaning)
of these operators is similar to their meaning in English.
 For example, is true only if x is greater than 0
and less than 10.
 is true if either of the conditions is true,
that is, if the number is divisible by 2 or 3.
 the not operator negates a boolean expression a is true if x > y is
false, that is, if x is less than or equal to y
 Strictly speaking, the operands of the logical operators should be boolean
expressions, but Python is not very strict. Any nonzero number is interpreted
as “true.”

 a This flexibility can be


useful but confusing.
You might want to
avoid it

8
8
The try / except Structure
 Earlier we saw a code segment where we used the raw_input and int functions to read and parse an
integer number entered by the user.
 We also saw how treacherous doing this could be:
 When we are executing these statements in the Python interpreter (in interactive session), we get a
new prompt from the interpreter, think “oops” and move on to our next statement. However if this code is placed in
Traceback a Python script and this error
occurs, your script
immediately stops in its tracks
with a traceback. It does not
execute the following
statement.

 a

8
9
The try / except Structure
 Considera sample program to convert a
Fahrenheit temperature to a Celsius temperature:

 Ifwe execute this code and give it invalid input, it


simply fails with an unfriendly error message:
Invalid
Input

9
0
The try / except Structure
• There is a conditional execution structure built into Python to handle
these types of expected and unexpected errors called “try / except”.
• You surround a dangerous section of code with try and except.
• If the code in the try works - the except is skipped
• If the code in the try fails - it jumps to the except section
• The idea of try and except is that you know that some sequence of
instruction(s) may have a problem and you want to add some
statements to be executed if an error occurs.
• These extra statements (the except block) are ignored if there is no
error.
• You can think of the try and except feature in Python as an “insurance
policy” on a sequence of statements.
The try / except Structure
 Python starts by executing the sequence of
statements in the try block.
 If all goes well, it skips the except block and
proceeds.
 If an exception occurs in the try block, Python
jumps out of the try block and executes the
sequence of statements in the except block.

9
2
The try / except Structure

 Handling an exception with a try statement is called catching an


exception.
 In this example, the except clause prints an error message.
 In general, catching an exception gives you a chance to fix the
problem, or try again, or at least end the program gracefully.

9
3
File Name is tryexcept.py

astr = 'Hello Bob'


When the first conversion fails - it
try:
just drops into the except: clause and
istr = int(astr) the program continues.
except:
istr = -1
$ python tryexcept.py
print('First', istr)
First -1
Second 123
astr = '123'
try:
istr = int(astr) When the second conversion succeeds
except: - it just skips the except: clause and
istr = -1 the program continues.

print('Second', istr)
astr = 'Bob'
try / except
print('Hello‘)
astr = 'Bob'
try:
print('Hello‘) istr = int(astr)
istr = int(astr)
print('There‘) print('There‘)
except:
istr = -1 istr = -1

print('Done', istr) print('Done', istr) Safety net


Short circuit evaluation of logical
expressions
 When Python is processing a logical expression such as x >= 2 and
(x/y) > 2 , it evaluates the expression from left-to-right.
 Because of the definition of and , if x is less than 2, the expression
x >= 2 is False and so the whole expression is False regardless of
whether (x/y) > 2 evaluates to True or False
 When Python detects that there is nothing to be gained by
evaluating the rest of a logical expression, it stops its evaluation and
does not do the computations in the rest of the logical expression.
 When the evaluation of a logical expression stops because the
overall value is already known, it is called short-circuiting the
evaluation.

9
6
Short circuit evaluation of logical expressions

 While this may seem like a fine point, the short


circuit behavior leads to a clever technique called
the guardian pattern.
 Consider the following code sequence in the
Python interpreter:

Not Executed due


This is False
to Short Circuit
9
7
Short circuit evaluation of logical expressions

 The third calculation failed because Python was


evaluating (x/y) and y was zero which causes a
runtime error.
 But the second example did not fail because the
first part of the expression x >= 2 evaluated to
False so the (x/y) was not ever executed due to the
short circuit rule and there was no error.

9
8
Guard Evaluation
 We can construct the logical expression to
strategically place a guard evaluation just before
the evaluation that might cause an error as follows:

9
9
Guard Evaluation
 In the first logical expression, x >= 2 is False so
the evaluation stops at the and .
 In the second logical expression x >= 2 is True but
y != 0 is False so we never reach (x/y) .
 In the third logical expression, the y != 0 is after
the (x/y) calculation so the expression fails with an
error.
 In the second expression, we say that y != 0 acts as
a guard to insure that we only execute (x/y) if y is
non-zero.
1
0
Exercise

1
0
Exercise

Rewrite your pay program using try and except so that


your program handles non-numeric input gracefully.
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input

Enter Hours: forty


Error, please enter numeric input
Summary
• Comparison operators == <= >= > < !=
• Logical operators: and or not
• Indentation
• One Way Decisions
• Two way Decisions if : and else :
• Nested Decisions
• Multiway decisions using elif
• Try / Except to compensate for errors
Functions
Function Definition
• In Python a function is some reusable code that
takes arguments(s) as input does some
computation and then returns a result or results
• We define a function using the def reserved word
• We call/invoke the function by using the function
name, parenthesis and arguments in an expression
• Once we define a function, we can reuse the
function over and over throughout our program
Python Functions
• There are two kinds of functions in Python.
• Built-in functions that are provided as part of Python
- input(), type(), float(), int() ...
• Functions that we define ourselves and then use
• We treat the user defined function names as "new"
reserved words (i.e. we avoid them as variable
names)
Built-in functions
 Python provides a number of important built-in functions that we can use
without needing to provide the function definition.
 The creators of Python wrote a set of functions to solve common problems and
included them in Python for us to use.
 The max and min functions give us the largest and smallest values in a list,
respectively:

 The max function tells us the “largest character” in the string (which turns out
to be the letter “w”)
 The min function shows us the smallest character which turns out to be a
space.

1
0
Built-in functions
 Another very common built-in function is the len function which
tells us how many items are in its argument.
 If the argument to len is a string, it returns the number of
characters in the string.

 These functions are not limited to looking at strings, they can


operate on any set of values.
 You should treat the names of built-in functions as reserved words
(i.e. avoid using “max” as a variable name).

1
0
Type conversion functions
 Python also provides built-in functions that
convert values from one type to another.
 The int function takes any value and converts it to
an integer, if it can, or complains otherwise:

1
0
Type conversion functions
 intcan convert floating-point values to integers,
but it doesn’t round off; it chops off the fraction
part:

 float
converts integers and strings to floating-point
numbers:

 str converts its argument 11to a string:


Random numbers
 Given the same inputs, most computer programs
generate the same outputs every time, so they are said
to be deterministic.
 Determinism is usually a good thing, since we expect
the same calculation to yield the same result.
 For some applications, though, we want the computer
to be unpredictable.
 Games are an obvious example, but there are more.

1
1
Random numbers
 Making a program truly nondeterministic turns out
to be not so easy, but there are ways to make it at
least seem nondeterministic.
 One of them is to use algorithms that generate
pseudorandom numbers.
 Pseudorandom numbers are not truly random
because they are generated by a deterministic
computation, but just by looking at the numbers it
is all but impossible to distinguish them from
random.
1
1
Random numbers
 The random module provides functions that
generate pseudorandom numbers (which I will
simply call “random” from here on).
 The function random returns a random float
between 0.0 and 1.0 (including 0.0 but not 1.0).
 Each time you call random , you get the next
number in a long series.

1
1
Random numbers
 The random function is only one of many
functions which handle random numbers.
 The function randint() takes parameters low and
high and returns an integer between low and high
(including both).

 To choose an element from a sequence at random,


you can use choice :

1
1
Math functions
 Python has a math module that provides most of the familiar mathematical
functions.
 Before we can use the module, we have to import it:

 This statement creates a module object named math. If you print the module
object, you get some information about it:

 The module object contains the functions and variables defined in the module.
 To access one of the functions, you have to specify the name of the module and
the name of the function, separated by a dot (also known as a period).
 This format is called dot notation.

1
1
Math functions

 The first example computes the logarithm base 10 of the signal-to-noise ratio.
 The math module also provides a function called log that computes logarithms base e .
 The second example finds the sine of radians . The name of the variable is a hint that
sin and the other trigonometric functions ( cos , tan , etc.) take arguments in radians.
 To convert from degrees to radians, divide by 360 and multiply by 2π:

 a

1
1
Math functions
 The expression math.pi gets the variable pi from
the math module.
 The value of this variable is an approximation of
π, accurate to about 15 digits.
 If you know your trigonometry, you can check the
previous result by comparing it to the square root
of two divided by two:

1
1
• We create a new function using the def keyword followed by
optional parameters in parenthesis.
• Building our Own Functions
We indent the body of the function
• This defines the function but does not execute the body of the
function
• The rules for function names are the same as for variable names:
letters, numbers and some punctuation marks are legal, but the first
character can’t be a number.
• You can’t use a keyword as the name of a function,
• You should avoid having a variable and a function with the same
name.
• The empty parentheses after the name indicate that this function
doesn’t take any arguments.
def print_lyrics():
print("I'm a lumberjack, and I'm okay.”)
print('I sleep all night and I work all day.‘)
Building our Own Functions
 The first line of the function definition is called the
header; the rest is called the body.
 The header has to end with a colon and the body has
to be indented.
 By convention, the indentation is always four spaces.
 The body can contain any number of statements.
 The strings in the print statements are enclosed in
double quotes.
 Single quotes and double quotes do the same thing;

1
1
Building our Own Functions
 Ifyou type a function definition in interactive mode,
the interpreter prints ellipses (...) to let you know that
the definition isn’t complete:

 To end the function, you have to enter an empty line


(this is not necessary in a script or python file).

1
2
Building our Own Functions
 Defininga function creates a variable with the
same name.

 The value of print_lyrics is a function object,


which has type ' function '.

1
2
Building our Own Functions
 The syntax for calling the new function is the same
as for built-in functions:

1
2
Building our Own Functions
 Once you have defined a function, you can use it
inside another function.
 For example, to repeat the previous refrain, we
could write a function called repeat_lyrics

1
2
Definitions and uses
 Pulling together the code fragments from the previous section, the whole program looks like
this:

 This program contains two function definitions: print_lyrics and repeat_lyrics.


 Function definitions get executed just like other statements, but the effect is to create function
objects.
 The statements inside the function do not get executed until the function is called, and the
function definition generates no output.

1
2
Flow of execution
 In order to ensure that a function is defined before its first use, you have
to know the order in which statements are executed, which is called the
flow of execution.
 Execution always begins at the first statement of the program.
 Statements are executed one at a time, in order from top to bottom.
 Function definitions do not alter the flow of execution of the program,
but remember that statements inside the function are not executed
until the function is called.
 A function call is like a detour in the flow of execution.
 Instead of going to the next statement, the flow jumps to the body of the
function, executes all the statements there, and then comes back to pick
up where it left off.

1
2
Flow of execution
 That sounds simple enough, until you remember that one function can call
another.
 While in the middle of one function, the program might have to execute the
statements in another function.
 But while executing that new function, the program might have to execute yet
another function!
 Fortunately, Python is good at keeping track of where it is, so each time a
function completes, the program picks up where it left off in the function that
called it.
 When it gets to the end of the program, it terminates.
 When you read a program, you don’t always want to read from top to bottom.
 Sometimes it makes more sense if you follow the flow of execution.

1
2
• An argument is a value we pass into the function as its input when


Arguments
we call the function
We use arguments so we can direct the function to do different
kinds of work when we call it at different times
• We put the arguments in parenthesis after the name of the
function

big = max('Hello world')


Argument
Parameters Parameter

>>> def greet(lang):


 A parameter is a variable ... if lang == 'es':
which we use in the ... print('Hola’)
function definition that ... elif lang == 'fr':
is a “handle” that allows ... print('Bonjour’)
the code in the function ... else:
... print('Hello’)
to access the arguments
...
for a particular function >>> greet('en')
invocation. Argument
Hello
>>> greet('es')
Hola
>>> greet('fr')
Bonjour
>>>
Arguments and Parameters
 Here is an example of a user-defined function that
takes an argument
 This function assigns the argument to a parameter
named param1.
 When the function is called, it prints the value of
the parameter (whatever it is) twice.

1
2
Arguments and Parameters
 You can also use a variable as an argument:

1
3
Fruitful functions and void functions
 A “fruitful” function is one that produces a result
(or return value)
 Some functions perform an action but don’t return
a value. They are called void functions
 The return statement ends the function execution
and “sends back” the result of the function
 When you call a fruitful function, you almost
always want to do something with the result;
 for example, you might assign it to a variable or
use it as part of an expression:
1
3
Fruitful functions and void functions
 When you call a function in interactive mode, Python displays the result:

 But in a script, if you call a fruitful function and do not store the result of the function in
a variable, the return value vanishes

 This script computes the square root of 5, but since it doesn’t store the result in a
variable or display the result, it is not very useful.
 Void functions might display something on the screen or have some other effect, but
they don’t have a return value.
 If you try to assign the result to a variable, you get a special value called None

 a

1
3
return Statement
 The value None is not the same as the string ' None '.
 It is a special value that has its own type:

 To return a result from a function, we use the return statement in our


function.
 For example, we could make a very simple function called addtwo that
adds two numbers together and return a result.

 a

1
3
return Statement
 When this script executes, the print statement will
print out “8” because the addtwo function was
called with 3 and 5 as arguments.
 Within the function the parameters a and b were 3
and 5 respectively.
 The function computed the sum of the two
numbers and placed it in the local function
variable named added and used the return
statement to send the computed value back to the
calling code as the function result which was
assigned to the variable x and printed out.
1
3
• Return Values
Often a function will take its arguments, do some computation
and return a value to be used as the value of the function call in
the calling expression. The return keyword is used for this.

def greet():
return “Hello”

print(greet(), "Glenn”) Hello Glenn


print(greet(), "Sally“) Hello Sally
>>> def greet(lang):
Return Value ...
...
if lang == 'es':
return 'Hola’
 A “fruitful” function is ... elif lang == 'fr':
... return 'Bonjour’
one that produces a ... else:
result (or return value) ... return 'Hello’
 The return statement ... >>> print(greet('en'),'Glenn’)
ends the function Hello Glenn
>>> print(greet('es'),'Sally’)
execution and “sends
Hola Sally
back” the result of the >>> print(greet('fr'),'Michael’)
function Bonjour Michael
>>>
Multiple Parameters / Arguments
• We can define more than
one parameter in the
function definition def addtwo(a, b):
• We simply add more added = a + b
arguments when we call return added
the function x = addtwo(3, 5)
• We match the number and print(x)
order of arguments and
parameters
Void (non-fruitful) Functions
• When a function does not return a value, we call it
a "void" function
• Functions that return values are "fruitful"
functions
• Void functions are "not fruitful"
To function or not to function...
 Organize your code into “paragraphs” - capture a
complete thought and “name it”
 Don’t repeat yourself - make it work once and
then reuse it
 If something gets too long or complex, break up
logical chunks and put those chunks in functions
 Make a library of common stuff that you do over
and over - perhaps share this with your friends...
Exercise

Rewrite your pay computation with time-and-a-half for


overtime and create a function called computepay
which takes two parameters ( hours and rate).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0

475 = 40 * 10 + 5 * 15
Summary
• Functions
• Built-In Functions
• Type conversion (int, float)
• Math functions (sin, sqrt)
• Try / except (again)
• Arguments
• Parameters

You might also like