You are on page 1of 147

Python Programming

Dr.S.Gowrishankar,
Associate Professor,
Department of Computer Science and Engineering,
Dr.Ambedkar Institute of Technology,
Bengaluru.

1
2 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT
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 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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/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 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Slides and Live Code
 The best system for me is to have a series of
PowerPoint slides “lead” our discussion
 This allows me to present the material in an organized way
 Also, we shall discuss code snippets. It’s the most
important part of the overall code.
 Then will show you how this Code snippet fits in the
overall picture.
 Read from Textbook. Slides are only to convey the
information as I deem fit.

7 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


People Basics
 Lets have Interactive Sessions
 Questions are always welcome
 No discussions among yourselves
 Class room sanity should be strictly maintained (Avoid
Noise).
 All cell phones (including my own) must be turned off.
 If your phone does accidentally go off, I expect you to
turn it off immediately.
 Please be respectful of other students’ time and
commitment to their studies by not breaching this
policy so that we don’t end up in the embarrassing
position of having to ask you to leave the class

8 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Pre-Requisite: Please Install Python

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


How To Obtain Python

Make sure that you have Python 3.5 installed.


All the examples in the Textbooks and class is
in Python 3.5.

10 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


What is PyCharm
 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.

11 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Lab Programs
https://github.com/csedrait

Click
Here

Click on Program
Name to see the
Code

12 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


IEEE Programming Language Ranking - 2017

13 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Unit 1 Review
 Why should you learn to write programs
 Variables, expressions and statements
 Conditional execution
 Functions

14 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Computers want to be helpful...

What
• Computers are built for one Next?
purpose - to do things for us
• But we need to speak their
language to describe what we
want done
• Users have it easy - someone What What What
already put many different Next? Next? Next?
programs (instructions) into
the computer and users just What What What
pick the ones we want to use Next? Next? Next?

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Hardware Architecture

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


http://upload.wikimedia.org/wikipedia/commons/3/3d/RaspberryPi.jpg

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Generic
Software What
Next? Computer
Input Central
and Output Processing
Devices Unit
Secondary
Memory

Main
Memory

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Definitions

 Central Processing Unit: Runs the Program - The CPUNext?


is What

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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Generic
Software What
Next? Computer
Input Central
and Output Processing
Devices Unit
Secondary
if x< 3: print Memory

Main
Memory

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Software What
Next?

Input Central
and Output Processing
Devices Unit
Secondary
01001001 Memory
00111001

Main
Memory

Machine
Language

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Totally Hot CPU

What
Next?

http://www.youtube.com/watch?v=y39D4529FM4

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Hard Disk in Action

http://www.youtube.com/watch?v=9eMWG3fwiEU

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Python as a Language

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Talking to Python

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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?

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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) This is a good test to make sure that you
2 have Python correctly installed. Note that
>>> exit() quit() also works to end the interactive
session.

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Lets Talk to Python...

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Elements of Python
• Vocabulary / Words - Variables and Reserved words
• Sentence structure - valid syntax patterns

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Sentences or Lines

x=2 Assignment Statement


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

Variable Operator Constant Reserved Word

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Programming Paragraphs

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Writing a Simple Program

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Program Steps or Program Flow
• Like a recipe or installation instructions, a program is
a sequence of steps to be done in order
• Some steps are conditional - they may be skipped
• Sometimes a step or group of steps are to be repeated
• Sometimes we store a set of steps to be used over and
over as needed several places throughout the program

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Sequential Steps

x=1 Program:
Output:
print(x) x=2
print(x) 2
x=x+1 x=x+2 4
print(x)
print(x)

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


programmers set up “paths” for the program to follow.

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Conditional Steps
x=5

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

