SlideShare a Scribd company logo
1
Course Objectives
2
 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.
Course Outcomes
3
 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.
Textbook
4
 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/pythonlearn.pdf )
 Allen B. Downey, "Think Python: How to Think Like a
Computer Scientist, 2nd Edition, Green Tea Press, 2015.
(http://greenteapress.com/thinkpython2/thinkpython2.pd
f)
Introduction
 Most recent popular (scripting/extension) language
although origin ~1991
 heritage: teaching language (ABC)
Tcl: shell
perl: string (regex) processing
 object-oriented
rather than add-on (OOTcl)
 Python is named after Monty Python and its
famous flying circus, not the snake. It is a
trademark of the Python Software Foundation
Python philosophy
 Coherence
not hard to read, write and maintain
 Power/Batteries
 scope
rapid development + large systems
 objects
 integration
hybrid systems
Python features
no compiling or linking rapid development cycle
no type declarations simpler, shorter, more flexible
automatic memory management garbage collection
high-level data types and
operations
fast development
object-oriented programming code structuring and reuse, C++
embedding and extending in C mixed language systems
classes, modules, exceptions "programming-in-the-large"
support
dynamic loading of C modules simplified extensions, smaller
binaries
dynamic reloading of C modules programs can be modified without
stopping
Lutz, Programming Python
Contd…
universal "first-class" object model fewer restrictions and rules
run-time program construction handles unforeseen needs, end-
user coding
interactive, dynamic nature incremental development and
testing
access to interpreter information metaprogramming, introspective
objects
wide portability cross-platform programming
without ports
compilation to portable byte-code execution speed, protecting source
code
built-in interfaces to external
services
system tools, GUIs, persistence,
databases, etc.
Lutz, Programming Python
Uses of Python
 shell tools
system admin tools, command line programs
 rapid prototyping and development
 graphical user interfaces
 database access
 distributed programming
 Internet scripting
10
What sort of language is Python?
Explicitly
compiled
to machine
code
Purely
interpreted
C, C++,
Fortran
Shell,
Perl
Explicitly
compiled
to byte
code
Java, C#
Implicitly
compiled
to byte
code
Python
Compiled Interpreted
Python packages
The packages we generally need are:
numpy (NUMeric Python): matrices and linear algebra
scipy (SCIentific Python): many numerical routines
matplotlib: (PLOTting LIBrary) creating plots of data
sympy (SYMbolic Python): symbolic computation
pytest (Python TESTing): a code testing framework
11
How To Obtain Python
12
Make sure that you have
Python 3.5 installed. All the
examples in the Textbooks
and class is in Python 3.5.
Anaconda is a freemium open source distribution
of the Python and R programming languages for
large-scale data processing, predictive analytics,
and scientific computing, that aims to simplify
package management and deployment
What is PyCharm
13
 PyCharm is an Integrated Development Environment (IDE) used for programming in Python.
 It provides code analysis, a graphical debugger, an integrated unit tester, integration with
version control systems (VCSes), and supports web development with Django.
 PyCharm is developed by the Czech company JetBrains.
IEEE Programming Language Ranking - 2017
14
Module 1
15
 Why should you learn to write programs
 Variables, expressions and statements
 Conditional execution
 Functions
Computers want to be helpful...
• Computers are built for one
purpose - to do things for us
• But we need to speak their
language to describe what we
want done
• Users have it easy - someone
already put many different
programs (instructions) into
the computer and users just
pick the ones we want to use
What
Next?
What
Next?
What
Next?
What
Next?
What
Next?
What
Next?
What
Next?
Hardware Architecture
Software
Input
and Output
Devices
Central
Processing
Unit
Main
Memory
Secondary
Memory
Generic
Computer
What
Next?
Definitions
 Central Processing Unit: Runs the Program - The CPU is
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
What
Next?
Software
Input
and Output
Devices
Central
Processing
Unit
Main
Memory
Secondary
Memory
Generic
Computer
What
Next?
if x< 3: print
Software
Input
and Output
Devices
Central
Processing
Unit
Main
Memory
Secondary
Memory
Machine
Language
What
Next?
01001001
00111001
http://upload.wikimedia.org/wikipedia/commons/3/3d/RaspberryPi.jpg
 The Raspberry Pi is a low cost, credit-card sized
computer that plugs into a computer monitor or TV,
and uses a standard keyboard and mouse.
 It is a capable little device that enables people of all
ages to explore computing, and to learn how to
program in languages like Scratch and Python.
 It’s capable of doing everything you’d expect a desktop
computer to do, from browsing the internet and
playing high-definition video, to making spreadsheets,
word-processing, and playing games.
23
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
>>> exit()
This is a good test to make sure that you
have 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
x = x + 2
print(x)
Variable Operator Constant Reserved Word
Assignment Statement
Assignment with expression
Print statement
interpreter and compiler:
 Python is a high-level language intended to be relatively
straightforward .
 The CPU understands a language we call machine language. Machine
language is very simple and frankly very tiresome to write because it
is represented all in zeros and ones:
 translators convert the programs to machine language for actual
execution by the CPU.
 programming language translators fall into two general categories:
(1) interpreters and
(2) compilers.
30
 An interpreter reads the source code of the program as written by
the programmer, parses the source code, and interprets the
instructions on the fly.
 A compiler needs to be handed the entire program in a file, and
then it runs a process to translate the high-level source code into
machine language and then the compiler puts the resulting
machine language into a file for later execution.
31
The building blocks of programs
 There are some low-level conceptual patterns that we
