Chapter

Python Control of Flow(if, Function)

Aman. W()
Department of Physics
University of Gondar
Contents

• Python Control of Flow
• If statment
• Elif
• Else statements
• Functions
• Function calls
• Variables and Functions
• Functions arguments
– default values for arguments
– Keyword Arguments
Flow control/conditionals
 The term control flow is typically used to describe the order of
execution in code
 In general. programs code flows from the first line to the last line, one
line at a time
 However, if we have one or more statements which are executed in the
order in your program, we order them by a flow control statement
 Some of the flow control statements are
 if
 if/elif
 if/elif/else
 For/while loops
 Function
 Try/except
If, elif

• The if statement of Python is similar to that of other languages.
• The syntax of the if statement is:
• if logical expression():
statement
• Indentation required
• if expression is true, then statement is executed
• if expression is false, statement is NOT executed
• But when we have if .. elif , It provides two-way selection
between executing one of 2 clauses (the if clause or the elif
clause)
• Example:

gpa = 2.5

if gpa > 2.0:
print "Welcome to University of Gondar Post prog!"
else:
print "Your application is denied."
If, elif, eles

• The if statement contains a logical expression using which
data is compared, and
– a decision is made based on the result of the comparison.
• The syntax of the if statement is:
if boolean Expr:
indented statement of code
elif boolean Expr:
indented statement of code
else:
indented statement of code
if/elif/else

• The elif statement allows you to check multiple expressions
for truth value and execute a block of code as soon as one of
the conditions evaluates to true.
• The elif statement is optional. However, unlike else, for which
there can be at most one statement, there can be an arbitrary
number of elif statements following an if.
• An else statement contains the block of code that executes if
the conditional expression in the if statement resolves to 0 or a
false value.
• Like the elif, the else statement is an optional statement and
there could be at most only one else statement following an if .
Example

if x == 3:
print “X equals 3.”
elif x < 3:
print “X less than 3.”
elif x > 3:
print “X greater than 3.”
else:
print “X equals something else.”
Comparison Operators

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

• if value in sequence:
statements • An alternative if form
returns a value. This can
• The sequence can be simplify your code
– a range,
– string, Example:
– tuple, or list
• Examples: >> return x+1 if x < 0 else x
x=3 -1
if x in range(0, 10):

print("x is between 0 and 9“)
Nested if's

• An if/loop that is inside • if a > 5:
another if/loop is called a if b < 10:
nested if/loop. print(“green”)
• The statement to be else:
executed in an if statement
print(“blue”)
can be another if
• an else branch goes with the »for hours in range(24):
if which matches its » for minutes in
indentation range(60):
» print hours,‘:’,minutes
• what’s the difference of these two statements?

• if a > 5: • if a > 5:
if b < 10: if b < 10:
print(“green”) print(“green”)
else: else:
print(“blue”) print(“blue”)
Functions

 The two main uses of a function are
1. Code reuse
 Well-designed functions are often useful for many
programs. Once you write and debug one, you can reuse it.
 Functions facilitate both recursion and iteration.
2. Procedural decomposition
 Split a long program into functions allows you to separate
parts of the program, debug them in isolation, and then
compose them into a whole.
 Easier for reader to understand and debug.
Function definition
Functions are started with defFunction name and arguments

• def get_name (filename):
• line1
• line2
• return name

Indentation matters! Return value sent back to main routine
Determines what is in the name = get_name ()
function, and when the function
ends. The body of the function is anything indented beneath
this line
Function definition

def <name>(arg1, arg2, ..., argN):
<statements>
return <value>

def times(x,y):
return x*y
 def creates a function and assigns it a name
– 'main' code appears below functions
– Statements inside a function must be indented
 return sends a result back to the caller
 Arguments are passed by assignment
 Arguments and return types are not declared
Function
• What all can I do within the body of a function?
– Define local variables
– Call other functions ---- print(a) , print(b)
– Define new functions
• Functions come up in two ways in programs
• Function Definition
• Where the function is created
• Starts with def in python
• Function Call
• Where the function is used
• result = myFunction(argument1,argument2)
Function
• Functions have an important feature
• They can receive and return values
• Values are ‘passed to’ a function inside of ( ) when
called and returned using a special instruction---

def myFunction(input_values):
output_value= m* input_values
return output_value
• If a function needs to return a value back to the place in
the code where it is called (it uses a return statement)
Function Call
• Once the function is defined it can be called as many times as one likes. If
the function has a return it can be stored into a variable at the call
• The syntax for a function call is:
>>> def myfun(x, y):
return x * y

>>> myfun(3, 4)
12
>>> a= myfun(4, 5)
20
• Arguments are bound at the “call site”
• Call site: a point in the program where the function is called
• The binding is active up until the return of the function
• Parameters in Python are Call by Assignment
• Old values for the variables that are parameter names are
hidden, and these variables are simply made to refer to the
new values
• All assignment in Python, including binding function
parameters, uses reference semantics.
• All functions in Python have a return value, even if no return
line inside the code
• Functions without a return the special value None
• None is a special constant in the language
Variables and Functions: Local Variables

• We saw that arguments can be rebound for the duration of the
call
– What about variables that we define in the function
body?
• Abstractly there are two types of local variables
1) those which introduce a new variable
2) those which redefine an existing variable which was
initially defined outside the function definition
• Local variables, just like arguments, have a lifetime associated
with the function call
• Local Variables
–a=3
– y = 10
– def myFun(a):
– print (a)

