0% found this document useful (0 votes)
5 views28 pages

Python Programming UNIT-II

Python programming

Uploaded by

Somen Debnath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views28 pages

Python Programming UNIT-II

Python programming

Uploaded by

Somen Debnath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT – II

CONTROL FLOW, LOOPS


Conditionals: Boolean values and operators, conditional (if), alternative (if-else),
chained conditional (if-elif-else); Iteration: while, for, break, continue. Functions---
function and its use, pass keyword, flow of execution, parameters and arguments.
Control Flow, Loops:
Boolean Values and Operators:
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:

>>> 5 = = 5

True

>>> 5 = = 6

False

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

>>> type(True)

<class 'bool'>

>>> type(False)

<class 'bool'>
The == operator is one of the relational operators; the others are: x != y # x is not equal
to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y

Note:
All expressions involving relational and logical operators will evaluate to either true or
false

Conditional (if):

The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.

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

if Statement Flowchart:

Fig: Operation of if statement

Example: Python if Statement

a=3
if a > 2:
print(a, "is greater")
print("done")

a = -1
if a < 0:
print(a, "a is smaller")
print("Finish")
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/if1.py
3 is greater
done
-1 a is smaller
Finish

#Program:
a=10
2
if a>9:
print("A is Greater than 9")

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/if2.py
A is Greater than 9

Alternative if (If-Else):

An else statement can be combined with an if statement. An else statement contains


the block of code (false block) that executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at most only one else
Statement following if.

Syntax of if - else :

if test expression:
Body of if stmts

else:
Body of else stmts

If - else Flowchart :

Fig: Operation of if – else statement

Example of if - else:

a=int(input('enter the number'))


if a>5:
print("a is greater")
3
else:
print("a is smaller than the input given")

Output:
C:/Users//AppData/Local/Programs/Python/Python38 32/pyyy/ifelse.py
enter the number 2
a is smaller than the input given

a=10
b=20
if a>b:
print("A is Greater than B")
else:
print("B is Greater than A")

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/if2.py
B is Greater than A
Chained Conditional: (If-elif-else):

The elif statement allows us to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE. Similar to the else,
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.
Syntax of if – elif - else :
If test expression:
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts

Flowchart of if – elif - else:

4
Fig: Operation of if – elif - else statement
Example of if - elif – else:
a=int(input('enter the number'))
b=int(input('enter the number'))
c=int(input('enter the number'))
if a>b:
print("a is greater")
elif b>c:
print("b is greater")
else:
print("c is greater")

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number 5
enter the number 2
enter the number 9
a is greater
>>>
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number 2
enter the number 5
enter the number 9
c is greater

var = 100
5
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)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/ifelif.py
3 - Got a true expression value
100

Iteration:
A loop statement allows us to execute a statement or group of statements multiple times
as long as the condition is true. Repeated execution of a set of statements with the help
of loops is called iteration.
Loops statements are used when we need to run same code again and again, each time
with a different value.

Statements:
In Python Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
3. Nested For Loops
While loop:

• Loops are either infinite or conditional. Python while loop keeps reiterating a
block of code defined inside it until the desired condition is met.
• The while loop contains a boolean expression and the code inside the loop is
repeatedly executed as long as the boolean expression is true.
• The statements that are executed inside while can be a single line of code or
a block of multiple statements.

Syntax:
while(expression):
Statement(s)
Flowchart:

6
Example Programs:
1.
i=1
while i<=6:
print("college")
i=i+1

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/wh1.py
college
college
college
college
college
college

2.
i=1
while i<=3:
print(" ", end= " ")
j=1
while j<=1:
print("CSE DEPT", end=" ")
j=j+1
i=i+1
print()

7
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/wh2.py
CSE DEPT
CSE DEPT
CSE DEPT
3.
i=1
while (i<10):
print(i)
i=i+1
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/wh3.py
1
2
3
4
5
6
7
8
9

4. a=1
b=1
while (a<10):
print ('Iteration',a)
a=a+1
b=b+1
if (b == 4):
break
print ('While loop terminated')
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/wh4.py
Iteration 1
Iteration 2
Iteration 3
While loop terminated
count = 0
while (count < 9):
print("The count is:", count) count = count + 1
print("Good bye!")

Output:
8
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/wh.py
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

For loop:
Python for loop is used for repeated execution of a group of statements for the desired
number of times. It iterates over the items of lists, tuples, strings, the dictionaries and
other
Syntax:
for var in sequence:
Flowchart:

Sample Program:

numbers = [1, 2, 4, 6, 11, 20]


