Python Mod1 PPT
Python Mod1 PPT
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
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 = 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
x = 3.9 * x * ( 1 - x )
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
• 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
• 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
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('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.”
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:
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
9
3
File Name is tryexcept.py
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
9
6
Short circuit evaluation of logical expressions
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
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.
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:
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).
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:
1
2
Building our Own Functions
Defininga function creates a variable with the
same name.
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:
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
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:
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”
475 = 40 * 10 + 5 * 15
Summary
• Functions
• Built-In Functions
• Type conversion (int, float)
• Math functions (sin, sqrt)
• Try / except (again)
• Arguments
• Parameters