– y=1
– myFun(4)
– print(a)
– print(y)
Variables and Functions

• Variables used in functions but defined outside of the
function can be changed

• Multiple calls to a function may yield different results if the
program “rebinds” such variables
x=3
def myFun():
print (x)
x=4
myFun()
x =5
myFun()
Functions default values for arguments

def f(a, b):
return a + b
def g(a, b=7):
return a + b
• consequence: only one function definition
f(3, 4)
g(3, 4) # returns 7
g(3) # returns 10
Default Values for Arguments
• You can provide default values for a function’s arguments
• These arguments are optional when the function is called

>>> def myfun(b, c=3, d=“hello”):

return b + c

>>> myfun(5,3,”hello”)

>>> myfun(5,3)

>>> myfun(5)
Keyword Arguments

• Can call a function with some/all of its arguments out of order as long as you specify
their names
>>> def foo(x,y,z):
return(2*x,4*y,8*z)
>>> foo(2,3,4)
(4, 12, 32)
>>> foo(z=4, y=2, x=3)
(6, 8, 32)
>>> foo(-2, z=-4, y=-3)
(-4, -12, -32)

• Can be combined with defaults, too
>>> def foo(x=1,y=2,z=3):
return(2*x,4*y,8*z)
>>> foo()
(2, 8, 24)
>>> foo(z=100)
(2, 8, 800)
Function Arguments
• Functions typically assume something important about the
arguments
• Will this work no matter what we provide as arguments?
def sumOfTwo(a,b):

return a+b
• Consider the following three cases:
• One of these cases will throw an error. This behavior is
defined by the code inside the function
res = sumOfTwo(1,2)
res = sumOfTwo(“Hello “, “World”)
res = sumOfTwo(“Hello”, 1)
Function Arguments
• There are two ways to handle this difficulty
1.Tell everyone what the function expects
2.Include checks inside the function to ensure the arguments
are what is expected
• A combination of both techniques should be used(Function
Documentation)

• This solution uses comments and if-statements.
• # This function expects two integers
# and returns -1 otherwise
def sumOfTwo(a,b):
if type(a) == int and type(b) == int :
return a+b
return -1
Modules
• A module is a python file (.py) with code in it
• Can contain any number of:
– Variables
– Functions
– Classes
• Some important built-in modules
• os operating system
• os.path path names
• sys Python interpreter
• math mathematical functions
• random random number generator
• re regular expressions
Math commands
• Python has useful commands for performing calculations.

Command name Description
abs(value) absolute value Constant Description
e 2.7182818...
ceil(value) rounds up
pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root

29
Example: math module
• To use many of these commands, you must write the
following at the top of your Python program:
>>> from math import * or
>>> import math
>>> dir(math)
['__doc__', '__name__', 'acos', 'asin',
'atan', 'atan2', 'ceil', 'cos', 'cosh',
'degrees', 'e', 'exp', 'fabs', 'floor',
'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians',
'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>> math.pi
3.1415926535897931
>>> math.sin(7)
0.65698659871878906
Using the Math Library

• Let’s write a program to compute the roots of a quadratic
equation!
-b � b 2 - 4ac
x=
2a

• The only part of this we don’t know how to find a square
root… but it’s in the math library!
Using the Math Library

• To use a library, we need to make sure this line is in our program:
import math
• Importing a library makes whatever functions are defined within it
available to the program.
• To access the sqrt library routine, we need to access it as
math.sqrt(x).
• Using this dot notation tells Python to use the sqrt function found in
the math library module.
• Alternate forms of import
– from math import *
– from math import sqrt
• Then don’t have to say math.sqrt
• Can just say disc = sqrt(…)
Assignment 2
• 1. Develop function that:
• To convert a Fahrenheit temperature to Centigrade. The
formula is C = (F -32) x 5/9

• 2. develop a function that compute the roots of a quadratic
equation (Using the Math Library)
• 3. temperature is less than or equal to 75 or humidity is less
than 70%
– Print a message saying the weather is good
• age is over 21 and age is less than 60
– Prints a message saying whether the person is eligible to
work

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.