The document summarizes key concepts in Python programming including decision statements, loops, and functions. It discusses boolean expressions and relational operators used in conditional statements. It also covers different loop constructs like while, for, and nested loops. Finally, it provides examples of defining and using functions, and concepts like local and global scope, default arguments, recursion, and returning values.
Python Programming: Unit 2 Decision Statements and Loops
1. 8 Apr 2022: Unit 2: Decision statements; Loops
PYTHON PROGRAMMING
B.Tech IV Sem CSE A
2. Unit 2
Decision Statements: Boolean Type, Boolean Operators, Using
Numbers with Boolean Operators, Using String with Boolean
Operators, Boolean Expressions and Relational Operators,
Decision Making Statements, Conditional Expressions.
Loop Control Statements: while Loop, range() Function, for Loop,
Nested Loops, break, continue.
Functions: Syntax and Basics of a Function, Use of a Function,
Parameters and Arguments in a Function, The Local and Global
Scope of a Variable, The return Statement, Recursive Functions,
The Lambda Function.
3. Boolean type
Python boolean data type has two values: True and False.
Use the bool() function to test if a value is True or False.
a = True
type(a)
<class 'bool'>
b = False
type(b)
<class 'bool'>
branch = "CSEA"
section = 4
print(bool(branch))
print(bool(section))
True
True
bool("Welcome")
True
bool(‘’)
False
print(bool("abc"))
print(bool(123))
print(bool(["app", “bat", “mat"]))
True
True
True
4. Boolean operators
not
and
or
A=True
B=False
A and B
False
A=True
B=False
A or B
True
A=True
B=False
not A
False
A=True
B=False
not B
True
A=True
B=False
C=False
D= True
(A and D) or(B or C)
True
5. Write code that counts the number of words in
sentence that contain either an “a” or an “e”.
sentence=input()
words = sentence.split(" ")
count = 0
for i in words:
if (('a' in i) or ('e' in i)) :
count +=1
print(count)
7. x = 84
y = 17
print(x >= y)
print(y <= x)
print(y < x)
print(x <= y)
print(x < y)
print(x % y == 0)
True
True
True
False
False
False
x = True
y = False
print(not y)
print(x or y)
print(x and not y)
print(not x)
print(x and y)
print(not x or y)
True
True
True
False
False
False
8. Decision statements
Python supports the following decision-
making statements.
if statements
if-else statements
Nested if statements
Multi-way if-elif-else statements
9. if
Write a program that prompts a user to enter two integer values.
Print the message ‘Equals’ if both the entered values are equal.
if num1- num2==0: print(“Both the numbers entered are Equal”)
Write a program which prompts a user to enter the radius of a circle.
If the radius is greater than zero then calculate and print the area
and circumference of the circle
if Radius>0:
Area=Radius*Radius*pi
.........
10. Write a program to calculate the salary of a medical
representative considering the sales bonus and incentives
offered to him are based on the total sales. If the sales
exceed or equal to 1,00,000 follow the particulars of
Column 1, else follow Column 2.
11. Sales=float(input(‘Enter Total Sales of the Month:’))
if Sales >= 100000:
basic = 4000
hra = 20 * basic/100
da = 110 * basic/100
incentive = Sales * 10/100
bonus = 1000
conveyance = 500
else:
basic = 4000
hra = 10 * basic/100
da = 110 * basic/100
incentive = Sales * 4/100
bonus = 500
conveyance = 500
salary= basic+hra+da+incentive+bonus+conveyance
# print Sales,basic,hra,da,incentive,bonus,conveyance,sal
12. Write a program to read three numbers from a user and
check if the first number is greater or less than the other
two numbers.
if num1>num2:
if num2>num3:
print(num1,”is greater than “,num2,”and “,num3)
else:
print(num1,” is less than “,num2,”and”,num3)
13. Finding the Number of Days in a Month
flag = 1
month = (int(input(‘Enter the month(1-12):’)))
if month == 2:
year = int(input(‘Enter year:’))
if (year % 4 == 0) and (not(year % 100 == 0)) or (year % 400 == 0):
num_days = 29
else:
num_days = 28
elif month in (1,3,5,7,8,10,12):
num_days = 31
elif month in (4, 6, 9, 11):
num_days = 30
else:
print(‘Please Enter Valid Month’)
flag = 0
if flag == 1:
print(‘There are ‘,num_days, ‘days in’, month,’ month’)
14. Write a program that prompts a user to enter two different
numbers. Perform basic arithmetic operations based on the
choices.
.......
if choice==1:
print(“ Sum=,”is:”,num1+num2)
elif choice==2:
print(“ Difference=:”,num1-num2)
elif choice==3:
print(“ Product=:”,num1*num2)
elif choice==4:
print(“ Division:”,num1/num2)
else:
print(“Invalid Choice”)
16. CONDITIONAL EXPRESSIONS
if x%2==0:
x = x*x
else:
x = x*x*x
x=x*x if x % 2 == 0 else x*x*x
find the smaller number among the two numbers.
min=print(‘min=‘,n1) if n1<n2 else print(‘min = ‘,n2)
20. text = "Engineering"
for character in text:
print(character)
E
n
g
i
n
e
e
r
i
n
g
courses = ["Python", "Computer Networks", "DBMS"]
for course in courses:
print(course)
Python
Computer Networks
DBMS
21. for i in range(10,0,-1):
print(i,end=" ")
# 10 9 8 7 6 5 4 3 2 1
Range
function
22. range(start,stop,step size)
dates = [2000,2010,2020]
N=len(dates)
for i in range(N):
print(dates[i])
2000
2010
2020
for count in range(1, 6):
print(count)
1
2
3
4
5
range: Examples
23. Program which iterates through integers from 1 to 50 (using for loop).
For an integer that is even, append it to the list even numbers.
For an integer that is odd, append it the list odd numbers
even = []
odd = []
for number in range(1,51):
if number % 2 == 0:
even.append(number)
else:
odd.append(number)
print("Even Numbers: ", even)
print("Odd Numbers: ", odd)
Even Numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50]
Odd Numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]
24. Write code that will count the number of vowels in the
sentence s and assign the result to the variable
num_vowels. For this problem, vowels are only a, e, i, o,
and u.
s = input()
vowels = ['a','e','i','o','u']
s = list(s)
num_vowels = 0
for i in s:
for j in i:
if j in vowels:
num_vowels+=1
print(num_vowels)
25. for i in range(1,100,1):
if(i==11):
break
else:
print(i, end=” “)
1 2 3 4 5 6 7 8 9 10
break: example
26. for i in range(1,11,1):
if i == 5:
continue
print(i, end=” “)
1 2 3 4 6 7 8 9 10
continue: example
29. def sum(x,y):
s=0;
for i in range(x,y+1):
s=s+i
print(‘Sum of no’s from‘,x,’to‘,y,’ is ‘,s)
sum(1,25)
sum(50,75)
sum(90,100)
function: Example
30. def disp_values(a,b=10,c=20):
print(“ a = “,a,” b = “,b,”c= “,c)
disp_values(15)
disp_values(50,b=30)
disp_values(c=80,a=25,b=35)
a = 15 b = 10 c= 20
a = 50 b = 30 c= 20
a = 25 b = 35 c= 80
function: Example
31. LOCAL AND GLOBAL SCOPE OF A VARIABLE
p = 20 #global variable p
def Demo():
q = 10 #Local variable q
print(‘Local variable q:’,q)
print(‘Global Variable p:’,p)
Demo()
print(‘global variable p:’,p)
Local variable q: 10
Global Variable p: 20
global variable p: 20
32. a = 20
def Display():
a = 30
print(‘a in function:’,a)
Display()
print(‘a outside function:’,a)
a in function: 30
a outside function: 20
Local and global variable
33. Write a function calc_Distance(x1, y1, x2, y2) to calculate the distance
between two points represented by Point1(x1, y1) and Point2 (x2, y2).
The formula for calculating distance is:
import math
def EuclD (x1, y1, x2, y2):
dx=x2-x1
dx=math.pow(dx,2)
dy=y2-y1
dy=math.pow(dy,2)
z = math.pow((dx + dy), 0.5)
return z
print("Distance = ",(format(EuclD(4,4,2,2),".2f")))
36. def factorial(n):
if n < 1:
return 1
else:
return n * factorial(n-1)
print(factorial(4))
Recursion: Factorial
37. def power(x, y):
if y == 0:
return 1
else:
return x * power(x,y-1)
power(2,4)
Recursion: power(x,y)
38. A lambda function is a small anonymous function with no name.
Lambda functions reduce the number of lines of code
when compared to normal python function defined using def
lambda function
(lambda x: x + 1)(2) #3
(lambda x, y: x + y)(2, 3) #5
41. Functions
Function: Equivalent to a static method in Java.
Syntax:
def name():
statement
statement
...
statement
Must be declared above the 'main' code
Statements inside the function must be indented
hello2.py
1
2
3
4
5
6
7
# Prints a helpful message.
def hello():
print("Hello, world!")
# main (calls hello twice)
hello()
hello()
42. Whitespace Significance
Python uses indentation to indicate blocks, instead of {}
Makes the code simpler and more readable
In Java, indenting is optional. In Python, you must indent.
hello3.py
1
2
3
4
5
6
7
8
# Prints a helpful message.
def hello():
print("Hello, world!")
print("How are you?")
# main (calls hello twice)
hello()
hello()