seq=0
for val in numbers:
seq=val*val
print(seq)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/fr.py
9
1
4
16
36
121
400

Iterating over a list:


#list of items
list = ['M','R','C','E','T']
i=1
#Iterating over the list
for item in list:
print ('college ',i,' is ',item)
i = i+1

Output:
C:/Users/ /AppData/Local/Programs/Python/Python38-32/pyyy/lis.py
college 1 is M
college 2 is R
college 3 is C
college 4 is E
college 5 is T

Iterating over a Tuple:


tuple = (2,3,5,7)
print ('These are the first four prime numbers ')
#Iterating over the tuple
for a in tuple:
print (a)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fr3.py
These are the first four prime numbers
2
3
5
7
Iterating over a dictionary:
#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}
#Iterating over the dictionary to print keys
print ('Keys are:')

for keys in college:


print (keys)
10
#Iterating over the dictionary to print values
print ('Values are:')
for blocks in college.values():
print(blocks)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/dic.py
Keys are:
ces
it
ece
Values are:
block1
block2
block3

Iterating over a String:

#declare a string to iterate over


college = 'TRIPURA'
#Iterating over the string
for name in college:
print (name)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/str.py
T
R
I
P
U
R
A

Nested Loop:
When one Loop defined within another Loop is called Nested Loops.
Syntax:
for val in sequence:
for val in sequence:
statements
statements
# Example 1 of Nested For Loops (Pattern Programs)

for i in range(1,6):
for j in range(0,i):
11
print(i, end=" ")
print('')
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/nesforr.py
1
22
333
4444
55555

# Example 2 of Nested For Loops (Pattern Programs)

for i in range(1,6):
for j in range(5, i-1,-1):
print(i, end=" ")
print('')

C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/nesforr.py

Output:
11111
2222
333
44
5

Break and continue:

In Python, break and continue statements can alter the flow of a normal loop.
Sometimes we wish to terminate the current iteration or even the whole loop without
checking test expression. The break and continue statements are used in these cases.

Break:

The break statement terminates the loop containing it and control of the program flows
to the statement immediately after the body of the loop. If break statement is inside a
nested loop (loop inside another loop), break will terminate the innermost loop.

Flowchart:

12
The following shows the working of break statement in for and while loop:

for var in sequence:


# code inside for loop
If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop
while test expression

# code inside while loop


If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop

Example:
for val in "TU COLLEGE":
if val == " ":
break
print(val)
print("The end")

Output:
T
U
The end

13
# Program to display all the elements before number 88

for num in [11, 9, 88, 10, 90, 3, 19]:


print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break
Output:
11
9
88
The number 88 is found
Terminating the loop

# Program
for letter in "Python":
# First Example
if letter == "h":
break
print("Current Letter :", letter )

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/br.py
Current Letter : P
Current Letter : y
Current Letter : t

Continue:
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.

Flowchart:

14
The following shows the working of break statement in for and while loop:
for var in sequence:
# code inside for loop
If condition:
continue (if break condition satisfies it jumps to outside loop)
# code inside for loop
# code outside for loop

while test expression:


