Ii MSC Python Unit Ii Notes
Ii MSC Python Unit Ii Notes
CONTENTS
UNIT - 2
2.4 Functions 14
2.4.1 Defining a Function 14
Python programming language assumes any non-zero and non-null values as TRUE,
and if it is either zero or null, then it is assumed as FALSE value.
1 if statements
2 if...else statements
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
2.1.1 If Statements
The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.
Syntax
if expression:
statement(s)
If the Boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed.
If Boolean expression evaluates to FALSE, then the first set of code after the end of the
if statement(s) is executed.
Flow Diagram
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
else:
print "1 - Got a false expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
else:
print "2 - Got a false expression value"
print var2
The elif statement allows you to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE.
syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Example
var = 100
if var == 200:
print "1 - Got a true expression value"
print var
elif var == 150:
print "2 - Got a true expression value"
print var
elif var == 100:
print "3 - Got a true expression value"
print var
else:
print "4 - Got a false expression value"
print var
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.
A loop statement allows us to execute a statement or group of statements multiple times.
Python programming language allows using one loop inside another loop. Following
section shows few examples to illustrate the concept.
Syntax
The syntax for a nested while loop statement in Python programming language is as follows −
while expression:
while expression:
statement(s)
statement(s)
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print i, " is prime"
i=i+1
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!
1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
Syntax
Example
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var.
Next, the statements block is executed. Each item in the list is assigned to iterating_var,
and the statement(s) block is executed until the entire sequence is exhausted.
Flow Diagram
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
When execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
1 break statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.
With the break statement we can stop the loop even if the while condition is true:
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
OUTPUT:
1
2
3
With the continue statement we can stop the current iteration, and continue with the next:
Example
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
OUTPUT:
1
2
4
5
6
2.4 Functions
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.
Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
One or more valid python statements that make up the function body. Statements must have the
same indentation level (usually 4 spaces).
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
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.
Example:
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
greet('Paul')
ouput:
>>> greet('Paul')
Hello, Paul. Good morning!
You can call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives
a syntax error as follows −
Keyword arguments are related to the function calls. When you use keyword arguments
in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters. You
can also make keyword calls to the printme() function in the following ways
My string
The following example gives more clear picture. Note that the order of parameters does
not matter.
Name: miki
Age 50
The following example gives an idea on default arguments, it prints default age if it is
not passed
Name: miki
Age 50
Name: miki
Age 35
To process a function for more arguments than you specified while defining the
function.
These arguments are called variable-length arguments and are not named in the function
definition, unlike required and default arguments.
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments.
This tuple remains empty if no additional arguments are specified during the function
call. Following is a simple example −
Output is:
10
Output is:
70
60
50
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.
The following image shows the working of a recursive function called recuse.
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
def func(x):
y0 = x+ 1
y1 = x * 3
y2 = y0 ** 3
23
DEPARTMENT OF COMPUTER SCIENCE-RCASW-MS.K.RATHI DEVI
DCS33-PROGRAMMING USING PYTHON UNIT II
PART-A QUESTIONS
PART-C QUESTIONS