use to construct programs.
input
output
sequential execution
conditional execution
repeated execution
reuse.
32
Python Scripts
 Interactive Python 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
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
What could possibly go wrong?
35
• For instance if you want to find the modulo of a certain
number (eg: a%4) instead you wrote the program for division(eg:
a/4) then this type of error is considered to be the logical error.
• For example if you are using an uninitialized variable as the code
given below:
int j;
j++;
In the code snipped given above the variable j is uninitialized but it is
post-incremented.
Variables, Expressions, and Statements
Constants
 Fixed values such as numbers, letters, and strings
are 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
Variables
 A variable is a named place in the memory where a
programmer can 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
12.2
x
14
y
x = 12.2
y = 14
100
x = 100
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
x = x + 2
print(x)
Variable Operator Constant Reserved Word
Assignment Statement
Assignment with expression
Print statement
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 )
x = 3.9 * x * ( 1 - x )
0.6
x
Right side is an expression.
Once expression is evaluated,
the result is placed in (assigned
to) x.
0.6 0.6
0.4
0.93
A variable is a memory location
used to store a value (0.6).
x = 3.9 * x * ( 1 - x )
0.6 0.93
x
Right side is an expression.
Once expression is evaluated,
the result is placed in (assigned
to) the variable on the left side
(i.e. x).
0.93
A variable is a memory location
used to store a value. The
value stored in a variable can be
updated by replacing the old
value (0.6) with a new value
(0.93).
Numeric Expressions
 Because of the lack of
mathematical symbols on
computer keyboards - we use
“computer-speak” to express
the classic math operations
 Asterisk is multiplication
 Exponentiation (raise to a
power) looks different from in
math.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
** Power
% Remainder
Numeric Expressions
>>> xx = 2
>>> xx = xx + 2
>>> print(xx)
4
>>> yy = 440 * 12
>>> print(yy)
5280
>>> zz = yy / 1000
>>> print(zz)
5.28
>>> jj = 23
>>> kk = jj % 5
>>> print(kk)
3
>>> print(4 ** 3)
64
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
** Power
% Remainder
5 23
20
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)
• Multiplication, Division, and Remainder
• Addition and Subtraction
• Left to right
Parenthesis
Power
Multiplication
Addition
Left to Right
Parenthesis
Power
Multiplication
Addition
Left to Right
1 + 2 ** 3 / 4 * 5
1 + 8 / 4 * 5
1 + 2 * 5
1 + 10
11
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11
>>>
Parenthesis
Power
Multiplication
Addition
Left to Right
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11
>>>
1 + 2 ** 3 / 4 * 5
1 + 8 / 4 * 5
1 + 2 * 5
1 + 10
11
Note 8/4 goes before 4*5
because of the left-right
rule.
Operator Precedence
• Remember the rules top to bottom
• When writing code - use parenthesis
• 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
Parenthesis
Power
Multiplication
Addition
Left to Right
Question: x = 1 + 2 * 3 - 4 / 5
Python Integer Division is Weird!
• Integer division yield
float
• Floating point division
produces floating point
numbers
>>> print(10 / 2)
5.0
>>> print(9 / 2)
4.5
>>> print(99 / 100)
0.99
>>> print(10.0 / 2.0)
5.0
>>> print(99.0 / 100.0)
0.99
Mixing Integer and Floating
• When you perform
an operation where
one operand is an
integer and the
other operand is a
floating point the
result is a floating
point
>>> print(99 / 100)
0.99
>>> print(99 / 100.0)
0.99
>>> print(99.0 / 100)
0.99
>>> print (1 + 2 * 3 / 4.0 – 5)
-2.5
>>>
What does “Type” Mean?
 In Python variables, literals,
and constants have a “type”
 Python knows the difference
between an integer number
and a string
 For example “ + ” means
“addition” if something is a
number and “concatenate” if
something is a string
>>> ddd = 1 + 4
>>> print(ddd)
5
>>> eee = 'hello ' + 'there'
>>> print(eee)
hellothere
concatenate = put together
Type Matters
 Python knows what “type”
everything is
 Some operations are
prohibited
 You cannot “add 1” to a
string
 We can ask Python what
type something is by using
the type() function.
>>> eee = 'hello ' + 'there'
>>> eee = eee + 1
Traceback (most recent call
last):
File "<stdin>", line 1, in
<module>
TypeError: Can't convert 'int'
object to str implicitly
>>> type(eee)
<class 'str'>
>>> type('hello')
<class 'str'>
>>> type(1)
<class 'int'>
>>>
Several Types of Numbers
• Numbers have two main types
• Integers are whole numbers: -14, -2,
0, 1, 100, 401233
• Floating Point Numbers have
decimal parts: -2.5 , 0.0, 98.6, 14.0
• There are other number types -
they are variations on float and
integer
>>> xx = 1
>>> type (xx)
<class 'int'>
>>> temp = 98.6
>>> type(temp)
<class 'float'>
>>> type(1)
<class 'int'>
>>> type(1.0)
<class 'float'>
>>>
User Input
• We can instruct
Python to pause
and read data from
the user using the
input function
• The input function
returns a string
>>>name = input(‘Who are you?’)
Who are you? Chuck
>>>print('Welcome', name)
Welcome Chuck
Even If you enter a
number input
considers it as string
by default
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”
 * implies “ multiple
concatenation”
 Python knows when it is