print('Finish‘)
print('Finish‘)

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Variables, Expressions, and Statements

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

x = 12.2 x 12.2 100


y = 14
x = 100 y 14

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Sentences or Lines

x=2 Assignment Statement


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

Variable Operator Constant Reserved Word

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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 )

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


A variable is a memory location x 0.6
used to store a value (0.6).

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

Right side is an expression.


Once expression is evaluated, 0.93
the result is placed in (assigned
to) x.

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

x = 3.9 * x * ( 1 - x )

Right side is an expression.


Once expression is evaluated, 0.93
the result is placed in (assigned
to) the variable on the left side
(i.e. x).

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Numeric Expressions

 Because of the lack of Operator Operation


mathematical symbols on + Addition
computer keyboards - we use - Subtraction
“ computer-speak ” to express
the classic math operations * Multiplication

 Asterisk is multiplication / Division


 Exponentiation (raise to a ** Power
power) looks different from in % Remainder
math.

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Numeric Expressions

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

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

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

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

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

>>> print(zz) 20
5.28
3

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


>>> 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 11
Left to Right

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Python Integer Division is Weird!

>>> print(10 / 2)
• Integer division yield
5.0
float >>> print(9 / 2)
• Floating point division 4.5
>>> print(99 / 100)
produces floating point 0.99
numbers >>> print(10.0 / 2.0)
5.0
>>> print(99.0 / 100.0)
0.99

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Mixing Integer and Floating
• When you perform >>> print(99 / 100)
an operation where 0.99
>>> print(99 / 100.0)
one operand is an 0.99
integer and the >>> print(99.0 / 100)
other operand is a 0.99
floating point the >>> print 1 + 2 * 3 / 4.0 - 5
result is a floating -2.5
point >>>

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


What does “Type” Mean?
 In Python variables, literals,
>>> ddd = 1 + 4
and constants have a “type”
>>> print(ddd)
 Python knows the difference 5
between an integer number >>> eee = 'hello ' + 'there'
and a string >>> print(eee)
 For example “ + ” means hellothere
“addition” if something is a
number and “concatenate” if
something is a string

concatenate = put together

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Type Matters
 Python knows what “type” >>> eee = 'hello ' + 'there'
everything is >>> eee = eee + 1
 Some operations are Traceback (most recent call
prohibited last):
 You cannot “add 1” to a File "<stdin>", line 1, in
string <module>
 We can ask Python what TypeError: Can't convert 'int'
type something is by using object to str implicitly
the type() function. >>> type(eee)
<class 'str'>
>>> type('hello')
<class 'str'>
>>> type(1)
<class 'int'>
>>>

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Several Types of Numbers

>>> xx = 1
• Numbers have two main types >>> type (xx)
• Integers are whole numbers: -14, -2, <class 'int'>
0, 1, 100, 401233 >>> temp = 98.6
• Floating Point Numbers have >>> type(temp)
decimal parts: -2.5 , 0.0, 98.6, 14.0 <class 'float'>
• There are other number types - >>> type(1)
<class 'int'>
they are variations on float and >>> type(1.0)
integer <class 'float'>
>>>

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Type Conversions

• When you put an integer >>> print(float(99) / 100)


0.99
and floating point in an
>>> i = 42
expression the integer is >>> type(i)
implicitly converted to a <class 'int'>
float >>> f = float(i)
• You can control this with >>> print(f)
42.0
the built in functions >>> type(f)
int() and float() <type 'float'>
>>> print(1 + 2 * float(3) / 4 – 5)
-2.5
>>>

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


String Conversions
>>> sval = '123'
>>> type(sval)
<class 'str'>
>>> print(sval + 1)
Traceback (most recent call last):
• You can also use File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str
int() and float() to implicitly
convert between
>>> ival = int(sval)
strings and integers >>> type(ival)
• You will get an error <class 'int'>
>>> print(ival + 1)
if the string does 124
not contain numeric >>> nsv = 'hello bob'
characters >>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base
10: 'hello bob'

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


User Input

Even If you enter a


• We can instruct number input considers it
as string by default
Python to pause
and read data from
the user using the >>>name = input(‘Who are you?’)
Who are you? Chuck
input function >>>print('Welcome', name)
• The input function Welcome Chuck
returns a string

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Converting User Input

• If we want to read a
number from the >>>inp = input(‘Europe floor?’)
user, we must Europe floor? 0
convert it from a >>>usf = int(inp) + 1
string to a number
using a type >>>print('US floor', usf)
conversion function US floor 1
• Later we will deal
with bad input data

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


String Operations

 Some operators apply to


strings
 + implies “concatenation” >>> print('abc' + '123’)
* implies “ multiple abc123
concatenation” >>> print('Hi' * 5)
 Python knows when it is HiHiHiHiHi
dealing with a string or a >>>
number and behaves
appropriately

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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)

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Summary
• Type
• Resrved words
• Variables (mnemonic)
• Operators
• Operator precedence

• Integer Division
• Conversion between types
• User input
• Comments (#)

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Conditional Execution

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Comparison Operators

• Boolean expressions ask a


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

http://en.wikipedia.org/wiki/George_Boole

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


increase / maintain after if or for
decrease to indicate end of block
blank lines and comment lines ignored
x=5
x=5 if x > 2 :
if x > 2 : # comments
print('Bigger than 2‘)
print('Still bigger‘) print(‘Bigger than 2’)
print('Done with 2‘) # don’t matter
print(‘Still bigger’)
# but can confuse you

print('Done with 2‘)


# if you don’t line
# them up

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Nested Decisions
yes
x>1

no print(‘More than one’)


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

print(‘More than one’)


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

print(‘Less than 100’)

print 'All done'


print('All Done‘)

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Nested Decisions
yes
x>1

no print('More than one‘)


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

print('More than one‘)


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

print('Less than 100‘)

print 'All done'


print('All Done‘)

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Nested Decisions
yes
x>1

no print('More than one‘)


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

print('More than one‘)


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

print('Less than 100‘)

print 'All done'


print('All Done‘)

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

print('All Done‘)

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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'

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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:

92 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Boolean Expressions
 True and False are special values that belong to the
type bool ; they are not strings:

93 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

 a
This flexibility can be
useful but confusing. You
might want to avoid it

94 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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 a


Traceback Python script and this error occurs,
your script
immediately stops in its tracks with a
traceback. It does not execute the
following
statement.

 a

95 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


The try / except Structure
 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

96 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.

98 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


The try / except Structure

 Handling an exception with a try statement is called


catching an exception.
 In this example, the except clause prints an error
message.
 In general, catching an exception gives you a chance to
fix the problem, or try again, or at least end the
program gracefully.
99 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT
File Name is tryexcept.py

astr = 'Hello Bob'


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

print('Second', istr)

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

102 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Short circuit evaluation of logical
expressions
 While this may seem like a fine point, the short circuit
behavior leads to a clever technique called the
guardian pattern.
 Consider the following code sequence in the Python
interpreter:

Not Executed due to


This is False
Short Circuit
103 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT
Short circuit evaluation of logical
expressions
 The third calculation failed because Python was
evaluating (x/y) and y was zero which causes a
runtime error.
 But the second example did not fail because the first
part of the expression x >= 2 evaluated to False so the
(x/y) was not ever executed due to the short circuit
rule and there was no error.

104 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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:

105 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.

106 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Exercise

107 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Functions

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Python Functions
• There are two kinds of functions in Python.
• Built-in functions that are provided as part of Python - input(),
type(), float(), int() ...
• Functions that we define ourselves and then use
• We treat the user defined function names as "new"
reserved words (i.e. we avoid them as variable names)

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Built-in functions
 Python provides a number of important built-in functions
that we can use without needing to provide the function
definition.
 The creators of Python wrote a set of functions to solve
common problems and included them in Python for us to
use.
 The max and min functions give us the largest and smallest
values in a list, respectively:

 The max function tells us the “largest character” in the


string (which turns out to be the letter “w”)
 The min function shows us the smallest character which
turns out to be a space.

113 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

 These functions are not limited to looking at strings,


they can operate on any set of values.
 You should treat the names of built-in functions as
reserved words (i.e. avoid using “max” as a variable
name).
114 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT
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:

115 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Type conversion functions
 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:

116 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

117 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.

118 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.

119 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

 To choose an element from a sequence at random, you


can use choice :

120 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.
121 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT
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

122 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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:

123 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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():
print("I'm a lumberjack, and I'm okay.”)
print('I sleep all night and I work all day.‘)
© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT
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;

125 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Building our Own Functions
 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).

126 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Building our Own Functions
 Defining a function creates a variable with the same
name.

 The value of print_lyrics is a function object, which has


type ' function '.

127 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

128 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

129 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.

130 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.

131 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.
132 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT
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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Parameters Parameter

>>> def greet(lang):


 A parameter is a ... if lang == 'es':
variable which we ... print('Hola’)
use in the function ... elif lang == 'fr':
definition that is a ... print('Bonjour’)
“handle” that allows ... else:
the code in the ... print('Hello’)
function to access ...
the arguments for a >>> greet('en')
particular function Argument
invocation. Hello
>>> greet('es')
Hola
>>> greet('fr')
Bonjour
>>>

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.

135 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Arguments and Parameters
 You can also use a variable as an argument:

136 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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:

137 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

138 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

139 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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.

140 © Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Return Values

• Often a function will take its arguments, do some


computation and return a value to be used as the value
of the function call in the calling expression. The return
keyword is used for this.

def greet():
return “Hello”

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


print(greet(), "Sally“) Hello Sally

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


>>> def greet(lang):
Return Value ...
...
if lang == 'es':
return 'Hola’
 A “fruitful” function ... elif lang == 'fr':
is one that produces ... return 'Bonjour’
a result (or return ... else:
... return 'Hello’
value)
... >>> print(greet('en'),'Glenn’)
 The return statement Hello Glenn
ends the function >>> print(greet('es'),'Sally’)
execution and “sends Hola Sally
back ” the result of >>> print(greet('fr'),'Michael’)
the function Bonjour Michael
>>>

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Multiple Parameters / Arguments

• We can define more


than one parameter in
the function definition
def addtwo(a, b):
• We simply add more
arguments when we added = a + b
call the function return added
x = addtwo(3, 5)
• We match the number
print(x)
and order of
arguments and
parameters

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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"

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


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

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT


Summary
• Functions
• Built-In Functions
• Type conversion (int, float)
• Math functions (sin, sqrt)
• Try / except (again)
• Arguments
• Parameters

© Dr.S.Gowrishankar, Dept. of CSE, Dr.AIT

You might also like