# code inside while loop
If condition:
continue(if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop

Example:
# Program to show the use of continue statement inside loops

for val in "string":


if val == "i":
continue
print(val)
print("The end")

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/cont.py
s
t
r
n
g
The end
# program to display only odd numbers
for num in [20, 11, 9, 66, 4, 89, 44]:
# Skipping the iteration when number is even

if num%2 == 0:
continue
# This statement will be skipped for all even
numbers print(num)
Output:
15
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/cont2.py
11
9
89
# First Example
for letter in "Python":
if letter == "h":
continue
print("Current Letter :", letter)
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/con1.py
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n

Pass:

In Python programming, pass is a null statement. The difference between a comment


and pass statement in Python is that, while the interpreter ignores a comment entirely,
pass is not ignored.
pass is just a placeholder for functionality to be added later.

Example:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/f1.y.py

Similarily we can also write,

def f(arg):
pass
# a function that does nothing (yet)

class C:
pass
# a class with no
Functions:

Functions and its use: Function is a group of related statements that perform a specific
16
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.
It avoids repetition and makes code reusable.

Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


Ex: abs(),all().ascii(),bool()………so on….

integer = -20
print('Absolute value of -20 is:', abs(integer))

Output:
Absolute value of -20 is: 20

2. User-defined functions - Functions defined by the users themselves.

def add_numbers(x,y):
sum = x + y
return sum

print("The sum is", add_numbers(5, 20))

Output:
The sum is 25

Flow of Execution:

1. The order in which statements are executed is called the flow of execution
2. Execution always begins at the first statement of the program.
3. Statements are executed one at a time, in order, from top to bottom.
4. 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.
5. Function calls are like a bypass in the flow of execution. Instead of going to the
next statement, the flow jumps to the first line of the called function, executes
all the statements there, and then comes back to pick up where it left off.

Note: When you read a program, don‟t read from top to bottom. Instead, follow the
flow of execution. This means that you will read the def statements as you are
scanning from top to bottom, but you should skip the statements of the function
definition until you reach a point where that function is called.

17
Example:
#example for flow of execution
print("welcome")
for x in range(3):
print(x)
print("Good morning college")
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/flowof.py
welcome
0
1
2
Good morning college

The flow/order of execution is: 2,3,4,3,4,3,4,5

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/flowof.py hi
hello
Good morning

done!
The flow/order of execution is: 2,5,6,7,2,3,4,7,8

Parameters and arguments:


Parameters are passed during the definition of function while Arguments are passed
during the function call.
18
Example:
#here a and b are parameters
def add(a,b): #//function definition
return a+b

#12 and 13 are arguments


#function call
result=add(12,13)
print(result)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/paraarg.py
25

There are three types of Python function arguments using which we can call a
function.

1. Default Arguments
2. Keyword Arguments
3. Variable-length Arguments

Syntax:

statements
.
.
.
functionname()

Function definition consists of following components:

1. Keyword def indicates the start of function header.


2. A function name to uniquely identify it. 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 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 same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

19
Example:

def hf():
hello world

hf()

In the above example we are just trying to execute the program by calling the function.
So it will not display any error and no output on to the screen but gets executed.

To get the statements of function need to be use print().

#calling function in python:


def hf():
print("hello world")

hf()

Output:
hello world

def hf():
print("hw")
print("gh kfjg 66666")

hf()
hf()
hf()

Output:
hw
gh kfjg 66666
hw
gh kfjg 66666
hw
gh kfjg 66666

def add(x,y):
c=x+y
print(c)

add(5,4)
Output:
9
20
def add_sub(x,y):
c=x+y
d=x-y
return c,d

print(add_sub(10,5))

Output:
(15, 5)

The return statement is used to exit a function and go back to the place from where
it was called. This statement can contain expression which gets evaluated and the
value is returned. If there is no expression in the statement or the return statement
itself is not present inside a function, then the function will return the None object.

def hf():

return "hw"

print(hf())

Output:
hw

def hello_f():
return "hellocollege"

print(hello_f().upper())

Output:

HELLOCOLLEGE

# Passing Arguments

def hello(wish):

return '{}'.format(wish)

print(hello(" "))
Output:

21
Here, the function wish() has two parameters. Since, we have called this function with
two arguments, it runs smoothly and we do not get any error. If we call it with different
number of arguments, the interpreter will give errors.

def wish(name,msg):
"""This function greets to the person
with the provided message"""
print("Hello",name + ' ' + msg)

wish(" ","Good morning!")

Output:

Hello Good morning!

Below is a call to this function with one and no arguments along with their respective
error
messages.
>>> wish(" ") # only one argument
TypeError: wish() missing 1 required positional argument: 'msg'
>>> wish() # no arguments
TypeError: wish() missing 2 required positional arguments: 'name' and 'msg'

def hello(wish,hello):
return "Hi" '{},{}'.format(wish,hello)
print(hello(" ","college"))

Output:

Hi ,college

#Keyword Arguments
When we call a function with some values, these values get assigned to the arguments
according to their position.
Python allows functions to be called using keyword arguments. When we call
functions in this way, the order (position) of the arguments can be changed.
(Or)

If you have some functions with many parameters and you want to specify only some
of them, then you can give values for such parameters by naming them - this is called
keyword arguments - we use the name (keyword) instead of the position (which we
have been using all along) to specify the arguments to the function.

There are two advantages - one, using the function is easier since we do not need to
worry about the order of the arguments. Two, we can give values to only those
22
parameters which we want, provided that the other parameters have default argument
values.

def func(a, b=5, c=10):


print ('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c=24)
func(c=50, a=100)
Output:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

Note:

The function named func has one parameter without default argument values,
followed by two parameters with default argument values.

In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the
value 5 and c gets the default value of 10.

In the second usage func(25, c=24), the variable a gets the value of 25 due to the
position of the argument. Then, the parameter c gets the value of 24 due to naming
i.e. keyword arguments. The variable b gets the default value of 5.

In the third usage func(c=50, a=100), we use keyword arguments completely to


specify the values. Notice, that we are specifying value for parameter c before that for
a even though a is defined before c in the function definition.

For example: if you define the function like below


def func(b=5, c=10,a): # shows error : non-default argument follows default argument

def print_name(name1, name2):


""" This function prints the name """
print (name1 + " and " + name2 + " are friends")

#calling the function

print_name(name2 = 'A',name1 = 'B')

23
Output:
B and A are friends

#Default Arguments
Function arguments can have default values in Python.
We can provide a default value to an argument by using the assignment operator (=)
def hello(wish,name='you'):
return '{},{}'.format(wish,name) print(hello("good morning"))

Output:
good morning,you

def hello(wish,name='you'):
return '{},{}'.format(wish,name) //print(wish + „ „ + name)

print(hello("good morning","nirosha"))// hello("good


morning","nirosha")

Output:
good morning,nirosha // good morning nirosha

Note: Any number of arguments in a function can have a default value. But once we
have a default argument, all the arguments to its right must also have default values.

This means to say, non-default arguments cannot follow default arguments. For
example, if we had defined the function header above as:

def hello(name='you', wish):


Syntax Error: non-default argument follows default argument

def sum(a=4, b=2): #2 is supplied as default argument

""" This function will print sum of two numbers if the


arguments are not supplied it will add the default value """
print (a+b)

sum(1,2) #calling with arguments


sum( ) #calling without arguments

Output:
3
6
24
Variable-length arguments

Sometimes you may need more arguments to process function then you mentioned in
the definition. If we don‟t know in advance about the arguments needed in function,
we can use variable-length arguments also called arbitrary arguments.

For this an asterisk (*) is placed before a parameter in function definition which can
hold non-keyworded variable-length arguments and a double asterisk (**) is placed
before a parameter in function which can hold keyworded variable-length arguments.

If we use one asterisk (*) like *var, then all the positional arguments from that point
till the end are collected as a tuple called „var‟ and if we use two asterisks (**) before
a variable like
**var, then all the positional arguments from that point till the end are collected as a
dictionary called „var‟.

def wish(*names):
"""This function greets all
the person in the names tuple."""

# name a tuple with arguments for name in names:


print("Hello",name)

wish(" ","CSE","SIR","MADAM")

Output:

Hello Hello CSE Hello SIR Hello MADAM

#Program to find area of a circle using function use single return value function
with argument.

pi=3.14
def areaOfCircle(r):
return pi*r*r

r=int(input("Enter radius of circle"))


print(areaOfCircle(r))
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter radius of circle 3
28.259999999999998

25
#Program to write sum different product and using arguments with return
value function.

def calculete(a,b):
total=a+b
diff=a-b
prod=a*b
div=a/b
mod=a%b
return total,diff,prod,div,mod

a=int(input("Enter a value"))
b=int(input("Enter b value"))

#function call
s,d,p,q,m = calculete(a,b)

print("Sum= ",s,"diff= ",d,"mul= ",p,"div= ",q,"mod= ",m) #print("diff=


",d)

#print("mul= ",p)

#print("div= ",q)

#print("mod= ",m)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value 6
Sum= 11 diff= -1 mul= 30 div= 0.8333333333333334 mod= 5

#program to find biggest of two numbers using functions.

def biggest(a,b):
if a>b :
return a
else :
return b

a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
26
big= biggest(a,b)
print("big number= ",big)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value-2 big number= 5

#program to find biggest of two numbers using functions. (nested if)

def biggest(a,b,c):
if a>b :
if a>c :
return a
else :
return c
else :
if b>c :
return b
else :
return c

a=int(input("Enter a value"))
b=int(input("Enter b value"))
c=int(input("Enter c value"))

#function call

big=biggest(a,b,c)

print("big number= ",big)

Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value -6
Enter c value 7
big number= 7

#Writer a program to read one subject mark and print pass or fail use single
return values function with argument.

def result(a):
if a>40:
27
return "pass"
else:
return "fail"
a=int(input("Enter one subject marks"))
print(result(a))
Output:
C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py

Enter one subject marks 35


fail

#Write a program to display TU CSE dept 10 times on the screen. (while loop)

def usingFunctions():
count =0
while count<10:
print(" TU cse dept",count)
count=count+1
usingFunctions()

Output:

C:/Users//AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
cse dept 0
cse dept 1
cse dept 2
cse dept 3
cse dept 4
cse dept 5
cse dept 6
cse dept 7

28

You might also like