dealing with a string or a
number and behaves
appropriately
>>> print('abc' + '123’)
abc123
>>> print('Hi' * 5)
HiHiHiHiHi
>>>
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
 Example:
x1q3z9ocd = 35.0 --- a = 35.0
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)
hours = 35.0
rate = 12.50
pay = hours * rate
print(pay)
a = 35.0
b = 12.50
c = a * b
print(c)
What is this
code doing?
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 (#)
Converting User Input
• If we want to read a
number from the
user, we must convert
it from a string to a
number using a type
conversion function
• Later we will deal
with bad input data
>>>inp = input(‘Europe floor?’)
Europe floor? 0
>>>usf = int(inp) + 1
>>>print('US floor', usf)
US floor 1
Type Conversions
• When you put an integer
and floating point in an
expression the integer is
implicitly converted to a
float
• You can control this with
the built in functions
int() and float()
>>> print(float(99) / 100)
0.99
>>> i = 42
>>> type(i)
<class 'int'>
>>> f = float(i)
>>> print(f)
42.0
>>> type(f)
<type 'float'>
>>> print(1 + 2 * float(3) / 4 – 5)
-2.5
>>>
String Conversions
• You can also use
int() and float() to
convert between
strings and integers
• You will get an error
if the string does
not contain numeric
characters
>>> sval = '123'
>>> type(sval)
<class 'str'>
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to
str implicitly
>>> ival = int(sval)
>>> type(ival)
<class 'int'>
>>> print(ival + 1)
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with
base 10: 'hello bob'
Conditional Execution
In programming, there are two ways to achieve control the flow of
execution, and they are known as conditional statements and looping
Conditional Steps
Output:
Smaller
Finish
Program:
x = 5
if x < 10:
print('Smaller’)
if x > 20:
print('Bigger‘)
print('Finish‘)
x = 5
X < 10 ?
print('Smaller‘)
X > 20 ?
print('Bigger‘)
print('Finish‘)
Yes
Yes
Comparison Operators
• Boolean expressions ask a
question and produce a Yes
or No result which we use to
control program flow
• Boolean expressions using
comparison operators
evaluate to - True / False -
Yes / No
• Comparison operators look
at variables but do not
change the variables
Remember: “=” is used for assignment.
Python Meaning
< Less than
<= Less than or Equal
== Equal to
>= Greater than or Equal
> Greater than
!= Not equal
Comparison Operators
x = 5
if x == 5 :
print('Equals 5‘)
if x > 4 :
print('Greater than 4’)
if x >= 5 :
print('Greater than or Equal 5‘)
if x < 6 :
print('Less than 6‘)
if x <= 5 :
print('Less than or Equal 5’)
if x != 6 :
print('Not equal 6‘)
Equals 5
Greater than 4
Greater than or Equal 5
Less than 6
Less than or Equal 5
Not equal 6
One-Way Decisions/Conditional statement
x = 5
print('Before 5’)
if x == 5 :
print('Is 5’)
print('Is Still 5’)
print('Third 5’)
print('Afterwards 5’)
print('Before 6’)
if x == 6 :
print('Is 6’)
print('Is Still 6’)
print('Third 6’)
print('Afterwards 6‘)
Before 5
Is 5
Is Still 5
Third 5
Afterwards 5
Before 6
Afterwards 6
X == 5 ?
print('Is 5‘)
Yes
print('Still 5‘)
print('Third 5‘)
No
Indentation
• Increase 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
x = 5
if x > 2 :
print('Bigger than 2‘)
print('Still bigger‘)
print('Done with 2‘)
x = 5
if x > 2 :
# comments
print(‘Bigger than 2’)
# don’t matter
print(‘Still bigger’)
# but can confuse you
print('Done with 2‘)
# if you don’t line
# them up
increase / maintain after if or for
decrease to indicate end of block
blank lines and comment lines ignored
Two Way Decisions/Alternative Execution
• Sometimes we want
to do one thing if a
logical expression is
true and something
else if the
expression is false
• It is like a fork in the
road - we must
choose one or the
other path but not
both
x > 2
print('Bigger‘)
yes
no
X = 4
print('Not bigger‘)
print('All Done‘)
Two-way using else :
x = 4
if x > 2 :
print('Bigger‘)
else :
print('Smaller‘)
print('All done‘)
x > 2
print('Bigger‘)
yes
no
X = 4
print('Smaller‘)
print('All Done‘)
Two-way using else :
x = 4
if x > 2 :
print('Bigger‘)
else :
print('Smaller‘)
print 'All done'
x > 2
Print('Bigger‘)
yes
no
X = 4
print('Smaller‘)
print('All Done‘)
Multi-way/CHAINED CONDITIONALS
if x < 2 :
print('Small‘)
elif x < 10 :
print('Medium‘)
else:
print('LARGE‘)
print('All done‘)
x < 2 print('Small‘)
yes
no
print('All Done‘)
x<10 Print('Medium‘)
yes
print('LARGE‘)
no
Multi-way
x = 0
if x < 2 :
print('Small‘)
elif x < 10 :
print('Medium‘)
else :
print('LARGE‘)
Print('All done‘)
x < 2 print('Small‘)
yes
no
X = 0
print('All Done‘)
x<10 print('Medium‘)
yes
print('LARGE‘)
no
Multi-way
x = 5
if x < 2:
print 'Small'
elif x < 10 :
print('Medium‘)
else :
print('LARGE‘)
print('All done‘)
x < 2 print('Small‘)
yes
no
X = 5
print('All Done‘)
x<10 print('Medium‘)
yes
print('LARGE‘)
no
Multi-way
x = 20
if x < 2 :
print('Small‘)
elif x < 10 :
print('Medium‘)
else :
print('LARGE‘)
Print('All done‘)
x < 2 print('Small‘)
yes
no
X = 20
print('All Done‘)
x<10 print('Medium‘)
yes
print('LARGE‘)
no
x > 1
print(‘More than one’)
x < 100
print(‘Less than 100’)
print('All Done‘)
yes
yes
no
no
x = 42
if x > 1 :
print(‘More than one’)
if x < 100 :
print(‘Less than 100’)
print 'All done'
Nested Decisions
x > 1
print('More than one‘)
x < 100
print('Less than 100‘)
print('All Done‘)
yes
yes
no
no
x = 42
if x > 1 :
print('More than one‘)
if x < 100 :
print('Less than 100‘)
print 'All done'
Nested
Decisions
x > 1
print('More than one‘)
x < 100
print('Less than 100‘)
print('All Done‘)
yes
yes
no
no
x = 42
if x > 1 :
print('More than one‘)
if x < 100 :
print('Less than 100‘)
print 'All done'
Nested
Decisions
Boolean Expressions
84
 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:
Boolean Expressions
85
 True and False are special values that belong to the
type bool ; they are not strings:
Logical Operators
86
 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
The try / except Structure
87
 a
Traceback
However if this code is placed in a
Python script and this error
occurs, your script
immediately stops in its tracks
with a traceback. It does not
execute the following
statement.
88
 Consider a sample program to convert a Fahrenheit
temperature to a Celsius temperature:
 If we execute this code and give it invalid input, it
simply fails with an unfriendly error message:
Invalid
Input
The try / except Structure
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.
90
 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.
The try / except Structure
91
 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.
The try / except Structure
astr = 'Hello Bob'
try:
istr = int(astr)
except:
istr = -1
print('First', istr)
astr = '123'
try:
istr = int(astr)
except:
istr = -1
print('Second', istr)
$ python tryexcept.py
First -1
Second 123
When the first conversion fails - it
just drops into the except: clause
and the program continues.
When the second conversion
succeeds - it just skips the
except: clause and the program
continues.
File Name is tryexcept.py
try / except
astr = 'Bob'
astr = 'Bob'
try:
print('Hello‘)
istr = int(astr)
print('There‘)
except:
istr = -1
print('Done', istr)
print('Hello‘)
print('There‘)
istr = int(astr)
print('Done', istr)
istr = -1
Safety net
Multiple Exception handling
import math
number_list = [10,-5,1.2,'apple']
for number in number_list:
try:
number_factorial = math.factorial(number)
except TypeError:
print("Factorial is not supported for given input type.")
except ValueError:
print("Factorial only accepts positive integer values.", number," is not a
positive integer.")
else:
print("The factorial of",number,"is", number_factorial)
finally:
print("Release any resources in use.")
94
Output
The factorial of 10 is 3628800
Release any resources in use.
Factorial only accepts positive integer values. -5 is not a
positive integer.
Release any resources in use.
Factorial only accepts positive integer values. 1.2 is not a
positive integer.
Release any resources in use.
Factorial is not supported for given input type.
Release any resources in use.
95
Raising an Exceptions
 You can raise exceptions in several ways by using the
raise statement.
 The general syntax for the raise statement is as follows
raise [Exception [, args [, traceback]]]
 Here, Exception is the type of exception (for example,
NameError)
 argument is a value for the exception argument. The
argument is optional; if not supplied, the exception
argument is None.
 The final argument, traceback, is also optional (and
rarely used in practice), and if present, is the traceback
object used for the exception.
96
def demo_bad_catch():
try:
raise ValueError('Represents a hidden bug, do not
catch this')
raise Exception('This is the exception you expect to
handle')
except Exception as error:
print('Caught this error: ' + repr(error))
>>> demo_bad_catch()
Caught this error: ValueError('Represents a hidden bug,
do not catch this',)
97
Short circuit evaluation of logical
expressions
98
 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.
99
 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 to Short
Circuit
This is
False
Guard Evaluation
100
 We can construct the logical expression to strategically
place a guard evaluation just before the evaluation
that might cause an error as follows:
Guard Evaluation
101
 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.
102
Exercise
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/userdefined and then
use
Built-in functions
108
 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.
Built-in functions
109
 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).
Type conversion functions
110
 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:
Type conversion functions
111
 int can 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 to a string:
Random numbers
112
 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.
Random numbers
113
 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.
Random numbers
114
 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.
Random numbers
115
 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 :
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.
116
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
117
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:
118
Building our Own Functions
• We create a new function using the def keyword followed by
optional parameters in parenthesis.
• 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(): #function header
print("I'm a lumberjack, and I'm okay.”) #function body
print('I sleep all night and I work all day.‘) #function body
Contd…,
 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;
120
Contd…,
 If you 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).
121
Contd…,
 Defining a function creates a variable with the same
name.
 The value of print_lyrics is a function object, which has
type ' function '.
122
Contd…,
 The syntax for calling the new function is the same as
for built-in functions:
123
Contd…,
 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
124
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.
125
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.
126
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.
127
Arguments
• An argument is a value we pass into the function as its input
when 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
 A parameter is a
variable which we
use in the function
definition that is a
“handle” that allows
the code in the
function to access
the arguments for a
particular function
invocation.
>>> def greet(lang):
... if lang == 'es':
... print('Hola’)
... elif lang == 'fr':
... print('Bonjour’)
... else:
... print('Hello’)
...
>>> greet('en')
Hello
>>> greet('es')
Hola
>>> greet('fr')
Bonjour
>>>
Parameter
Argument
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.
130
Arguments and Parameters
 You can also use a variable as an argument:
131
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:
132
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
133
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
134
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.
135
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”)
print(greet(), "Sally“)
Hello Glenn
Hello Sally
Return Value
 A “fruitful” function
is one that produces
a result (or return
value)
 The return statement
ends the function
execution and “sends
back” the result of
the function
>>> def greet(lang):
... if lang == 'es':
... return 'Hola’
... elif lang == 'fr':
... return 'Bonjour’
... else:
... return 'Hello’
... >>> print(greet('en'),'Glenn’)
Hello Glenn
>>> print(greet('es'),'Sally’)
Hola Sally
>>> print(greet('fr'),'Michael’)
Bonjour Michael
>>>
Multiple Parameters / Arguments
• We can define more
than one parameter in
the function definition
• We simply add more
arguments when we
call the function
• We match the number
and order of
arguments and
parameters
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print(x)
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

More Related Content

MODULE 1.pptx

  • 1. 1
  • 2. Course Objectives 2  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 3  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. Textbook 4  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/pythonlearn.pdf )  Allen B. Downey, "Think Python: How to Think Like a Computer Scientist, 2nd Edition, Green Tea Press, 2015. (http://greenteapress.com/thinkpython2/thinkpython2.pd f)
  • 5. Introduction  Most recent popular (scripting/extension) language although origin ~1991  heritage: teaching language (ABC) Tcl: shell perl: string (regex) processing  object-oriented rather than add-on (OOTcl)  Python is named after Monty Python and its famous flying circus, not the snake. It is a trademark of the Python Software Foundation
  • 6. Python philosophy  Coherence not hard to read, write and maintain  Power/Batteries  scope rapid development + large systems  objects  integration hybrid systems
  • 7. Python features no compiling or linking rapid development cycle no type declarations simpler, shorter, more flexible automatic memory management garbage collection high-level data types and operations fast development object-oriented programming code structuring and reuse, C++ embedding and extending in C mixed language systems classes, modules, exceptions "programming-in-the-large" support dynamic loading of C modules simplified extensions, smaller binaries dynamic reloading of C modules programs can be modified without stopping Lutz, Programming Python
  • 8. Contd… universal "first-class" object model fewer restrictions and rules run-time program construction handles unforeseen needs, end- user coding interactive, dynamic nature incremental development and testing access to interpreter information metaprogramming, introspective objects wide portability cross-platform programming without ports compilation to portable byte-code execution speed, protecting source code built-in interfaces to external services system tools, GUIs, persistence, databases, etc. Lutz, Programming Python
  • 9. Uses of Python  shell tools system admin tools, command line programs  rapid prototyping and development  graphical user interfaces  database access  distributed programming  Internet scripting
  • 10. 10 What sort of language is Python? Explicitly compiled to machine code Purely interpreted C, C++, Fortran Shell, Perl Explicitly compiled to byte code Java, C# Implicitly compiled to byte code Python Compiled Interpreted
  • 11. Python packages The packages we generally need are: numpy (NUMeric Python): matrices and linear algebra scipy (SCIentific Python): many numerical routines matplotlib: (PLOTting LIBrary) creating plots of data sympy (SYMbolic Python): symbolic computation pytest (Python TESTing): a code testing framework 11
  • 12. How To Obtain Python 12 Make sure that you have Python 3.5 installed. All the examples in the Textbooks and class is in Python 3.5. Anaconda is a freemium open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing, that aims to simplify package management and deployment
  • 13. What is PyCharm 13  PyCharm is an Integrated Development Environment (IDE) used for programming in Python.  It provides code analysis, a graphical debugger, an integrated unit tester, integration with version control systems (VCSes), and supports web development with Django.  PyCharm is developed by the Czech company JetBrains.
  • 14. IEEE Programming Language Ranking - 2017 14
  • 15. Module 1 15  Why should you learn to write programs  Variables, expressions and statements  Conditional execution  Functions
  • 16. Computers want to be helpful... • Computers are built for one purpose - to do things for us • But we need to speak their language to describe what we want done • Users have it easy - someone already put many different programs (instructions) into the computer and users just pick the ones we want to use What Next? What Next? What Next? What Next? What Next? What Next? What Next?
  • 19. Definitions  Central Processing Unit: Runs the Program - The CPU is 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 What Next?
  • 23.  The Raspberry Pi is a low cost, credit-card sized computer that plugs into a computer monitor or TV, and uses a standard keyboard and mouse.  It is a capable little device that enables people of all ages to explore computing, and to learn how to program in languages like Scratch and Python.  It’s capable of doing everything you’d expect a desktop computer to do, from browsing the internet and playing high-definition video, to making spreadsheets, word-processing, and playing games. 23
  • 24. 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?
  • 25. 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 >>> exit() This is a good test to make sure that you have Python correctly installed. Note that quit() also works to end the interactive session.
  • 26. Lets Talk to Python...
  • 27. Elements of Python • Vocabulary / Words - Variables and Reserved words • Sentence structure - valid syntax patterns
  • 28. 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
  • 29. Sentences or Lines x = 2 x = x + 2 print(x) Variable Operator Constant Reserved Word Assignment Statement Assignment with expression Print statement
  • 30. interpreter and compiler:  Python is a high-level language intended to be relatively straightforward .  The CPU understands a language we call machine language. Machine language is very simple and frankly very tiresome to write because it is represented all in zeros and ones:  translators convert the programs to machine language for actual execution by the CPU.  programming language translators fall into two general categories: (1) interpreters and (2) compilers. 30
  • 31.  An interpreter reads the source code of the program as written by the programmer, parses the source code, and interprets the instructions on the fly.  A compiler needs to be handed the entire program in a file, and then it runs a process to translate the high-level source code into machine language and then the compiler puts the resulting machine language into a file for later execution. 31
  • 32. The building blocks of programs  There are some low-level conceptual patterns that we use to construct programs. input output sequential execution conditional execution repeated execution reuse. 32
  • 33. Python Scripts  Interactive Python 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
  • 34. 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
  • 35. What could possibly go wrong? 35 • For instance if you want to find the modulo of a certain number (eg: a%4) instead you wrote the program for division(eg: a/4) then this type of error is considered to be the logical error. • For example if you are using an uninitialized variable as the code given below: int j; j++; In the code snipped given above the variable j is uninitialized but it is post-incremented.
  • 37. Constants  Fixed values such as numbers, letters, and strings are 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
  • 38. Variables  A variable is a named place in the memory where a programmer can 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 12.2 x 14 y x = 12.2 y = 14 100 x = 100
  • 39. 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
  • 40. 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
  • 41. Sentences or Lines x = 2 x = x + 2 print(x) Variable Operator Constant Reserved Word Assignment Statement Assignment with expression Print statement
  • 42. 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 )
  • 43. x = 3.9 * x * ( 1 - x ) 0.6 x Right side is an expression. Once expression is evaluated, the result is placed in (assigned to) x. 0.6 0.6 0.4 0.93 A variable is a memory location used to store a value (0.6).
  • 44. x = 3.9 * x * ( 1 - x ) 0.6 0.93 x Right side is an expression. Once expression is evaluated, the result is placed in (assigned to) the variable on the left side (i.e. x). 0.93 A variable is a memory location used to store a value. The value stored in a variable can be updated by replacing the old value (0.6) with a new value (0.93).
  • 45. Numeric Expressions  Because of the lack of mathematical symbols on computer keyboards - we use “computer-speak” to express the classic math operations  Asterisk is multiplication  Exponentiation (raise to a power) looks different from in math. Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder
  • 46. Numeric Expressions >>> xx = 2 >>> xx = xx + 2 >>> print(xx) 4 >>> yy = 440 * 12 >>> print(yy) 5280 >>> zz = yy / 1000 >>> print(zz) 5.28 >>> jj = 23 >>> kk = jj % 5 >>> print(kk) 3 >>> print(4 ** 3) 64 Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder 5 23 20 3
  • 47. 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
  • 48. Operator Precedence Rules • Highest precedence rule to lowest precedence rule • Parenthesis are always respected • Exponentiation (raise to a power) • Multiplication, Division, and Remainder • Addition and Subtraction • Left to right Parenthesis Power Multiplication Addition Left to Right
  • 49. Parenthesis Power Multiplication Addition Left to Right 1 + 2 ** 3 / 4 * 5 1 + 8 / 4 * 5 1 + 2 * 5 1 + 10 11 >>> x = 1 + 2 ** 3 / 4 * 5 >>> print(x) 11 >>>
  • 50. Parenthesis Power Multiplication Addition Left to Right >>> x = 1 + 2 ** 3 / 4 * 5 >>> print(x) 11 >>> 1 + 2 ** 3 / 4 * 5 1 + 8 / 4 * 5 1 + 2 * 5 1 + 10 11 Note 8/4 goes before 4*5 because of the left-right rule.
  • 51. Operator Precedence • Remember the rules top to bottom • When writing code - use parenthesis • 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 Parenthesis Power Multiplication Addition Left to Right Question: x = 1 + 2 * 3 - 4 / 5
  • 52. Python Integer Division is Weird! • Integer division yield float • Floating point division produces floating point numbers >>> print(10 / 2) 5.0 >>> print(9 / 2) 4.5 >>> print(99 / 100) 0.99 >>> print(10.0 / 2.0) 5.0 >>> print(99.0 / 100.0) 0.99
  • 53. Mixing Integer and Floating • When you perform an operation where one operand is an integer and the other operand is a floating point the result is a floating point >>> print(99 / 100) 0.99 >>> print(99 / 100.0) 0.99 >>> print(99.0 / 100) 0.99 >>> print (1 + 2 * 3 / 4.0 – 5) -2.5 >>>
  • 54. What does “Type” Mean?  In Python variables, literals, and constants have a “type”  Python knows the difference between an integer number and a string  For example “ + ” means “addition” if something is a number and “concatenate” if something is a string >>> ddd = 1 + 4 >>> print(ddd) 5 >>> eee = 'hello ' + 'there' >>> print(eee) hellothere concatenate = put together
  • 55. Type Matters  Python knows what “type” everything is  Some operations are prohibited  You cannot “add 1” to a string  We can ask Python what type something is by using the type() function. >>> eee = 'hello ' + 'there' >>> eee = eee + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't convert 'int' object to str implicitly >>> type(eee) <class 'str'> >>> type('hello') <class 'str'> >>> type(1) <class 'int'> >>>
  • 56. Several Types of Numbers • Numbers have two main types • Integers are whole numbers: -14, -2, 0, 1, 100, 401233 • Floating Point Numbers have decimal parts: -2.5 , 0.0, 98.6, 14.0 • There are other number types - they are variations on float and integer >>> xx = 1 >>> type (xx) <class 'int'> >>> temp = 98.6 >>> type(temp) <class 'float'> >>> type(1) <class 'int'> >>> type(1.0) <class 'float'> >>>
  • 57. User Input • We can instruct Python to pause and read data from the user using the input function • The input function returns a string >>>name = input(‘Who are you?’) Who are you? Chuck >>>print('Welcome', name) Welcome Chuck Even If you enter a number input considers it as string by default
  • 58. 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
  • 59. String Operations  Some operators apply to strings  + implies “concatenation”  * implies “ multiple concatenation”  Python knows when it is dealing with a string or a number and behaves appropriately >>> print('abc' + '123’) abc123 >>> print('Hi' * 5) HiHiHiHiHi >>>
  • 60. 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  Example: x1q3z9ocd = 35.0 --- a = 35.0
  • 61. x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print(x1q3p9afd) hours = 35.0 rate = 12.50 pay = hours * rate print(pay) a = 35.0 b = 12.50 c = a * b print(c) What is this code doing?
  • 62. 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
  • 63. Summary • Type • Resrved words • Variables (mnemonic) • Operators • Operator precedence • Integer Division • Conversion between types • User input • Comments (#)
  • 64. Converting User Input • If we want to read a number from the user, we must convert it from a string to a number using a type conversion function • Later we will deal with bad input data >>>inp = input(‘Europe floor?’) Europe floor? 0 >>>usf = int(inp) + 1 >>>print('US floor', usf) US floor 1
  • 65. Type Conversions • When you put an integer and floating point in an expression the integer is implicitly converted to a float • You can control this with the built in functions int() and float() >>> print(float(99) / 100) 0.99 >>> i = 42 >>> type(i) <class 'int'> >>> f = float(i) >>> print(f) 42.0 >>> type(f) <type 'float'> >>> print(1 + 2 * float(3) / 4 – 5) -2.5 >>>
  • 66. String Conversions • You can also use int() and float() to convert between strings and integers • You will get an error if the string does not contain numeric characters >>> sval = '123' >>> type(sval) <class 'str'> >>> print(sval + 1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't convert 'int' object to str implicitly >>> ival = int(sval) >>> type(ival) <class 'int'> >>> print(ival + 1) 124 >>> nsv = 'hello bob' >>> niv = int(nsv) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'hello bob'
  • 67. Conditional Execution In programming, there are two ways to achieve control the flow of execution, and they are known as conditional statements and looping
  • 68. Conditional Steps Output: Smaller Finish Program: x = 5 if x < 10: print('Smaller’) if x > 20: print('Bigger‘) print('Finish‘) x = 5 X < 10 ? print('Smaller‘) X > 20 ? print('Bigger‘) print('Finish‘) Yes Yes
  • 69. Comparison Operators • Boolean expressions ask a question and produce a Yes or No result which we use to control program flow • Boolean expressions using comparison operators evaluate to - True / False - Yes / No • Comparison operators look at variables but do not change the variables Remember: “=” is used for assignment. Python Meaning < Less than <= Less than or Equal == Equal to >= Greater than or Equal > Greater than != Not equal
  • 70. Comparison Operators x = 5 if x == 5 : print('Equals 5‘) if x > 4 : print('Greater than 4’) if x >= 5 : print('Greater than or Equal 5‘) if x < 6 : print('Less than 6‘) if x <= 5 : print('Less than or Equal 5’) if x != 6 : print('Not equal 6‘) Equals 5 Greater than 4 Greater than or Equal 5 Less than 6 Less than or Equal 5 Not equal 6
  • 71. One-Way Decisions/Conditional statement x = 5 print('Before 5’) if x == 5 : print('Is 5’) print('Is Still 5’) print('Third 5’) print('Afterwards 5’) print('Before 6’) if x == 6 : print('Is 6’) print('Is Still 6’) print('Third 6’) print('Afterwards 6‘) Before 5 Is 5 Is Still 5 Third 5 Afterwards 5 Before 6 Afterwards 6 X == 5 ? print('Is 5‘) Yes print('Still 5‘) print('Third 5‘) No
  • 72. Indentation • Increase 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
  • 73. x = 5 if x > 2 : print('Bigger than 2‘) print('Still bigger‘) print('Done with 2‘) x = 5 if x > 2 : # comments print(‘Bigger than 2’) # don’t matter print(‘Still bigger’) # but can confuse you print('Done with 2‘) # if you don’t line # them up increase / maintain after if or for decrease to indicate end of block blank lines and comment lines ignored
  • 74. Two Way Decisions/Alternative Execution • Sometimes we want to do one thing if a logical expression is true and something else if the expression is false • It is like a fork in the road - we must choose one or the other path but not both x > 2 print('Bigger‘) yes no X = 4 print('Not bigger‘) print('All Done‘)
  • 75. Two-way using else : x = 4 if x > 2 : print('Bigger‘) else : print('Smaller‘) print('All done‘) x > 2 print('Bigger‘) yes no X = 4 print('Smaller‘) print('All Done‘)
  • 76. Two-way using else : x = 4 if x > 2 : print('Bigger‘) else : print('Smaller‘) print 'All done' x > 2 Print('Bigger‘) yes no X = 4 print('Smaller‘) print('All Done‘)
  • 77. Multi-way/CHAINED CONDITIONALS if x < 2 : print('Small‘) elif x < 10 : print('Medium‘) else: print('LARGE‘) print('All done‘) x < 2 print('Small‘) yes no print('All Done‘) x<10 Print('Medium‘) yes print('LARGE‘) no
  • 78. Multi-way x = 0 if x < 2 : print('Small‘) elif x < 10 : print('Medium‘) else : print('LARGE‘) Print('All done‘) x < 2 print('Small‘) yes no X = 0 print('All Done‘) x<10 print('Medium‘) yes print('LARGE‘) no
  • 79. Multi-way x = 5 if x < 2: print 'Small' elif x < 10 : print('Medium‘) else : print('LARGE‘) print('All done‘) x < 2 print('Small‘) yes no X = 5 print('All Done‘) x<10 print('Medium‘) yes print('LARGE‘) no
  • 80. Multi-way x = 20 if x < 2 : print('Small‘) elif x < 10 : print('Medium‘) else : print('LARGE‘) Print('All done‘) x < 2 print('Small‘) yes no X = 20 print('All Done‘) x<10 print('Medium‘) yes print('LARGE‘) no
  • 81. x > 1 print(‘More than one’) x < 100 print(‘Less than 100’) print('All Done‘) yes yes no no x = 42 if x > 1 : print(‘More than one’) if x < 100 : print(‘Less than 100’) print 'All done' Nested Decisions
  • 82. x > 1 print('More than one‘) x < 100 print('Less than 100‘) print('All Done‘) yes yes no no x = 42 if x > 1 : print('More than one‘) if x < 100 : print('Less than 100‘) print 'All done' Nested Decisions
  • 83. x > 1 print('More than one‘) x < 100 print('Less than 100‘) print('All Done‘) yes yes no no x = 42 if x > 1 : print('More than one‘) if x < 100 : print('Less than 100‘) print 'All done' Nested Decisions
  • 84. Boolean Expressions 84  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:
  • 85. Boolean Expressions 85  True and False are special values that belong to the type bool ; they are not strings:
  • 86. Logical Operators 86  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
  • 87. The try / except Structure 87  a Traceback However if this code is placed in a Python script and this error occurs, your script immediately stops in its tracks with a traceback. It does not execute the following statement.
  • 88. 88  Consider a sample program to convert a Fahrenheit temperature to a Celsius temperature:  If we execute this code and give it invalid input, it simply fails with an unfriendly error message: Invalid Input The try / except Structure
  • 89. 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.
  • 90. 90  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. The try / except Structure
  • 91. 91  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. The try / except Structure
  • 92. astr = 'Hello Bob' try: istr = int(astr) except: istr = -1 print('First', istr) astr = '123' try: istr = int(astr) except: istr = -1 print('Second', istr) $ python tryexcept.py First -1 Second 123 When the first conversion fails - it just drops into the except: clause and the program continues. When the second conversion succeeds - it just skips the except: clause and the program continues. File Name is tryexcept.py
  • 93. try / except astr = 'Bob' astr = 'Bob' try: print('Hello‘) istr = int(astr) print('There‘) except: istr = -1 print('Done', istr) print('Hello‘) print('There‘) istr = int(astr) print('Done', istr) istr = -1 Safety net
  • 94. Multiple Exception handling import math number_list = [10,-5,1.2,'apple'] for number in number_list: try: number_factorial = math.factorial(number) except TypeError: print("Factorial is not supported for given input type.") except ValueError: print("Factorial only accepts positive integer values.", number," is not a positive integer.") else: print("The factorial of",number,"is", number_factorial) finally: print("Release any resources in use.") 94
  • 95. Output The factorial of 10 is 3628800 Release any resources in use. Factorial only accepts positive integer values. -5 is not a positive integer. Release any resources in use. Factorial only accepts positive integer values. 1.2 is not a positive integer. Release any resources in use. Factorial is not supported for given input type. Release any resources in use. 95
  • 96. Raising an Exceptions  You can raise exceptions in several ways by using the raise statement.  The general syntax for the raise statement is as follows raise [Exception [, args [, traceback]]]  Here, Exception is the type of exception (for example, NameError)  argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None.  The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception. 96
  • 97. def demo_bad_catch(): try: raise ValueError('Represents a hidden bug, do not catch this') raise Exception('This is the exception you expect to handle') except Exception as error: print('Caught this error: ' + repr(error)) >>> demo_bad_catch() Caught this error: ValueError('Represents a hidden bug, do not catch this',) 97
  • 98. Short circuit evaluation of logical expressions 98  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.
  • 99. 99  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 to Short Circuit This is False
  • 100. Guard Evaluation 100  We can construct the logical expression to strategically place a guard evaluation just before the evaluation that might cause an error as follows:
  • 101. Guard Evaluation 101  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.
  • 103. 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
  • 104. 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
  • 106. 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
  • 107. 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/userdefined and then use
  • 108. Built-in functions 108  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.
  • 109. Built-in functions 109  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).
  • 110. Type conversion functions 110  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:
  • 111. Type conversion functions 111  int can 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 to a string:
  • 112. Random numbers 112  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.
  • 113. Random numbers 113  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.
  • 114. Random numbers 114  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.
  • 115. Random numbers 115  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 :
  • 116. 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. 116
  • 117. 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 117
  • 118. 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: 118
  • 119. Building our Own Functions • We create a new function using the def keyword followed by optional parameters in parenthesis. • 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(): #function header print("I'm a lumberjack, and I'm okay.”) #function body print('I sleep all night and I work all day.‘) #function body
  • 120. Contd…,  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; 120
  • 121. Contd…,  If you 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). 121
  • 122. Contd…,  Defining a function creates a variable with the same name.  The value of print_lyrics is a function object, which has type ' function '. 122
  • 123. Contd…,  The syntax for calling the new function is the same as for built-in functions: 123
  • 124. Contd…,  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 124
  • 125. 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. 125
  • 126. 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. 126
  • 127. 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. 127
  • 128. Arguments • An argument is a value we pass into the function as its input when 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
  • 129. Parameters  A parameter is a variable which we use in the function definition that is a “handle” that allows the code in the function to access the arguments for a particular function invocation. >>> def greet(lang): ... if lang == 'es': ... print('Hola’) ... elif lang == 'fr': ... print('Bonjour’) ... else: ... print('Hello’) ... >>> greet('en') Hello >>> greet('es') Hola >>> greet('fr') Bonjour >>> Parameter Argument
  • 130. 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. 130
  • 131. Arguments and Parameters  You can also use a variable as an argument: 131
  • 132. 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: 132
  • 133. 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 133
  • 134. 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 134
  • 135. 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. 135
  • 136. 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”) print(greet(), "Sally“) Hello Glenn Hello Sally
  • 137. Return Value  A “fruitful” function is one that produces a result (or return value)  The return statement ends the function execution and “sends back” the result of the function >>> def greet(lang): ... if lang == 'es': ... return 'Hola’ ... elif lang == 'fr': ... return 'Bonjour’ ... else: ... return 'Hello’ ... >>> print(greet('en'),'Glenn’) Hello Glenn >>> print(greet('es'),'Sally’) Hola Sally >>> print(greet('fr'),'Michael’) Bonjour Michael >>>
  • 138. Multiple Parameters / Arguments • We can define more than one parameter in the function definition • We simply add more arguments when we call the function • We match the number and order of arguments and parameters def addtwo(a, b): added = a + b return added x = addtwo(3, 5) print(x)
  • 139. 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"
  • 140. 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...
  • 141. 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
  • 142. Summary • Functions • Built-In Functions • Type conversion (int, float) • Math functions (sin, sqrt) • Try / except (again) • Arguments • Parameters