Sem 3 Python Module II Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Page : 1

Module II
Boolean expressions
Boolean represents either True or False. Boolean is named for the
mathematician George Boole. The word Boolean always begins with a
capitalized B. Boolean expressions have only one value either True or
False.
Example
A=100
While(a>=20) This expression returns True
Boolean Operators for Flow Control
Decision making statements available in python are
 if statement
 if..else statements
 nested if statements
 if-elif ladder
1. if statement
Simple if is used to execute a set of statements only when condition is
true.
Syntax:
if (<condition>):
statement block
Statement-x
The condition is any expression that returns a True or False value. The
statement block may be a single statement or group of statements. If the
condition is true the statement block will be executed otherwise the
statement block will be skipped and the execution will jump to the
statement-x. when condition is true statement block and statement-x will
be executed.
Page : 2

Flowchart:-

Example
#Simple if
na=input("Enter name:")
sal=eval(input("Enter salary:"))
print(“Name:”,na)
print("Salary:",sal)
if(sal>=10000): #sal>=10000 is an expression which returns True or
False
bonus=sal*10/100
print("Bonus:",bonus)
print("Program completed")
output1
Enter name:Anu
Enter salary:8000
Name:Anu
Salary: 8000
Program completed
Output2
Enter name:Anu
Enter salary:12000
Name:Anu
Salary: 12000
Bonus: 1200.0
Program completed
2. if- else
This is an extension of simple if statement.
Syntax:
Page : 3

if (<condition>):
Statement block-1
else:
statement block-2
statement-x
If the condition is true the statement block-1 will be executed and then
execution will jump to the statement-x. If the condition is false the
statement block-2 will be executed and then execution will jump to the
statement-x.
Flowchart

Example
#if-else
na=input("Enter name:")
sal=eval(input("Enter salary:"))
if(sal>=10000):
bonus=sal*10/100
else:
bonus=2000
print("Name:",na);
print("Salary:",sal)
print("Bonus:",bonus)
print("Program completed")
Output1
Enter name:Anu
Enter salary:12000
Name: Anu
Page : 4

Salary: 12000
Bonus: 1200.0
Program completed
Output2
Enter name:Anu
Enter salary:3000
Name: Anu
Salary: 3000
Bonus: 2000
Program completed
Q1.Program to print the largest of two numbers (write program)
nested-if
A nested if is an if statement inside another if statement.
Syntax:
if (<condition1>):
Statement block-1
If(<condition2>):
statement block-2
--------
else:
statement block-3
else:
statement block-4
statement-x
Flow chart:-
Page : 5

Example
#nested if
eng=eval(input("Enter English mark:"))
maths=eval(input("Enter Maths mark:"))
if(eng>=40):
if(maths>=40):
print("Elgible for Test")
else:
print("Maths below 40")
else:
print("English mark below 40. maths mark is not evaluated")
output 1
Enter English mark:34
Enter Maths mark:45
English mark below 40. maths mark is not evaluated
output 2
Enter English mark:45
Enter Maths mark:49
Elgible for Test
Output 3
Enter English mark:43
Enter Maths mark:23
Maths below 40
if-elif-else ladder - multi way decisions.
if-elif-else ladder is used to execute one option from multiple options.
The if statements are executed from the top to down. if any one
condition is true, the statement associated with that if is executed, and
the rest of the ladder is bypassed. If none of the conditions is true, then
the final else statement will be executed.
Syntax:-
if (condition1):
Statement block-1
elif (condition2):
Statement block-2
elif (condition3):
Statement block-3
…..
……
else:
Page : 6

Statement block-n
statement-x

Flow Chart:-

Example:-
#if-elif-else ladder
na=input("Enter name :")
sal=eval(input("Enter salary :"))
if(sal>=40000):
pf=sal*30/100
hra=sal*20/100
elif(sal>=30000):
pf=sal*20/100
hra=sal*10/100
elif(sal>=15000):
pf=sal*10/100
hra=sal*5/100
else:
pf=sal*10/100
hra=500
net=sal+hra-pf
print("Name :",na);
print("Salary :",sal);
print("PF :",pf)
Page : 7

print("HRA :",hra);
print("NET Salary :",net);
output1
Enter name :John
Enter salary :40000
Name : John
Salary : 40000
PF : 12000.0
HRA : 8000.0
NET Salary : 36000.0
Output2
Enter name :Minu
Enter salary :12000
Name : Minu
Salary : 12000
PF : 1200.0
HRA : 500
NET Salary : 11300.0
Else is optional. This means if-elif is used for evaluating multiple
conditions.
Single statement condition
If the block of an executable statement of if - clause contains only a
single line, user can write it on the same line as a header statement.
Example:
a = 15
if (a == 15): print("The value of a is 15")
compound boolean expressions
These are expressions which consist of logical operators.
Example1
If(mark1>=40 and mark2>=40 and mark3>=40):
Print(“Passed”
Example 2
If(lang=”mal” or lang=”eng”):
Print(“Eligible”)
Nesting
Nesting means including multiple selection statements within a program.
Example nested if.
Example
#Program to find the largest of 3 nos
Page : 8

a=eval(input("Enter no:"))
b=eval(input("Enter no:"))
c=eval(input("Enter no:"))
if(a>b):
if(a>c):
print("Largest :", a)
else:
print("Largest :", c)
else:
if(b>c):
print("Largest is ",b);
else:
print("Largest is",c)
output
Enter no:34
Enter no:12
Enter no:23
Largest : 34
Loops in python
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. In Python Iteration (Loops) statements
are of three types:
1. While Loop
2. For Loop
3. Nested Loops
1. While loop:
While loop in python is used to execute multiple statement or codes
repeatedly until the given condition is true. 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):
block of statements
Increment or decrement operator
Page : 9

