CONDITIONAL STATEMENTS,
LOOPING, CONTROL STATEMENTS
Unit Structure
3.0 Objectives
3.1 Introduction
3.2 Conditional Statements:
3.2.1 if statement
3.2.2 if-else,
3.2.3 if...elif...else
3.2.4 nested if –else
3.3 Looping Statements:
3.3.1 for loop
3.3.2 while loop
3.3.3 nested loops
3.4 Control statements:
3.4.1 Terminating loops
3.4.2 skipping specific conditions
3.5 Summary
3.6 References
3.7 Unit End Exercise
3.0 OBJECTIVES
After reading through this chapter, you will be able to –
To understand and use the conditional statementsin python.
To understand the loop control in python programming.
To understand the control statements in python.
To understand the concepts of python and able to apply it for
solving the complex problems.
3.1 INTRODUCTION
In order to write useful programs, we almost always need the
ability to check conditions and change the behavior of the program
accordingly. Conditional statements give us this ability.
The simplest form is the if statement:
if x > 0:
print 'x is positive'
26
The boolean expression after if is called the condition. If it is true,
then the indented statement gets executed. If not, nothing happens.
if statements have the same structure as function definitions: a
header followed by an indented body. Statements like this are
called compound statements.
There is no limit on the number of statements that can appear in the
body, but there has to be at least one. Occasionally, it is useful to
have a body with no statements. In that case, you can use the pass
statement, which does nothing.
if x < 0:
pass # need to handle negative values!
3.2 CONDITIONAL STATEMENTS
Conditional Statement in Python perform different
computations or actions depending on whether a specific Boolean
constraint evaluates to true or false. Conditional statements are handled
by IF statements in Python.
Story of Two if’s:
Consider the following if statement, coded in a C-like language:
if (p > q)
{ p = 1;
q = 2;
}
Now, look at the equivalent statement in the Python language:
if p > q:
p=1
q=2
what Python adds
what Python removes
1) Parentheses are optional
if (x < y) ---> if x < y
2) End-of-line is end of statement
C-like languages Python language
x = 1; x=1
3) End of indentation is end of block
Why Indentation Syntax?
A Few Special Cases
a = 1; b = 2; print (a + b)
27
You can chain together only simple statements, like assignments,
prints, and function calls.
3.2.1 if statement:
Syntax
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute
statement(s) only if the test expression is True.
If the test expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the
indentation. The body starts with an indentation and the first
unindented line marks the end.
Python interprets non-zero values as True. None and 0 are
interpreted as False.
Example: Python if Statement
# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print (num, "is a positive number.")
print ("This is always printed.")
num = -1
if num > 0:
print (num, "is a positive number.")
print ("This is also always printed.")
When you run the program, the output will be:
3 is a positive number.
This is always printed.
This is also always printed.
In the above example, num > 0 is the test expression.
The body of if is executed only if this evaluates to True.
When the variable num is equal to 3, test expression is true and
statements inside the body of if are executed.
If the variable num is equal to -1, test expression is false and
statements inside the body of if are skipped.
The print() statement falls outside of the if block (unindented).
Hence, it is executed regardless of the test expression.
28
3.2.2 if-else statement:
Syntax
if test expression:
Body of if
else:
Body of else
The if...else statement evaluates test expression and will execute
the body of if only when the test condition is True.
If the condition is False, the body of else is executed. Indentation is
used to separate the blocks.
Example of if...else
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print ("Positive or Zero")
else:
print ("Negative number")
Output:
Positive or Zero
In the above example, when num is equal to 3, the test expression
is true and the body of if is executed and the body of else is
skipped.
If num is equal to -5, the test expression is false and the body
of else is executed and the body of if is skipped.
If num is equal to 0, the test expression is true and body of if is
executed and body of else is skipped.
3.2.3 if...elif...else Statement:
Syntax
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
29
The elif is short for else if. It allows us to check for multiple
expressions.
If the condition for if is False, it checks the condition of the
next elif block and so on.
If all the conditions are False, the body of else is executed.
Only one block among the several if...elif...else blocks is executed
according to the condition.
The if block can have only one else block. But it can have
multiple elif blocks.
Example of if...elif...else:
'''In this program,
we check if the number is positive or
negative or zero and
display an appropriate message'''
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print ("Positive number")
elif num == 0:
print("Zero")
else:
print ("Negative number")
When variable num is positive, Positive number is printed.
If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed.
3.2.4 nested if –else:
We can have a if...elif...else statement inside
another if...elif...else statement. This is called nesting in computer
programming.
Any number of these statements can be nested inside one another.
Indentation is the only way to figure out the level of nesting. They
can get confusing, so they must be avoided unless necessary.
Python Nested if Example
'''In this program, we input a number
check if the number is positive or
negative or zero and display
30
an appropriate message
This time we use nested if statement'''
num = float (input ("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print ("Positive number")
else:
print ("Negative number")
Output1:
Enter a number: 5
Positive number
Output2:
Enter a number: -1
Negative number
Output3:
Enter a number: 0
Zero
3.3 LOOPING STATEMENTS
In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second,
and so on. There may be a situation when you need to execute a
block of code several number of times.
Programming languages provide various control structures that
allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of
statements multiple times.
3.3.1 for loop:
The for loop in Python is used to iterate over a sequence
(list, tuple, string) or other iterable objects. Iterating over a
sequence is called traversal.
Syntax of for Loop
for val in sequence:
Body of for
31
Here, val is the variable that takes the value of the item inside the
sequence on each iteration.
Loop continues until we reach the last item in the sequence. The
body of for loop is separated from the rest of the code using
indentation.
Example: Python for Loop
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print ("The sum is", sum)
When you run the program, the output will be:
The sum is 48
The range () function:
We can generate a sequence of numbers using range
() function. range (10) will generate numbers from 0 to 9 (10
numbers).
We can also define the start, stop and step size as range (start,
stop,step_size). step_size defaults to 1, start to 0 and stop is end of
object if not provided.
This function does not store all the values in memory; it would be
inefficient. So, it remembers the start, stop, step size and generates
the next number on the go.
To force this function to output all the items, we can use the
function list().
Example:
print(range(10))
print(list(range(10)))
print (list (range (2, 8)))
print (list (range (2, 20, 3)))
Output:
range (0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]
32
We can use the range () function in for loops to iterate through a
sequence of numbers. It can be combined with the len () function to
iterate through a sequence using indexing. Here is an example.
# Program to iterate through a list using indexing
city = ['pune', 'mumbai', 'delhi']
# iterate over the list using index
for i in range(len(city)):
print ("I like", city[i])
Output:
I like pune
I like mumbai
I like delhi
for loop with else:
A for loop can have an optional else block as well. The else part is
executed if the items in the sequence used in for loop exhausts.
The break keyword can be used to stop a for loop. In such cases,
the else part is ignored.
Hence, a for loop's else part runs if no break occurs.
Example:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
When you run the program, the output will be:
0
1
5
No items left.
Here, the for loop prints items of the list until the loop exhausts.
When the for-loop exhausts, it executes the block of code in
the else and prints No items left.
This for...else statement can be used with the break keyword to run
the else block only when the break keyword was not executed.
Example:
# program to display student's marks from record
student_name = 'Soyuj'
marks = {'Ram': 90, 'Shayam': 55, 'Sujit': 77}
33
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print ('No entry with that name found.')
Output:
No entry with that name found.
3.3.2 while loop:
The while loop in Python is used to iterate over a block of code as
long as the test expression (condition) is true.
We generally use while loop when we don't know the number of
times to iterate beforehand.
Syntax of while Loop in Python
while test_expression:
Body of while
In the while loop, test expression is checked first. The body of the
loop is entered only if the test_expression evaluates to True.
After one iteration, the test expression is checked again. This
process continues until the test_expression evaluates to False.
In Python, the body of the while loop is determined through
indentation.
The body starts with indentation and the first unindented line marks
the end.
Python interprets any non-zero value as True. None and 0 are
interpreted as False.
Example: Python while Loop
# Program to add natural
# numbers up to
# sum = 1+2+3+...+n
# To take input from the user,
# n = int (input ("Enter n: "))
n = 10
# initialize sum and counter
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
34
# print the sum
print ("The sum is", sum)
When you run the program, the output will be:
Enter n: 10
The sum is 55
In the above program, the test expression will be True as long as
our counter variable i is less than or equal to n (10 in our program).
We need to increase the value of the counter variable in the body of
the loop. This is very important. Failing to do so will result in an
infinite loop (never-ending loop).
While loop with else:
Same as with for loops, while loops can also have an
optional else block.
The else part is executed if the condition in the while loop
evaluates to False.
The while loop can be terminated with a break statement. In such
cases, the else part is ignored. Hence, a while loop's else part runs
if no break occurs and the condition is false.
Example:
'''Example to illustrate
the use of else statement
with the while loop'''
counter = 0
while counter < 3:
print ("Inside loop")
counter = counter + 1
else:
print ("Inside else")
Output:
Inside loop
Inside loop
Inside loop
Inside else
Here, we use a counter variable to print the string Inside loop three
times.
On the fourth iteration, the condition in while becomes False.
Hence, the else part is executed.
3.3.3 Nested Loops:
Loops can be nested in Python similar to nested loops in
other programming languages.
35
Nested loop allows us to create one loop inside another loop.
It is similar to nested conditional statements like nested if
statement.
Nesting of loop can be implemented on both for loop and while
loop.
We can use any loop inside loop for example, for loop can have
while loop in it.
Nested for loop:
For loop can hold another for loop inside it.
In above situation inside for loop will finish its execution first and
the control will be returned back to outside for loop.
Syntax
for iterator in iterable:
for iterator2 in iterable2:
statement(s) of inside for loop
statement(s) of outside for loop
In this first for loop will initiate the iteration and later
second for loop will start its first iteration and till second for loop
complete its all iterations the control will not be given to
first for loop and statements of inside for loop will be executed.
Once all iterations of inside for loop are completed then statements
of outside for loop will be executed and next iteration from
first for loop will begin.
Example1: of nested for loop in python:
for i in range (1,11):
for j in range (1,11):
m=i*j
print (m, end=' ')
print (“Table of “, i)
Output:
1 2 3 4 5 6 7 8 9 10 Table of 1
2 4 6 8 10 12 14 16 18 20 Table of 2
3 6 9 12 15 18 21 24 27 30 Table of 3
4 8 12 16 20 24 28 32 36 40 Table of 4
5 10 15 20 25 30 35 40 45 50 Table of 5
6 12 18 24 30 36 42 48 54 60 Table of 6
7 14 21 28 35 42 49 56 63 70 Table of 7
8 16 24 32 40 48 56 64 72 80 Table of 8
36
9 18 27 36 45 54 63 72 81 90 Table of 9
10 20 30 40 50 60 70 80 90 100 Table of 10
Example2: of nested for loop in python:
for i in range (10):
for j in range(i):
print ("*”, end=' ')
print (" ")
Output:
*
**
***
****
*****
******
*******
********
*********
Nested while loop:
While loop can hold another while loop inside it.
In above situation inside while loop will finish its execution first
and the control will be returned back to outside while loop.
Syntax
while expression:
while expression2:
statement(s) of inside while loop
statement(s) of outside while loop
In this first while loop will initiate the iteration and later
second while loop will start its first iteration and till
second while loop complete its all iterations the control will not be
given to first while loop and statements of inside while loop will be
executed.
Once all iterations of inside while loop are completed than
statements of outside while loop will be executed and next iteration
from first while loop will begin.
It is also possible that if first condition in while loop expression is
False then second while loop will never be executed.
Example1: Program to show nested while loop
p=1
37
while p<10:
q=1
while q<=p:
print (p, end=" ")
q+=1
p+=1
print (" ")
Output:
1
22
333
4444
55555
666666
7777777
88888888
999999999
Exampleb2: Program to nested while loop
x=10
while x>1:
y=10
while y>=x:
print (x, end=" ")
y-=1
x-=1
print(" ")
Output:
10
99
888
7777
66666
555555
4444444
33333333
222222222
38
3.4 CONTROL STATEMENTS:
Control statements in python are used to control the order of
execution of the program based on the values and logic.
Python provides us with three types of Control Statements:
Continue
Break
3.4.1 Terminating loops:
The break statement is used inside the loop to exit out of the loop.
It is useful when we want to terminate the loop as soon as the
condition is fulfilled instead of doing the remaining iterations.
It reduces execution time. Whenever the controller encountered a
break statement, it comes out of that loop immediately.
Syntax of break statement
for element in sequence:
if condition:
break
Example:
for num in range (10):
if num > 5:
print ("stop processing.")
break
print(num)
Output:
0
1
2
3
4
5
stop processing.
3.4.2 skipping specific conditions:
The continue statement is used to skip the current iteration
and continue with the next iteration.
Syntax of continue statement:
for element in sequence:
if condition:
continue
39
Example of a continue statement:
for num in range (3, 8):
if num == 5:
continue
else:
print(num)
Output:
3
4
6
7
3.5 SUMMARY
In this chapter we studied conditional statements like if, if-else, if-
elif-else and nested if-else statements for solving complex
problems in python.
More focuses on loop control in python basically two types of
loops available in python like while loop, for loop and nested loop.
Studied how to control the loop using break and continue
statements in order to skipping specific condition and terminating
loops.
3.6 UNIT END EXERCISE
1. Print the squares of numbers from 1 to 10 using loop control.
2. Write a Python program to print the prime numbers of up to a
given number, accept the number from the user.
3. Write a Python program to print the following pattern
1
23
456
78910
1112131415
4. Write a Python program to construct the following pattern, using a
nested for loop.
*
**
***
****
*****
****
***
**
*
40
5. Write a Python program to count the number of even and odd
numbers from a series of numbers.
Sample numbers: numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
Expected Output:
Number of even numbers: 5
Number of odd numbers: 4
6. Write a Python program that prints all the numbers from 0 to 6
except 3 and 6
Note: Use 'continue' statement.
Expected Output: 0 1 2 4 5
7. Print First 10 natural numbers using while loop
8. Print the following pattern
1
12
123
1234
12345
9. Display numbers from -10 to -1 using for loop
10. Print the following pattern
*
**
***
*****
******
3.7 REFERENCES
Think Python by Allen Downey 1st edition.
Python Programming for Beginners By Prof. Rahul E. Borate, Dr.
Sunil Khilari, Prof. Rahul S. Navale.
[Link]
[Link]
[Link]
[Link]
*****
41
FUNCTIONS
Unit Structure
4.0 Objectives
4.1 Introduction
4.2 Function Calls
4.3 Type Conversion Functions
4.4 Math Functions
4.5 Adding New Functions
4.6 Definitions and Uses
4.6.1 Flow of Execution
4.6.2 Parameters and Arguments
4.6.3 Variables and Parameters Are Local
4.6.4 Stack Diagrams
4.7 Fruitful Functions and Void Functions
4.8 Why Functions?
4.9 Importing with from, Return Values, Incremental Development
4.10 Boolean Functions
4.11 More Recursion, Leap of Faith, Checking Types
4.12 Summary
4.13 References
4.14 Unit End Exercise
4.0 OBJECTIVES
After reading through this chapter, you will be able to –
To understand and use the function calls.
To understand the type conversion functions.
To understand the math function.
To adding new function.
To understand the Parameters and Arguments.
To understand the fruitful functions and void functions.
To understand the boolean functions, Recursion, checking types
etc.
4.1 INTRODUCTION
One of the core principles of any programming language is, "Don't
Repeat Yourself". If you have an action that should occur many
42
times, you can define that action once and then call that code
whenever you need to carry out that action.
We are already repeating ourselves in our code, so this is a good
time to introduce simple functions. Functions mean less work for
us as programmers, and effective use of functions results in code
that is less error.
4.2 FUNCTION CALLS
What is a function in Python?
In Python, a function is a group of related statements that performs
a specific task.
Functions help break our program into smaller and modular
chunks. As our program grows larger and larger, functions make it
more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition that consists of the following
components.
1. Keyword def that marks the start of the function header.
2. A function name to uniquely identify the function. Function
naming follows the same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a
function. They are optional.
4. A colon (:) to mark the end of the function header.
5. Optional documentation string (docstring) to describe what the
function does.
6. One or more valid python statements that make up the function
body. Statements must have the same indentation level (usually 4
spaces).
7. An optional return statement to return a value from the function.
Example:
def greeting(name):
"""
This function greets to
the person passed in as
43
a parameter
"""
print ("Hello, " + name + ". Good morning!")
How to call a function in python?
Once we have defined a function, we can call it from another
function, program or even the Python prompt.
To call a function we simply type the function name with
appropriate parameters.
>>> greeting('IDOL')
Hello, IDOL. Good morning!
4.3 TYPE CONVERSION FUNCTIONS
The process of converting the value of one data type (integer,
string, float, etc.) to another data type is called type conversion.
Python has two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion
1. Implicit Type Conversion:
In Implicit type conversion, Python automatically converts one
data type to another data type. This process doesn't need any user
involvement.
Let's see an example where Python promotes the conversion of the
lower data type (integer) to the higher data type (float) to avoid
data loss.
Example 1: Converting integer to float
num_int = 123
num_float = 1.23
num_new = num_int + num_float
print (“datatype of num_int:”, type(num_int))
print (“datatype of num_float:” type(num_float))
print (“Value of num_new:”, num_new)
print (“datatype of num_new:”, type(num_new))
Output:
datatype of num_int: <class 'int'>
datatype of num_float: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
44
Example 2: Addition of string(higher) data type and integer(lower)
datatype
num_int = 123
num_str = "456"
print ("Data type of num_int:”, type(num_int))
print ("Data type of num_str:”, type(num_str))
print(num_int+num_str)
Output:
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
Traceback (most recent call last):
File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
In the above program,
We add two variables num_int and num_str.
As we can see from the output, we got TypeError. Python is not
able to use Implicit Conversion in such conditions.
However, Python has a solution for these types of situations which
is known as Explicit Conversion.
2. Explicit Type Conversion:
In Explicit Type Conversion, users convert the data type of an
object to required data type. We use the predefined functions like
int(), float(), str(), etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.
Syntax:
<required_datatype>(expression)
Example 3: Addition of string and integer using explicit conversion
num_int = 123
num_str = "456"
print ("Data type of num_int:”, type(num_int))
print ("Data type of num_str before Type Casting:”, type(num_str))
num_str = int(num_str)
print ("Data type of num_str after Type Casting:”, type(num_str))
num_sum = num_int + num_str
45
print ("Sum of num_int and num_str:”, num_sum)
print ("Data type of the sum:”, type(num_sum))
Output:
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>
Type Conversion is the conversion of object from one data type to
another data type.
Implicit Type Conversion is automatically performed by the
Python interpreter.
Python avoids the loss of data in Implicit Type Conversion.
Explicit Type Conversion is also called Type Casting, the data
types of objects are converted using predefined functions by the
user.
In Type Casting, loss of data may occur as we enforce the object to
a specific data type.
4.4 MATH FUNCTIONS
The math module is a standard module in Python and is always
available. To use mathematical functions under this module, you
have to import the module using import math.
For example
# Square root calculation
import math
[Link](4)
Functions in Python Math Module
Pi is a well-known mathematical constant, which is defined as the
ratio of the circumference to the diameter of a circle and its value is
3.141592653589793.
>>> import math
>>>[Link]
3.141592653589793
Another well-known mathematical constant defined in the math
module is e. It is called Euler's number and it is a base of the
natural logarithm. Its value is 2.718281828459045.
>>> import math
>>>math.e
2.718281828459045
46
The math module contains functions for calculating various
trigonometric ratios for a given angle. The functions (sin, cos, tan,
etc.) need the angle in radians as an argument. We, on the other
hand, are used to express the angle in degrees. The math module
presents two angle conversion functions: degrees () and radians (),
to convert the angle from degrees to radians and vice versa.
>>> import math
>>>[Link](30)
0.5235987755982988
>>>[Link]([Link]/6)
29.999999999999996
[Link]()
The [Link]() method returns the natural logarithm of a given
number. The natural logarithm is calculated to the base e.
>>> import math
>>>[Link](10)
2.302585092994046
[Link]()
The [Link]() method returns a float number after raising e to the
power of the given number. In other words, exp(x) gives e**x.
>>> import math
>>>[Link](10)
22026.465794806718
[Link]()
The [Link]() method receives two float arguments, raises the first to
the second and returns the result. In other words, pow(4,4) is
equivalent to 4**4.
>>> import math
>>>[Link](2,4)
16.0
>>> 2**4
16
[Link]()
The [Link]() method returns the square root of a given number.
>>> import math
>>>[Link](100)
10.0
47
>>>[Link](3)
1.7320508075688772
4.5 ADDING NEW FUNCTIONS
So far, we have only been using the functions that come with
Python, but it is also possible to add new functions.
A function definition specifies the name of a new function and the
sequence of statements that execute when the function is called.
Example:
def print_lyrics():
print ("I'm a lumberjack, and I'm okay.")
print ("I sleep all night and I work all day.")
def is a keyword that indicates that this is a function definition. The
name of the function is print_lyrics. 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, and
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.
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; most people
use single quotes except in cases like this where a single quote
appears in the string.
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:
def repeat_lyrics():
print_lyrics()
print_lyrics()
And then call repeat_lyrics:
>>> repeat_lyrics()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
48
4.6 DEFINITIONS AND USES
Pulling together the code fragments from the previous section, the
whole program looks like this:
def print_lyrics ():
print ("I'm a lumberjack, and I'm okay.")
print ("I sleep all night and I work all day.")
def repeat_lyrics ():
print_lyrics ()
print_lyrics ()
repeat_lyrics ()
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.
4.6.1 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.
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.
4.6.2 Parameters and Arguments:
Some of the built-in functions we have seen require arguments. For
example, when you call [Link] you pass a number as an
argument. Some functions take more than one
argument: [Link] takes two, the base and the exponent.
49
Inside the function, the arguments are assigned to variables
called parameters. Here is an example of a user-defined function
that takes an argument.
def print_twice(bruce):
print(bruce)
print(bruce)
This function assigns the argument to a parameter named bruce.
When the function is called, it prints the value of the parameter
twice.
>>> print_twice('Spam')
Spam
Spam
>>> print_twice (17)
17
17
>>> print_twice([Link])
3.14159265359
3.14159265359
The same rules of composition that apply to built-in functions also
apply to user-defined functions, so we can use any kind of
expression as an argument for print_twice.
>>> print_twice ('Spam '*4)
Spam SpamSpamSpam
Spam SpamSpamSpam
>>> print_twice([Link]([Link]))
-1.0
-1.0
The argument is evaluated before the function is called, so in the
examples the expressions 'Spam '*4 and [Link]([Link]) are only
evaluated once.
4.6.3 Variables and Parameters Are Local:
When you create a variable inside a function, it is local, which
means that it only exists inside the function.
For example
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
50
This function takes two arguments, concatenates them, and prints the
result twice. Here is an example that uses it:
>>> line1 = 'Bing tiddle '
>>> line2 = 'tiddle bang.'
>>> cat_twice(line1, line2)
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.
When cat_twice terminates, the variable cat is destroyed. If we try
to print it, we get an exception:
>>> print cat
NameError: name 'cat' is not defined
Parameters are also local. For example, outside print_twice, there is
no such thing as bruce.
4.6.4 Stack Diagrams:
To keep track of which variables can be used where, it is
sometimes useful to draw a stack diagram. Like state diagrams,
stack diagrams show the value of each variable, but they also show
the function each variable belongs to.
Each function is represented by a frame. A frame is a box with the
name of a function beside it and the parameters and variables of the
function inside it. The stack diagram for the previous example is
shown in Figure.
Fig. Stack Diagram
The frames are arranged in a stack that indicates which function
called which, and so on. In this example, print_twice was called
by cat_twice, and cat_twice was called by __main__, which is a
special name for the topmost frame. When you create a variable
outside of any function, it belongs to __main__.
51
Each parameter refers to the same value as its corresponding
argument. So, part1 has the same value as line1, part2 has the same
value as line2, and bruce has the same value as cat.
If an error occurs during a function call, Python prints the name of
the function, and the name of the function that called it, and the
name of the function that called that, all the way back to __main__.
4.7 FRUITFUL FUNCTIONS AND VOID FUNCTIONS
Some of the functions we are using, such as the math functions,
yield results; for lack of a better name, I call them fruitful
functions. Other functions, like print_twice, perform an action but
don’t return a value. They are called void functions.
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:
x = [Link](radians)
golden = ([Link](5) + 1) / 2
When you call a function in interactive mode, Python displays
the result:
>>>[Link](5)
2.2360679774997898
But in a script, if you call a fruitful function all by itself, the return
value is lost forever
[Link](5)
This script computes the square root of 5, but since it doesn’t store 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.
>>> result = print_twice('Bing')
Bing
Bing
>>> print(result)
None
The value None is not the same as the string 'None'. It is a special
value that has its own type:
>>> print type(None)
<type 'NoneType'>
The functions we have written so far are all void.
52
4.8 WHY FUNCTIONS?
It may not be clear why it is worth the trouble to divide a program
into functions. There are several reasons:
Creating a new function gives you an opportunity to name a group
of statements, which makes your program easier to read and debug.
Functions can make a program smaller by eliminating repetitive
code. Later, if you make a change, you only have to make it in one
place.
Dividing a long program into functions allows you to debug the
parts one at a time and then assemble them into a working whole.
Well-designed functions are often useful for many programs. Once
you write and debug one, you can reuse it.
4.9 IMPORTING WITH FROM, RETURN VALUES,
INCREMENTAL DEVELOPMENT
Importing with from:
Python provides two ways to import modules, we have already seen
one:
>>> import math
>>> print math
<module 'math' (built-in)>
>>> print [Link]
3.14159265359
If you import math, you get a module object named math. The
module object contains constants like pi and functions
like sin and exp.
But if you try to access pi directly, you get an error.
>>> print pi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pi' is not defined
As an alternative, you can import an object from a module like this:
>>> from math import pi
Now you can access pi directly, without dot notation.
>>> print pi
3.14159265359
Or you can use the star operator to import everything from the module:
>>> from math import *
53
>>> cos(pi)
-1.0
The advantage of importing everything from the math module is
that your code can be more concise.
The disadvantage is that there might be conflicts between names
defined in different modules, or between a name from a module
and one of your variables.
4.10 BOOLEAN FUNCTIONS
Syntax for boolean function is as follows
Bool([value])
As we seen in the syntax that the bool() function can take a single
parameter (value that needs to be converted). It converts the given
value to True or False.
If we don’t pass any value to bool() function, it returns False.
bool() function returns a boolean value and this function
returns False for all the following values
1. None
2. False
3. Zero number of any type such as int, float and complex. For
example: 0, 0.0, 0j
4. Empty list [], Empty tuple (), Empty String ”.
5. Empty dictionary {}.
6. objects of Classes that implements __bool__() or __len()__
method, which returns 0 or False
bool() function returns True for all other values except the values
that are mentioned above.
Example: bool() function
In the following example, we will check the output of bool() function
for the given values. We have different values of different data
types and we are printing the return value of bool() function in the
output.
# empty list
lis = []
print(lis,'is',bool(lis))
# empty tuple
t = ()
print(t,'is',bool(t))
# zero complex number
54
c = 0 + 0j
print(c,'is',bool(c))
num = 99
print(num, 'is', bool(num))
val = None
print(val,'is',bool(val))
val = True
print(val,'is',bool(val))
# empty string
str = ''
print(str,'is',bool(str))
str = 'Hello'
print(str,'is',bool(str))
Output:
[] is False
() is False
0j is False
99 is True
None is False
True is True
is False
Hello is True
4.11 MORE RECURSION, CHECKING TYPES:
What is recursion?
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors
facing each other. Any object in between them would be reflected
recursively.
In Python, we know that a function can call other functions. It is
even possible for the function to call itself. These types of construct
are termed as recursive functions.
55
Following is an example of a recursive function to find the factorial
of an integer.
Factorial of a number is the product of all the integers from 1 to that
number. For example, the factorial of 6 (denoted as 6!)
is 1*2*3*4*5*6 = 720.
Example of a recursive function
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output:
The factorial of 3 is 6
In the above example, factorial () is a recursive function as it calls
itself. When we call this function with a positive integer, it will
recursively call itself by decreasing the number.
Each function multiplies the number with the factorial of the
number below it until it is equal to one. This recursive call can be
explained in the following steps.
factorial (3) # 1st call with 3
3 * factorial (2) # 2nd call with 2
56
3 * 2 * factorial (1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call
4.12 SUMMARY
In this chapter we studied function call, type conversion functions
in Python Programming Language.
In this chapter we are more focused on math function and adding
new function in python.
Elaborating on definitions and uses of function, parameters and
arguments in python.
Also studied fruitful functions and void functions, importing with
from, boolean functions and recursion in python.
4.14 UNIT END EXERCISE
1. Python provides a built-in function called len that returns the length
of a string, so the value of len('allen') is 5.
Write a function named right_justify that takes a string named s as
a parameter and prints the string with enough leading spaces so that
the last letter of the string is in column 70 of the display.
>>> right_justify('allen')
allen
2. Write a Python function to sum all the numbers in a list. Go to the
editor
Sample List : (8, 2, 3, 0, 7)
Expected Output : 20
3. Write a Python program to reverse a string
Sample String : "1234abcd"
Expected Output : "dcba4321"
4. Write a Python function to calculate the factorial of a number (a
non-negative integer). The function accepts the number as an
argument.
5. Write a Python program to print the even numbers from a given
list.
Sample List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result: [2, 4, 6, 8]
57
4.13 REFERENCES
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Think Python by Allen Downey 1st edition.
*****
58