UNIT III
CONTROL FLOW, FUNCTIONS, STRINGS
BOOLEAN VALUES AND OPERATOR
Boolean Operators are those that result in the Boolean values of True and
False. These include and, or and not. While and & or require 2 operands, not is
a unary operator. Boolean operators are most commonly used in arithmetic
computations and logical comparisons.
BOOLEAN OPERATOR
Types of Boolean Operators in Python
There are two types of operators in Python that return boolean values, i.e.,
Logical operators and Comparison operators.
Since both these operators have return types as boolean, they are also
termed, Boolean operators.
1. Comparison operators
If you were to choose a stream between Science, Commerce and Humanities,
you would weigh out their pros and cons and accordingly take a decision.
When we want to decide between 2 or more options, we compare them based
on their weights.
In programming, comparison operators are used to comparing values and
evaluate down to a single Boolean value of either True or False.
Operator Title Description Example Output
It results in a True if the 2 print(1==1)
True
== Equal to operands are equal, and a print((10-
False
False if unequal. 5+2)==(7-9+1))
It results in a True if the 2 print(3!=2)
Not equal True
!= operands are unequal, and print((7-1*2)!
to True
a False if equal. =(8*2+4))
It results in a True if the
print(1<1)
first operand is smaller False
< Less than print((10-5+2)<(7-
than the second, else a False
9+1))
False.
It results in a True if the
print(1>1)
Greater first operand is greater False
> print((10-5+2)>(7-
than than the second, else a True
9+1))
False.
<= Less than It results in a True if the print(3<=2) False
Operator Title Description Example Output
first operand is lesser than
print((7-
or equal to or equal to the second, else True
1*2)<=(8*2+4)
a False.
It results in a True if the
Greater print(1>=1)
first operand is greater True
>= than or print((10-
than or equal to the False
equal to 5+2)>=(7-9+1))
second, else a False.
2. Logical Operators
The logical operators and, or and not are also referred to as Boolean
operators. and and or require 2 operands and are thus called binary
operators. On the other hand, not is a unary operator which works on one
operand.
Operator Description Representation
and True if both are True x and y
or True if at least one is True x or y
not True only if False not x
and It is a binary operator surrounded by 2 operands (variables,
constants or expressions). It analyzes them and results in a value based
on the following fact: ‘It results in True only if the operands on both
sides of the AND are True.’
**Consider the statement: **
I will come to the party if mom is back from work and she permits me to
leave.
The statement implies that I will go to the party only if both the
conditions are satisfied.
Thus, let’s consider 2 example cases and the results based on the and
operator.
Case 1:
Condition 1: Mom is back.
Condition 2: She doesn’t permit me to leave.
Result: I will not come to the party.
Case 2:
Condition 1: Mom is back.
Condition 2: She permits me to leave.
Result: I will come to the party.
Example:
x=5
y = 10
z = 11
print((x > y) and (y > z))
print((x > y) and (y < z))
print((x < y) and (y > z))
print((x < y) and (y < z))
Output:
False
False
False
True
or It is a binary operator surrounded by 2 operands (variables,
constants or expressions). It analyzes them and results in a value based
on the following fact: ‘It results in False only if the operands on both
sides of the OR are False.’
Consider the statement:
I will rest if Mohan disconnects the call sooner or there is no extra class.
The statement implies that I will rest if both conditions are satisfied and not if
none of them is.
Thus, let’s consider 2 example cases and the results based on the or operator.
Case 1:
Condition 1: Mohan disconnects the call sooner
Condition 2: There is no extra class
Result: I will rest.
Case 2:
Condition 1: Mohan does not disconnect the call sooner
Condition 2: There is no extra class.
Result: I will not rest.
Example:
x=5
y = 10
z = 11
print((x > y) or (y > z))
print((x > y) or (y < z))
print((x < y) or (y > z))
print((x < y) or (y < z))
Output:
False
True
True
True
not It is a unary operator that is used to negate the expression after
succeeding the operator. According to this, every True expression
becomes False, and vice versa.
Consider the statement:
Sunita will not go to school.
If the above statement is true, the statement ‘Sunita will go to school’
would be false.
Thus, not interchanges True and False values.
Example:
x = True
y = False
print(not x)
print(not y)
Output:
False
True
Truth Table for and Operation:
X Y X and Y
False False False
True False False
False True False
True True True
Truth Table for or Operation:
X Y X or Y
False False False
True False True
False True True
True True True
Truth Table for not Operation:
X not X
True False
False True
CONDITIONALS
Conditional if
Alternative if… else
Chained if…elif…else
Nested if….else
Conditional (if):
conditional (if) is used to test a condition, if the condition is true the
statements inside if will be executed.
syntax:
if(condition 1):
Statement 1
Flowchart:
Example:
1. Program to provide flat rs 500, if the purchase amount is greater than
2000.
2. Program to provide bonus mark if the category is sports.
Program to provide flat rs 500, if the purchase amount is greater than
2000.
purchase=eval(input(“enter your purchase amount”))
if(purchase>=2000):
purchase=purchase-500
print(“amount to pay”,purchase)
output
enter your purchase
amount
2500
amount to pay
2000
Program to provide bonus mark if the category is sports
m=eval(input(“enter ur mark out of 100”))
c=input(“enter ur categery G/S”)
if(c==”S”):
m=m+5
print(“mark is”,m)
output
enter ur mark out of 100
85
enter ur categery G/S
mark is 90
alternative (if-else)
In the alternative the condition must be true or false. In this else statement
can be combined with if statement. The else statement contains the block of
code that executes when the condition is false. If the condition is true
statements inside the if get executed otherwise else part gets executed. The
alternatives are called branches, because they are branches in the flow of
execution.
syntax:
Flowchart:
Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
4. greatest of two numbers
5. eligibility for voting
Odd or even number
n=eval(input("enter a number"))
if(n%2==0):
print("even number")
else:
print("odd number")
Output
enter a number4
even number
positive or negative number
n=eval(input("enter a number"))
if(n>=0):
print("positive number")
else:
print("negative number")
Output
enter a number8
positive number
leap year or not
y=eval(input("enter a yaer"))
if(y%4==0):
print("leap year")
else:
print("not leap year")
Output
enter a yaer2000
leap year
greatest of two numbers
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
if(a>b):
print("greatest:",a)
else:
print("greatest:",b)
Output
enter a value:4
enter b value:7
greatest: 7
eligibility for voting
age=eval(input("enter ur age:"))
if(age>=18):
print("you are eligible for vote")
else:
print("you are eligible for vote")
Output
enter ur age:78
you are eligible for vote
Chained conditionals(if-elif-else)
The elif is short for else if.
This is used to check more than one condition.
If the condition1 is False, it checks the condition2 of the elif block. If all
the conditions are False, then the else part is executed.
Among the several if...elif...else part, only one part is executed according
to the condition.
• The if block can have only one else block. But it can have multiple elif blocks.
• The way to express a computation like that is a chained conditional.
syntax:
Flowchart:
Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation
student mark system
mark=eval(input("enter ur mark:"))
if(mark>=90):
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
Output
enter ur mark:78
grade:B
traffic light system
colour=input("enter colour of light:")
if(colour=="green"):
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
Output
enter colour of light:green
GO
compare two numbers
x=eval(input("enter x value:"))
y=eval(input("enter y value:"))
if(x == y):
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
Output
enter x value:5
enter y value:7
x is less than y
Roots of quadratic equation
a=eval(input("enter a value:"))
b=eval(input("enter b value:"))
c=eval(input("enter c value:"))
d=(b*b-4*a*c)
if(d==0):
print("same and real roots")
elif(d>0):
print("diffrent real roots")
else:
print("imaginagry roots")
output
enter a value:1
enter b value:0
enter c value:0
same and real roots
Nested conditionals
One conditional can also be nested within another.
Any number of condition can be nested inside one another.
In this, if the condition is true it checks another if condition1.
If both the conditions are true statement1 get executed otherwise statement2
get execute.
if the condition is false statement3 gets executed
Syntax:
Flowchart:
Exampe:
1. greatest of three numbers
2. positive negative or zero
greatest of three numbers
a=eval(input(“enter the value of a”))
b=eval(input(“enter the value of b”))
c=eval(input(“enter the value of c”))
if(a>b):
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
output
enter the value of a 9
enter the value of a 1
enter the value of a 8
the greatest no is 9
positive negative or zero
n=eval(input("enter the value of n:"))
if(n==0):
print("the number is zero")
else:
if(n>0):
print("the number is positive")
else:
print("the number is negative")
output
enter the value of n:-9
the number is negative
ITERATION/CONTROL STATEMENTS:
state
while
for
break
continue
pass
State:
Transition from one process to another process under specified condition
with in a time is called state.
While loop:
While loop statement in Python is used to repeatedly executes set of
statement as long as a given condition is true.
In while loop, test expression is checked first. The body of the loop
isentered only if the test_expression is 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 statements inside the while starts with indentation and the first
unindented line marks the end.
Syntax:
Flowchart
Examples:
1. program to find sum of n numbers:
2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not
Sum of n numbers:
n=eval(input("enter n"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
print(sum)
output
enter n
10
55
Factorial of a numbers:
n=eval(input("enter n"))
i=1
fact=1
while(i<=n):
fact=fact*i
i=i+1
print(fact)
output
enter n
120
Sum of digits of a number:
n=eval(input("enter a number"))
sum=0
while(n>0):
a=n%10
sum=sum+a
n=n//10
print(sum)
output
enter a number
123
Reverse the given number:
n=eval(input("enter a number"))
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
print(sum)
output
enter a number
123
321
Armstrong number or not
n=eval(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong number")
else:
print("The given number is not
Armstrong number")
output
enter a number153
The given number is Armstrong number
Palindrome or not
n=eval(input("enter a number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is not palindrome")
output
enter a number121
The given no is palindrome
For loop:
for in range:
v
We can generate a sequence of numbers using range() function. range(10) will
generate numbers from 0 to 9 (10 numbers).
v
In range function have to define the start, stop and step size as
range(start,stop,step size). step size defaults to 1 if not provided.
Syntax
Flowchart:
For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string).
Iterating over a sequence is called traversal. Loop continues until we reach the
last element in the sequence.
The body of for loop is separated from the rest of the code using indentation.
Sequence can be a list, strings or tuples
Examples:
1. print nos divisible by 5 not by 10:
2. Program to print fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not
5. check the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range
print nos divisible by 5 not by 10
n=eval(input("enter a"))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)
output
enter a:30
15
25
Fibonacci series
a=0
b=1
n=eval(input("Enter the number of terms: "))
print("Fibonacci Series: ")
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c
output
Enter the number of terms: 6
Fibonacci Series:
01
find factors of a number
n=eval(input("enter a number:"))
for i in range(1,n+1,1):
if(n%i==0):
print(i)
Output
enter a number:10
10
check the no is prime or not
n=eval(input("enter a number"))
for i in range(2,n):
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.")
output
enter a no:7
The num is a prime number.
check a number is perfect number or not
n=eval(input("enter a number:"))
sum=0
for i in range(1,n,1):
if(n%i==0):
sum=sum+i
if(sum==n):
print("the number is perfect number")
else:
print("the number is not perfect number")
Output
enter a number:6
the number is perfect number
Program to print first n prime numbers
number=int(input("enter no of prime
numbers to be displayed:"))
count=1
n=2
while(count<=number):
for i in range(2,n):
if(n%i==0):
break
else:
print(n)
count=count+1
n=n+1
Output
enter no of prime numbers to be
displayed:5
5
7
11
Program to print prime numbers in range
lower=eval(input("enter a lower range"))
upper=eval(input("enter a upper range"))
for n in range(lower,upper + 1):
if n > 1:
for i in range(2,n):
if (n % i) == 0:
break
else:
print(n)
output:
enter a lower range50
enter a upper range100
53
59
61
67
71
73
79
83
89
97
----------------------------------------------------------------------------------------------------------
LOOP CONTROL STRUCTURES
BREAK
Break statements can alter the flow of a loop.
It terminates the current
loop and executes the remaining statement outside the loop.
If the loop has else statement, that will also gets terminated and come out of
the loop completely.
Syntax:
Break
Flowchart
example
for i in "welcome":
if(i=="c"):
break
print(i)
Output
CONTINUE
It terminates the current iteration and transfer the control to the next
iteration in the loop.
Syntax:
Continue
Flowchart
Example:
for i in "welcome":
if(i=="c"):
continue
print(i)
Output
w
e
PASS
It is used when a statement is required syntactically but you don’t want any
code to execute.
It is a null statement, nothing happens when it is executed.
Syntax:
pass
break
Example
for i in “welcome”:
if (i == “c”):
pass
print(i)
Output
Difference between break and continue
FRUITFUL FUNCTION
Fruitful function
Void function
Return values
Parameters
Local and global scope
Function composition
Recursion
Fruitful function:
A function that returns a value is called fruitful function.
Example:
Root=sqrt(25)
Example:
def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Return values:
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a,b,c– return 3 variables
return a+b– return expression
return 8– return value
PARAMETERS / ARGUMENTS:
Parameters are the variables which used in the function definition.
Parameters are inputs to functions. Parameter receives the input from the
function call.
It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
Required/ Positional Parameter:
The number of parameter in the function definition should match exactly with
number of arguments in the function call.
Example
def student( name, roll ):
print(name,roll)
student(“George”,98)
Output:
George 98
Keyword parameter:
When we call a function with some values, these values get assigned to the
parameter according to their position. When we call functions in keyword
parameter, the order of the arguments can be changed.
Example
def student(name,roll,mark):
print(name,roll,mark)
student(90,102,"bala")
Output:
90 102 bala
Default parameter:
Python allows function parameter to have default values; if the function is
called without the argument, the argument gets its default value in function
definition.
Example
def student( name, age=17):
print (name, age)
student( “kumar”):
student( “ajay”):
Output:
Kumar 17
Ajay 17
Variable length parameter
Sometimes, we do not know in advance the number of arguments that will
be passed into a function.
Python allows us to handle this kind of situation through function calls
with number of arguments.
In the function definition we use an asterisk (*) before the parameter name
to denote this is variable length of parameter.
Example
def student( name,*mark):
print(name,mark)
student (“bala”,102,90)
Output:
bala ( 102 ,90)
Local and Global Scope
Global Scope
The scope of a variable refers to the places that you can see or access a
variable.
A variable with global scope can be used anywhere in the program.
It can be created by defining a variable outside the function.
Local Scope
A variable with local scope can be used only within the function .
Function Composition:
Function Composition is the ability to call one function from within
another function
It is a way of combining functions such that the result of each function is
passed as the argument of the next function.
In other words the output of one function is given as the input of another
function is known as function composition.
Example:
math.sqrt(math.log(10))
def add(a,b):
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
Output:
900
find sum and average using function composition
def sum(a,b):
sum=a+b
return sum
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
sum=sum(a,b)
avg=avg(sum)
print("the avg is",avg)
output
enter a:4
enter b:8
the avg is 6.0
Recursion
A function calling itself till it reaches the base value - stop point of function
call. Example: factorial of a given number using recursion
Factorial of n
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=eval(input("enter no. to find
fact:"))
fact=fact(n)
print("Fact is",fact)
Output
enter no. to find fact:5
Fact is 120
Explanation
Examples:
1. sum of n numbers using recursion
2. exponential of a number using recursion
Sum of n numbers
def sum(n):
if(n==1):
return 1
else:
return n*sum(n-1)
n=eval(input("enter no. to find
sum:"))
sum=sum(n)
print("Fact is",sum)
Output
enter no. to find sum:10
Fact is 55
STRINGS:
Strings
String slices
Immutability
String functions and methods
String module
Strings:
String is defined as sequence of characters represented in quotation
marks(either single quotes ( ‘ ) or double quotes ( “ ).
An individual character in a string is accessed using a index.
The index should always be an integer (positive or negative).
A index starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be changed after
it is created.
Python will get the input at run time by default as a string.
Python does not support character data type. A string of size 1 can be
treated as characters.
1. single quotes (' ')
2. double quotes (" ")
3. triple quotes(“”” “”””)
Operations on string:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Member ship
String slices:
v
A part of a string is called string slices.
v
The process of extracting a sub string from a string is called slicing.
Immutability:
v
Python strings are “immutable” as they cannot be changed after they are
created.
v
Therefore [ ] operator cannot be used on the left side of an assignment.
string built in functions and methods:
A method is a function that “belongs to” an object.
Syntax to access the method
Stringname.method()
a=”happy birthday”
here, a is the string name.
String modules:
A module is a file containing Python definitions, functions, statements.
Standard library of Python is extended as modules.
To use these modules in a program, programmer needs to import the
module.
Once we import a module, we can reference or use to any of its functions or
variables in our code.
There is large number of standard modules also available in python.
Standard modules can be imported the same way as we import our user-
defined modules.
Syntax:
import module_name
Example
import string
print(string.punctuation)
print(string.digits)
print(string.printable)
print(string.capwords("happ
y birthday"))
print(string.hexdigits)
print(string.octdigits)
output
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
./:;<=>?@[\]^_`{|}~
Happy Birthday
0123456789abcdefABCDEF
01234567
Escape sequences in string
List as array:
Array:
Array is a collection of similar elements. Elements in the array can be
accessed by index. Index starts with 0. Array can be handled in python by
module named array.
To create array have to import array module in the program.
Syntax :
import array
Syntax to create array:
Array_name = module_name.function_name(‘datatype’,[elements])
example:
a=array.array(‘i’,[1,2,3,4])
a- array name
array- module name
i- integer datatype
Example
Program to find sum of array elements
import array
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
Output
10
Convert list into array:
fromlist() function is used to append list to array. Here the list is act like a
array.
Syntax:
arrayname.fromlist(list_name)
Example
program to convert list into array
import array
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist(l)
for i in a:
sum=sum+i
print(sum)
Output
35
Methods in array
a=[2,3,4,5]