In while loop, expression is evaluated first and then if it is true, the


block of statements present inside the while loop will be executed. For
every iteration, it will check the condition and execute the block of
statements until the condition becomes false.
Example 1
Program for displaying numbers from 1 to 5.
i=1
while (i<=5):
print(i)
i=i+1
print("Loop is completed")
output
1
2
3
4
5
Loop is completed
Example 2
Program for displaying numbers from 5 to 1.
i=5
while (i>=1):
print(i)
i=i-1
output
5
4
3
2
1
Example 3
Program for displaying reverse of a number.
n=eval(input("Enter no:"))
print("Reverse of ",n," is ",end=" ")
rev=0
while (n>0):
d=n%10
rev=rev*10+d
if(rev==0):
Page : 10

print(rev,end="")
n=n//10
print(rev)
output 1
Enter no:123
Reverse of 123 is 321
output 2
Enter no:400
Reverse of 400 is 004
while-else loop
while loop executes the block until a condition is satisfied. When the
condition becomes false, the statement immediately after the loop is
executed. The else clause is only executed when your while condition
becomes false. If you break out of the loop, or if an exception is raised,
it won’t be executed.
Example 1
i=1
while (i < 6): #while i<6:
print(i)
i =i+ 1
else:
print("i is greater than or equal to 6")
output
1
2
3
4
5
i is greater than or equal to 6
Example 2
i=1
while (i < 6):
print(i)
i =i+ 1
if (i==6) :
break;
else:
print("i is greater than or equal to 6")
output
Page : 11

1
2
3
4
5
2.For in 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:
for val in sequence :
block of statements
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
# using for loop
l1=[10,30,20,40,50]
print("Items from list");
for item in l1:
print(item)
print("Items finished")
output
Items from list
10
30
20
40
50
Items finished
#Program to display the type of variable of for in loop
l1=[101,"Anu",10,20,30,60,True]
print(type(l1))
print("Items from list");
for n in l1:
print(n)
print(type(n))
for l1 in l1:
Page : 12

print(l1)
print(type(l1))
print("Items finished")
output
<class 'list'>
Items from list
101
Anu
10
20
30
60
True
<class 'bool'>
101
Anu
10
20
30
60
True
<class 'bool'>
Items finished
range() function
range() is a built-in function of Python. It is used when a user needs to
perform an action for a specific number of times. range() in Python(3.x)
is just a renamed version of a function called xrange() in Python(2.x).
The range() function is used to generate a sequence of numbers.
range() takes mainly three arguments.
 start: integer starting from which the sequence of integers is to be
returned
 stop: integer before which the sequence of integers is to be returned.
The range of integers end at stop – 1.
 step: integer value which determines the increment/decrement between
each integer in the sequence
Example 1
# Printing numbers from 0 to 4 using for in range()
for i in range(5):
print(i)
Page : 13

print("Completed")
Output
0
1
2
3
4
Completed
Example 2
# Printing numbers from 1 to 4 using for in range()
for i in range(1,5):
print(i)
print("Completed")
Output
1
2
3
4
Completed
Example 3
# Printing even numbers from 10 to 20 using for in range()
for i in range(10,20,2):
print(i)
print("Completed")
Output
10
12
14
16
18
Completed
for-else loop
For loop executes the block until a condition is satisfied. When the
condition becomes false, the statement immediately after the loop is
executed. The else clause is only executed when your for condition
becomes false. If you break out of the loop, or if an exception is raised,
it won’t be executed.
Syntax:
for val in sequence:
Page : 14

block of statement
else:
block of statement
Example
#for -else
l=eval(input("Enter lower limit:"))
u=eval(input("Enter upper limit:"))
for i in range(l,u):
print(i)
else:
print("Upper limit reached or check upper limit ")
print("Program finished")
output
Enter lower limit:10
Enter upper limit:15
10
11
12
13
14
Upper limit reached or check upper limit
Program finished
Output
Enter lower limit:15
Enter upper limit:10
Upper limit reached or check upper limit
Program finished
Nested loop
Using loop inside another loop is known as nested loop.
Example
#nested for loop
Syntax:
n=eval(input("Enter number :"))
for i in range(1,n):
print("Multiplication Table of ",i)
for j in range(1,11):
print(j,"*",i,"=",j*i)
output
Enter number :3
Page : 15

