Unit II - Conditionals Programs
Unit II - Conditionals Programs
Python Programming
ing Problem Solving Approach
Reema Thareja
1
CHAPTER 4
Decision Control
Statements
2
3
If Statement
Example:
4
If Statement Programs
#Biggest of two numbers Output:
a=200 200 is greater than 100
b=100
if a>b:
print("{} is greater than {}".format(a,b))
#Biggest of two numbers – input from user Enter a value:66
a=int(input("Enter a value:")) Enter b value:45
b=int(input("Enter b value:")) 66 is greater than 45
if a>b:
print("{} is greater than {}".format(a,b))
#Check input is alphabet, space or a number Enter any key:
x = input("Enter any key: ") The input is a space
if(x.isalpha()):
print("The input is a character") Enter any key: d
if(x.isdigit()): The input is a
print("The input is a digit") character
if(x.isspace()): 5
print("The input is a space") Enter any key: 5
The input is a digit
If Statement Programs
#Absolute value of a number Output:
n = int(input("Enter a number:")) Enter a number:-5
if n<0: Absolute value of given number
n = -n is 5
print("Absolute value of given number
is ",n) Enter a number:10
Absolute value of given number
is 10
n = int(input("Enter a number:")) Enter a number:5
if n>0: Hai
print('Hai') Hello
print('Hello')
Enter a number:-5
Hello
Enter a number:0
Hello
6
One-Line if Statements
It is permissible to write entire if block on one line i.e., there can be more than one
statement on the same line separated by semicolon.
Syntax:
if <expr> : <statement_1> ; <statement_2> ; <statement_3>
Example: if 10<20 : print('hai') ; print('hello') ; hai
print('bye') hello
bye
a = 10 a = 10
b = 20 a = 20
if a<b : print('a = ', a) ; a = b ; print('a
= ', a)
a = 20 No output 7
b = 10
if a<b : print('a = ', a) ; a = b ; print('a
If-Else Statement
Example:
8
If-Else Statement Programs
9
If-Else Statement Programs
11
Nested if Statements
A statement that contains other statements is called a compound statement. To
perform more complex checks, if statements can be nested, that is, can be placed one
inside the other. In such a case, the inner if statement is the statement part of the
outer one. Nested if statements are used to check if more than one conditions are
satisfied.
Example:
12
If-elif-else Statement
Python supports if-elif-else statements to test additional conditions apart from the
initial test expression. The if-elif-else construct works in the same way as a usual if-
else statement. If-elif-else construct is also known as nested-if construct.
Example:
13
If-Elif-Else Statement Programs
16
If-Elif-Else Statement Programs
17
If-Elif-Else Statement Programs
#positive or negative number Output:
num = int(input("Enter any number:")) Enter any number:0
if num>=0: 0 is ZERO
if num==0:
print(num," is ZERO")
else:
print(num," is a positive number")
else:
print(num," is a negative number")
#positive or negative number Enter any number:-6
num = int(input("Enter any number:")) -6 is a negative number
if num<0:
print(num," is a negative number")
else:
if num==0:
print(num," is ZERO")
else: 18
print(num," is a positive number")
If-Elif-Else Statement Programs
19
If-Elif-Else Statement Programs
#Quadratic Equation Output:
import math Enter the value of a: 3
a=int(input("Enter the value of a: ")) Enter the value of b: 4
b=int(input("Enter the value of b: ")) Enter the value of c: 5
c=int(input("Enter the value of c: ")) IMAGINARY ROOTS
D=(b*b)-(4*a*c)
if D>0:
print("REAL ROOTS")
R1 = (-b + math.sqrt(D))/(2*a)
R2 = (-b - math.sqrt(D))/(2*a)
print("The roots are ", R1, R2)
elif D==0:
print("EQUAL ROOTS")
R1 = (-b)/(2*a)
print("The roots are ", R1, R1)
else:
20
print("IMAGINARY ROOTS")
If-Elif-Else Statement Programs
#Grade of a Student Output:
total_mark=float(input("Enter a subject's total Enter a subject's total
marks: ")) marks: 85
if (total_mark>=90 and total_mark<=100): Grade: A+
print("Grade: O")
elif (total_mark>=80 and total_mark<90):
print("Grade: A+")
elif (total_mark>=70 and total_mark<80):
print("Grade: A")
elif (total_mark>=60 and total_mark<70):
print("Grade: B+")
elif (total_mark>=50 and total_mark<60):
print("Grade: B")
else:
print("Reappear")
21
Inline if statement/ Conditional Expression
( Python’s Ternary operator)
• Inline if statement is used to perform a simple task and is more convenient
Syntax: <expr1> if (condition) else <expr2>
a=0 Output:
print("True") if (a) else False
print("False")
Output:
a=10 True
print("True") if (a) else
print("False") Output:
True
a=-5
print("True") if (a) else
print("False“)
x = "hai" if 10<20 else "hello" hai
22
print(x)
Basic loop structure / Iterative Statement
• Iterative statements are decision control statements that are used to repeat the
execution of a list of statements.
• Python supports two types of iterative statements:
• while loop
• for loop
• While loop:
• Repeat one or more statements while a particular condition is True.
• The condition is tested before any of the statements in the statement block is
executed
• If the condition is True, only then the statements will be executed otherwise if
23
Example:
• end specifies the values which have to be printed after the print statement has
been executed
• Can specify any separator like tab, space, comma, ‘ ‘, “ “ with end. 24
While Loop Programs
#Sum of first 10 numbers #Sum of first 10 odd numbers
i=1 i=1
sum=0 sum=0
while(i<=10): while(i<=10):
sum=sum+i sum=sum+i
i+=1 i+=2
print("The sum of 10 numbers = ", print("The sum of 10 odd numbers =
sum) ", sum)
Output: Output:
The sum of 10 numbers = 55 The sum of 10 odd numbers = 25
#Sum of first 10 even numbers #To print first 10 even numbers
i=0 i=0
sum=0 while(i<=10):
while(i<=10): print(i, end=" ")
sum=sum+i i+=2
i+=2
print("The sum of 10 even numbers = Output: 25
", sum) 0 2 4 6 8 10
Output:
While Loop Programs
#Amstrong number #Palindrome number
n = int(input("Enter a number = ")) n = int(input("Enter a number = "))
sum = 0 sum = 0
num = n num = n
while (n>0): while (n>0):
r = n%10 r = n%10
sum = sum + (r*r*r) sum = sum * 10 + r
n = n//10 n = n//10
if(sum==num): if(sum==num):
print("Number is Armstrong") print("Number is Palindrome")
else: else:
print("Number is not Armstrong") print("Number is not Palindrome")
Output: Output:
Enter a number = 432 Enter a number = 12321
Number is not Armstrong Number is Palindrome
Enter a number = 371 Enter a number = 371
Number is Armstrong Number is not Palindrome
Enter a number = 153 26
Number is Armstrong
While Loop Programs
#Sum of numbers from m to n #Count of all positives, neagatives and Zeros
m = int(input("Enter value for m pos = neg = zero = 0
= ")) T=1
n = int(input("Enter value for n while(T):
= ")) num = int(input("Enter the number:"))
sum = 0 if(num > 0):
i=m pos+=1
while (i<=n): elif num == 0:
sum = sum + i zero+=1
i+=1 else:
print("Sum of number from {} neg+=1
to {} is {}".format(m,n,sum)) T = int(input("To continue press 1 otherwise
Output: press 0: "))
Enter value for m = 5 print("Number of positive numbers = ",pos)
Enter value for n = 10 print("Number of negative numbers = ",neg)
Sum of number from 5 to 10 is 45 print("Number of zeros = ",zero)
Enter the number: 20
To continue press 1 otherwise press 0: 1
Enter the number: -6
To continue press 1 otherwise press 0: 1
Enter the number: 0 27
To continue press 1 otherwise press 0: 0
Number of positive numbers = 1
Number of negative numbers = 1
While Loop Programs
#Decimal to Binary #Binary to Decimal
deci_num = int(input("Enter the decimal number: ")) bin_num = int(input("Enter the binary number: "))
bin_num = 0 deci_num = 0
i=0 i=0
while(deci_num!=0): while(bin_num!=0):
rem = deci_num%2 rem = bin_num%10
bin_num = bin_num + rem*(10**i) deci_num = deci_num + rem*(2**i)
deci_num = deci_num//2 bin_num = bin_num//10
i = i+1 i = i+1
print("The binary number of {} is {}".format(deci_num, print("The decimal number of {} is
bin_num)) {}".format(bin_num, deci_num))
OUTPUT: OUTPUT:
Enter the decimal number: 9 Enter the binary number: 00011001
The binary number of 0 is 1001 The decimal number of 0 is 25
28
While Loop Programs
#Sum of digits in a number #Reverse a number
sum_digits = 0 rev_num = 0
num = int(input("Enter a number: ")) num = int(input("Enter a number: "))
while(num > 0): while(num > 0):
rem = num%10 rem = num%10
num = num//10 num = num//10
sum_digits += rem rev_num = rev_num*10 + rem
print("Sum of digits = ", sum_digits) print("Sum of digits = ", rev_num)
OUTPUT: OUTPUT:
Enter a number: 167 Enter a number: 167
Sum of digits = 14 Sum of digits = 761
29
While Loop Programs
#GCD of two numbers – Euclidean Algorithm
OUTPUT:
Enter first number: 24
Enter second number: 8
GCD of 24 and 8 is 8 30
The else statement used with loops
• When else is used with while loop, the else statement is executed when the
condition become#while
False. with else
i=1
while(i < 0):
print(i)
i = i -1
else:
print(i, "is a positive number so loop is not
executed")
OUTPUT:
1 is a positive number so loop is not executed
31
The else statement used with loops
• When else is used with while loop, the else statement is executed when the
condition becomenFalse.
= int(input("Enter n value: "))
i=2
while i<=n//2:
if n%i == 0:
print("Not prime")
break
else:
i+=1
else:
print("Prime")
OUTPUT:
Enter n value: 5
Prime
32
For Loop
For loop provides a mechanism to repeat a task until a particular condition is True.
It is usually known as a determinate or definite loop because the programmer knows
exactly how many times the loop will repeat.
The number of times the loop has to be executed can be determined by checking the
logic of the loop.
The for...in statement is a looping statement used in Python to iterate over a sequence of
objects.
33
For Loop and Range() Function
The range() function is a built-in function in Python that is used to iterate over a
sequence of numbers.
Syntax: range(beg, end, [step])
The range() produces a sequence of numbers starting with beg (inclusive) and ending
with one less than the number end. The step argument is optional. By default, every
number in the range is incremented by 1 but we can specify a different increment using
step. It can be both negative and positive, but not zero.
Examples:
34
Range() Function
• If range() function is given a single argument, it produces an object with values from 0
to argument-1. For example: range(10) is equal to writing range(0, 10).
• If range() is called with two arguments, it produces values from the first to the second.
For example, range(0,10).
• If range() has three arguments then the third argument specifies the interval of the
sequence produced. In this case, the third argument must be an integer. For example,
range(1,20,3).
Examples:
35
For Loop Programs
#Print numbers in reverse #Print sum of n numbers
for i in range(10, 0, -1): n=10
print(i, end=" ") sum = 0
for i in range(1, n+1):
OUTPUT: sum = sum + i
10 9 8 7 6 5 4 3 2 1 print("sum = ",sum)
#Print even numbers in reverse OUTPUT:
for i in range(10, 0, -2): sum = 55
print(i, end="\t")
#Print sum of n numbers
OUTPUT: n=10
10 8 6 4 2 sum = 0
for i in range(n+1):
sum = sum + i
print("sum = ",sum)
OUTPUT:”
Sum = 55 36
For Loop Programs
#Multiplication Table #Prime number
n=int(input("Enter the table number to n=int(input("Enter a number:"))
print")) for i in range(2, n):
for i in range(1, 11): if(n%i == 0):
print(i, " * ", n, " = ", i*n) break
if((i+1)==n):
OUTPUT: print(n," is a prime number")
Enter the table number to print5 else:
1 * 5 = 5
print(n, " is a composite number")
2 * 5 = 10
3 * 5 = 15
OUTPUT:
4 * 5 = 20
Enter a number:7
5 * 5 = 25
7 is a prime number
6 * 5 = 30
7 * 5 = 35
Enter a number:10
8 * 5 = 40
10 is a composite number
9 * 5 = 45
10 * 5 = 50
37
For Loop Programs
#Leap Year #Leap Years
year=int(input("Enter a year:")) for year in range(1700, 1905):
if(year%4==0 and year%100!=0 or year if(year%4==0 and year%100!=0 or year
%400==0): %400==0):
print(year," is a leap year") print(year, end=" ")
else:
print(year, " is not a leap year") OUTPUT:
1704 1708 1712 1716 1720 1724 1728 1732
OUTPUT: 1736 1740 1744 1748 1752 1756 1760 1764
Enter a year:1700 1768 1772 1776 1780 1784 1788 1792 1796
1700 is not a leap year 1804 1808 1812 1816 1820 1824 1828 1832
1836 1840 1844 1848 1852 1856 1860 1864
Enter a year:2000 1868 1872 1876 1880 1884 1888 1892 1896
2000 is a leap year 1904
38
For Loop Programs
#To print sum of the series: 1 + 1/2 + 1/3 #To print sum of the series: 1 + 1/22 + 1/32
+......+1/n +......+1/n2
n=int(input("Enter n value:")) n=int(input("Enter n value:"))
sum = 0 sum = 0
for i in range(1,n+1): for i in range(1,n+1):
sum = sum + (1/i) sum = sum + (1/(i**2))
print("The sum of the series = ", sum) print("The sum of the series = ", sum)
OUTPUT: OUTPUT:
Enter n value:7 Enter n value:6
The sum of the series = 2.5928571428571425 The sum of the series = 1.4913888888888889
39
For Loop Programs
#Exponential series: 1 + x/1! + x2/2! + x3/3! #Exponential series: 1 + x/1! + x2/2! + x3/3! +....
+....+ xn/n! + xn/n!
x=int(input("Enter x value: ")) import math
x=int(input("Enter x value: "))
n=int(input("Enter number of terms(n): "))
n=int(input("Enter number of terms(n): "))
sum = 1 sum = 1
fact = 1 for i in range(1,n+1):
for i in range(1,n+1): fact = math.factorial(i)
fact = fact * i term = pow(x,i)/fact
term = pow(x,i)/fact sum = sum + term
sum = sum + term print("Exponential series value: ", sum)
print("Exponential series value: ", sum) OUTPUT:
Enter x value: 2
OUTPUT: Enter number of terms(n): 5
Enter x value: 2 Exponential series value: 4.433333333333333
Enter number of terms(n): 5
Exponential series value: 4.433333333333333
40
For Loop Programs
#Sine series: x – x3/3! + x5/5! – x7/7!+..... #Cosine series: 1 – x2/2! + x4/4! – x6/6!+..... xn/n!
xn/n! import math
import math a=int(input("Enter angle value: "))
n=int(input("Enter number of terms(n): "))
a=int(input("Enter angle value: "))
x = a * (3.14/180)
n=int(input("Enter number of terms(n): ")) sign = -1
x = a * (3.14/180) sum = 1
sign = -1 for i in range(2,n+1,2):
sum = x fact = math.factorial(i)
for i in range(3,n+1,2): term = math.pow(x,i)/fact
fact = math.factorial(i) sum = sum + (sign*term)
term = math.pow(x,i)/fact sign = (-1)*sign
print(“Cosine series value: ", sum)
sum = sum + (sign*term)
sign = (-1)*sign OUTPUT:
print(“Sine series value: ", sum) Enter angle value: 30
OUTPUT: Enter number of terms(n): 7
Enter angle value: 30 Cosine series value: 0.8661579552866722
Enter number of terms(n): 7
Sine series value: 0.49977009454912874
41
Nested Loops
Python allows its users to have nested loops, that is, loops that can be placed inside
other loops. Although this feature will work with any loop like while loop as well as for
loop.
A for loop can be used to control the number of times a particular set of statements will
be executed. Another outer loop could be used to control the number of times that a
whole loop is repeated.
Example:
Loops should be properly indented to identify which statements are contained within
each for statement.
42
For Loop Programs
for i in range(1,6): for i in range(1,6): for i in range(1,6): for i in range(1,6): for i in range(1,6):
for j in range(0,5): for j in range(0,5): for j in range(0,i): for j in range(i,6): for j in range(i,6):
print(i,end=' ') print('*',end=' print('*',end=' ') print('*',end=' ') print(i,end=' ')
print() print() print()
print() ')
print() OUTPUT: OUTPUT: OUTPUT:
OUTPUT: * ***** 11111
11111 OUTPUT: ** **** 2222
22222 ***** *** *** 333
33333 ***** **** ** 44
44444 ***** ***** * 5
55555 *****
*****
43
For Loop Programs
for i in range(1,6): for i in range(1,6): k=1 for i in range(1,6): for i in range(1,6):
for j in range(0,i): for j in for i in range(1,5): for k in range(i,6): for k in range(i,6):
print(i,end=' ') range(1,i+1): for j in range(1,i+1): print(' ',end=' ') print('',end=' ')
print(k,end=' ') for j in range(1,i+1): for j in range(1,i+1):
print() print(j,end=' ')
k+=1 print(j,end=' ') print(j,end=' ')
print() print() print() print()
OUTPUT:
1 OUTPUT: OUTPTU: OUTPUT: OUTPUT:
22 1 1 1 1
333 12 23 12 12
4444 123 456 123 123
55555 1234 7 8 9 10 1234 1234
12345 12345
12345
44
For Loop Programs
for i in range(1,6): for i in range(1,6): for i in range(1,6): n=5
for k in range(0,i): for k in for k in range(1,6): for i in range(1,n+1):
print('',end=' ') range(1,6): if(i==1 or i==5): for k in range(i,n+1):
if(i==k): print(' ',end=' ')
for j in range(i,6): if(i==1 or
for j in range(1,i+1):
print(j,end=' ') i==5): print('$',end=' ') print(j,end=' ')
print() else: for l in range(i-1,0,-
print('*',end=' ') 1):
OUTPUT: elif(k==1 or print('*',end=' ') print(l,end=' ')
12345 k==5): else: print()
2345 if(k==1 or
345 print('*',end=' ') k==5): OUTPUT:
1
45 else:
print('*',end=' ') 121
5 print(' else: 1 2321
',end=' ') if(i==k): 1234321
print() 123454321
print('$',end=' ')
OUTPUT: else:
***** print('
* * ',end=' ')
print()
* * 45
* * OUTPUT:
***** $****
Condition-controlled and Counter-controlled Loops
46
The Break Statement
The break statement is used to terminate the execution of the nearest enclosing loop in
which it appears. The break statement is widely used with for loop and while loop. When
compiler encounters a break statement, the control passes to the statement that follows
the loop in which the break statement appears.
Example:
47
The Break Statement
#Example:
n=5
c=0
while c<n:
c+=1
if c==3:
break
print(c)
print("Loop Ends")
OUTPUT:
1
2
Loop Ends
48
The Continue Statement
Like the break statement, the continue statement can only appear in the body of a loop.
When the compiler encounters a continue statement then the rest of the statements in
the loop are skipped and the control is unconditionally transferred to the loop-
continuation
Example: portion of the nearest enclosing loop.
49
The Continue Statement
#Example
n=5
c=0
while c<n:
c+=1
if c==3:
continue
print(c)
print("Loop Ends")
OUTPUT:
1
2
4
5
Loop Ends
50
The Pass Statement
Pass statement is used when a statement is required syntactically but no command or
code has to be executed. It specified a null operation or simply No Operation (NOP)
statement. Nothing happens when the pass statement is executed.
Difference between comment and pass statements In Python programming, pass is a
null statement. The difference between a comment and pass statement is that while the
interpreter ignores a comment entirely, pass is not ignored. Comment is not executed
but pass statement is executed but nothing happens.
Example:
51
The Pass Statement
#Example:
n=5
c=0
while c<n:
c+=1
if c==3:
pass
print(c)
print("Loop Ends")
OUTPUT:
1
2
3
4
5
Loop Ends
52
While Loop Programs
#Prime number within range
53