Multiplication Table of 1
1*1=1
2*1=2
3*1=3
4*1=4
5*1=5
6*1=6
7*1=7
8*1=8
9*1=9
10 * 1 = 10
Multiplication Table of 2
1*2=2
2*2=4
3*2=6
4*2=8
5 * 2 = 10
6 * 2 = 12
7 * 2 = 14
8 * 2 = 16
9 * 2 = 18
10 * 2 = 20
Loop Control Statements
Loop control statements change execution from its normal sequence.
They are used to control the order of execution of the program based on
the values and logic. Sometimes we wish to terminate the current
iteration or even the whole loop without checking test expression.
Python provides 3 types of Control Statements:
1. break
2. continue
3. pass
1. Break Statement
The break statement is used to terminate the loop containing it, the
control of the program will come out of that loop.
Syntax:
Break
Example 1
#using break
i=1
Page : 16

while i<=5:
print(i)
if i%2==0:
break
i=i+1
Output
1
2
Example 2
i=2
flag=False
n=eval(input("Enter no: "))
while i<=n/2: //floating part is also taken or use i<=n//2
if n%i==0:
flag=True
break
i=i+1
if flag:
print(n," is not Prime")
else:
print(n," is Prime")
Output
Enter no: 4
4 is not Prime
Output
Enter no: 7
7 is Prime
2.Continue Statement
When the program encounters continue statement, it will skip the
statements which are present after the continue statement inside the loop
and proceed with the next iterations.
#USAGE OF CONTINUE
n=input("Enter a string:")
for ch in n:
if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u' :
print(ch,end="")
continue
print("*",end="")
Output 1
Page : 17

Enter a string:welcome
*e**o*e
Output 2
Enter a string:TCS
***
3. 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.
#USAGE OF PASS
n=input("Enter a string:")
for ch in n:
if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u' :
pass
print(ch,end="")
Output
Enter a string:welcome
welcome
Finite Loops
Loop is used to execute set of statements for n times. The most common
kind of loop is the finite loop (i.e., a loop that we explicitly know, in
advance, which values the control variables will have during the loop
execution). The simplest case of a finite loop is the for loop within a
range.
Program for printing numbers from 1 to 5
#Finite loop
for i in range(1,5):
print(i)
output
1
2
3
4
Infinite loop
A loop becomes infinite loop if a condition never becomes False. This
results in a loop that never ends. While loop is an example of infinite
loop.
Example
Page : 18

i=1
while i<=5:
print(i)
output
1
1
1
1
1
Above Program displays 1 and it is an infinite loop. To terminate control
from infinite loop press ctrl+c.
Important questions
3. Define Boolean expression
4. Write a short note on decision statements
5. Explain about multi-way decision statement available in Python.
6. Write a short note on while loop
7. Explain about for in loop.
8. What is the usage of range() ?
9. Write a program to print multiplication table of a number.
10. Program to print odd numbers between 1 and 50
11. Differentiate between finite and infinite loop.
12. Write a short note on loop control statements.
13. Write a program to find the sum of all odd and even numbers upto
a number specified by the user.
14. Write a program to display the sum of digits of a number.
15. Write a program to display the reverse of a number.
16. Write a program to check whether a number is prime or not.
Prompt user for input.
17. Write a program to check whether a number is armstrong or not.
Prompt user for input.
18. Python program to find Largest of 2 Numbers
19. Python Program to Swap Two Numbers
20. Python program to find Largest of 3 Numbers
21. Python program to Print Natural number 1 to N
22. Python program for Leap Year
23. Python program to find Odd or Even
24. Python program to print sum of Even Numbers from 1 to 100
25. Python program to print sum of Odd Numbers from 1 to 100
26. Python program to find Positive or Negative
Page : 19

27. Python program to find Square of a Number


28. Python program to check Number Divisible by 5 and 11
29. Python program for Multiplication Table
30. Python example to find Student Grade
31. Python example to find Simple Interest
32. Python example to Calculate Electricity Bill
33. Python program to find Total Average & Percentage of 5
Subjects
34. Python Program to Check Armstrong Number
35. Python Program to Count Number of Digits in a Number
36. Python example for Fibonacci Series
37. Python example to find Factors of a Number
38. Python example to find Factorial of a Number
39. Python program to print First Digit of a Number
40. Python program to print Last Digit in a Number
41. Python program to find GCD of Two Numbers
42. Python program to find LCM of Two Numbers
43. Python Palindrome Program
44. Python program to print Palindrome numbers from 1 to 100
45. Python program to check Prime Number
46. Python program to print Prime Numbers from 1 to 100
47. Python program to find Prime Factors of a Number
48. Py Python program to check Alphabet or not
49. Python program to check Alphabet or Digit
50. Python program to check Character is an Alphabet, Digit or
Special Character

You might also like