0% found this document useful (0 votes)
10 views20 pages

CH 4 Conditional and Looping Construct

This document provides an introduction to Python's conditional and looping constructs, detailing control flow, including sequential, selection, and iteration. It explains various conditional statements such as 'if', 'if-else', and 'if-elif-else', along with looping mechanisms like 'while' and 'for' loops, including their syntax and examples. Additionally, it covers the usage of the 'in' and 'not in' operators, loop control statements, and includes homework exercises for practice.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views20 pages

CH 4 Conditional and Looping Construct

This document provides an introduction to Python's conditional and looping constructs, detailing control flow, including sequential, selection, and iteration. It explains various conditional statements such as 'if', 'if-else', and 'if-elif-else', along with looping mechanisms like 'while' and 'for' loops, including their syntax and examples. Additionally, it covers the usage of the 'in' and 'not in' operators, loop control statements, and includes homework exercises for practice.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit 2: Introduction to Python

Chapter 4: Conditional and Looping Constructs

The Python interpreter reads a program one line at a time, from left to
right and top to bottom. The interpreter executes operations in the
order that it encounters them. This is called control flow or the flow of
execution. The control flow of a program can be broadly classified into
3.
1. Sequential
2. Selection/conditional
3. Iteration /looping

Sequential

In this type of execution, instructions are executed one after another


starting with the first instruction of the program.
Selection/conditional

A selection statement selects a set of statements depending on a


condition.

Iteration /looping

Repeated execution of a set of statements is called iteration.

Selection/conditional statements

Conditional statements are also known as decision-making statements.


We use these statements when we want to execute a block of code
when the given condition is true or false.

In Python we can achieve decision making by using the below statements:


● if statements
● if-else statements
● if-elif-else statements
● Nested if-else statements

if statement

If statement is one of the most commonly used conditional statements.


If statement checks for a given condition, if the condition is true, then

1
the set of code present inside the if block will be executed. The If
condition evaluates a Boolean expression and executes the block of code
only when the Boolean expression becomes TRUE.
Syntax:
if condition:
Block of code
If the condition is true, then the statement or program present inside the
if block will be executed and if the condition is false, then the statements
or program present inside the if block will not be executed.
Python uses indentation for blocks. Leading whitespace (spaces and tabs)
at the beginning of a statement is called indentation. In Python, the
same level of indentation associates statements into a single block of
code. The interpreter checks indentation levels very strictly and throws
up syntax errors if indentation is not correct. It is a common practice to
use a single tab for each level of indentation.
1.
Num = 5
if Num < 10:
print(Num ,"is smaller than 10")
2.
passing_Score = 60
my_Score = 67
if my_Score >= passing_Score:
print("You are passed in the exam")
print("Congratulations!!!")
3.
#program to display the largest number
n1=int(input("Enter number 1 : "))
n2=int(input("Enter number 2 : "))
if n1>n2:
print(n1,"is larger than ",n2)

2
if n2>n1:
print(n2,"is larger than ",n1)

if..else statement
It executes the statement(s) inside if when the condition is true,
otherwise executes the statement(s) inside else (when the condition is
false).
Syntax

if condition:

Block of code #Set of statements to execute if condition is true

else:

Block of code #Set of statements to execute if condition is false

1.
‘’’Program to subtract smaller number from the larger number
and display the difference.’’’
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2
else:
diff = num2 - num1
print("The difference of",num1,"and",num2, "is",diff)
2.
#program to display the largest number
n1=int(input("Enter number 1 : "))
n2=int(input("Enter number 2 : "))
if n1>n2:

3
print(n1,"is larger than ",n2)
else:
print(n2,"is larger than ",n1)
3.
#program to check that the entered number is even or odd
n1=int(input("Enter number : "))
if n1%2==0:
print("Even number")
else:
print("odd number")
Home Work
1. Write a program to input the age of a person. If age is greater than
or equal to 18, display that the person is eligible to vote.
2. Write a program to input the grade of a student. If the grade is
“A”. Display “Well done” otherwise display “Work hard”.
3. Write a program to input a number. Check that the number is a
multiple of 5 or not.

if...elif....else statement

It is used to check multiple conditions and execute statements


accordingly. When the conditional statements appear, the Python
interpreter executes code inside one block that is selected based on the
condition. Number of elif is dependent on the number of conditions to
be checked. If the first condition is false, then the next condition is
checked, and so on. If one of the conditions is true, then the
corresponding indented block executes, and the if statement terminates.
After that, the statements outside the if..else are executed or the
program terminates if there are no further statements.
Syntax:
if condition 1:

4
statement(s) #Set of statement to execute if condition is true

elif condition 2:

statement(s) ‘’’Set of statements to be executed when if condition


is false and elif condition is true’’’

else:

statement(s) ‘’’Set of statement to be executed when both if


and elif conditions are false’’’

1.
#Check whether a number is positive, negative, or zero.
number = int(input("Enter a number: "))
if number >0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
2.
#program to print the number names of 1 to 5
number = int(input("Enter a number: "))
if number ==1:
print("one")
elif number ==2:
print("two")
elif number ==3:
print("three")

5
elif number ==4:
print("four")
else:
print("five")
Home Work
1. Write program to input numbers from 1 to 7 and display weekday
names like 1 for Sunday.
2. Write a program to accept percentage of mark of a student.
Display grade based on the following table.
Percentage of mark Grade
Above 80 A
80 - 61 B
60 - 41 C
Below 40 D

Nested if-else statements


Nested if-else statements mean that an if statement or if-else
statement is present inside another if or if-else block.

Syntax:
if condition1 :
#Statements to execute if condition is true
if condition 2:
#Statements to execute if condition is true
else:
#Statements to execute if condition2 is false
else:
#Statements to execute if condition1 is false

6
#Check whether a number is positive, negative, or zero.
number = int(input("Enter a number: "))
if number >=0: #Outer if
if number == 0: #Inner if
print("Number is zero")
else:
print("Number is positive")
else:
print("Number is negative")

Iteration /Looping Constructs

Loops are used to repeatedly execute the same code in a


program. Python provides two types of looping constructs:

1) while loop
2) for loop

While loop
With the while loop we can execute a set of statements as long
as a condition is true.

syntax :

while condition:
Statements
else: # optional part of while
Statements

7
The statement(s) keeps on executing till condition in while
remains True; once the condition becomes False and if the else
clause is written in while, then else will get executed. While loop
may not execute even once, if the condition evaluates to false.
Example
1.
a loop to print nos. from 1 to 10
i=1
while i <=10:
print (i)
i = i+1
Output
1
2
3
4
5
6
7
8
9
10
2.
i=1
while i <=10:
print (i)

8
i+=1
else:
print ("coming out of loop")
output
1
2
3
4
5
6
7
8
9
10
coming out of loop
Home work
1. Write program to display the even numbers between 10
and 20
#To display the even numbers between 10 and 20
n=11
while n<20:
if n%2==0:
print(n)
n=n+1
2. Write program to enter the lower and upper limit and
display the multiples of 7 within the limit.
l=int(input("Enter the lower limit"))
9
u=int(input("Enter the upper limit:"))
while l<u:
if l%7==0:
print(l)
l=l+1
3. Write program to calculate the sum of numbers between
1 to 5
#To calculate the sum of numbers from 1 to 5
n=1
s=0
while n<=5:
s=s+n
n+=1
print("Sum =",s)

Range function
It is used in a for loop. It generates a list or a sequence of
values.
Syntax:
range(lower limit, upper limit, step value)
lower limit specifies the starting value.
Upper limit specifies the last values.
Step value specifies the difference between 2 number in the
list.
1. Range(u) : generates a list that starts from 0 to u-1
2. Range(l,u) : generates a list starting from l till u-1
3. Range(l,u,s) : generates a list starting from l till u-1 and
next number in the list will be based on value of s.
Example
1. list(range(4))
10
[0, 1, 2, 3]
2. list(range(4,10))
[4, 5, 6, 7, 8, 9]
3. list(range(4,10,2))
[4, 6, 8]
4. list(range(40,10,-5))
[40, 35, 30, 25, 20, 15]
5. list(range(4,10,-1))
[]
6. list(range(-4,10,2))
[-4, -2, 0, 2, 4, 6, 8]

‘in’ and ‘not in’ operator

The in and not in operators are membership operators. They are used
along with sequence (string, list, tuple)type data. The membership
operator will check that a value is a member of given sequence. It
returns Boolean as result.

1. 3 in [1,2,3]

True

2. 5 in (1,2,3,4)

False

3. ‘a’ in ‘apple’

True

4. ‘c’ not in ‘python’

True

5. ‘c’ in ‘python’

False

For loop

11
The for loop is used to iterate over a range of values or a sequence. The
loop is executed for each item in the range. The values can be numeric,
string, list, or tuple. When all the items in the range are exhausted, the
statements with in loop are not executed and Python interpreter starts
executing the statements immediately following the for loop.

Syntax of the for Loop:

for<control-variable> in <sequence/items in range>:

<statements inside body of the loop>

Example

1) for i in [1,2,3]:

print(i)

output

2) for i in ‘python’:

print(i)

output

n
12
3) for i in (5,6,7):

print(i)

4) for i in range(1,11):

print(i,end=” “)

output

1 2 3 4 5 6 7 8 9 10
1. Write program to display the odd numbers between 10 and 20
for i in range(11,20,2)
print(i)
OR
# pgm to display the odd numbers from 10 to 20
for i in range(11,21):
if i%2==1:
print(i,end=" ")
2. Write program to display the multiplication table for 5
for x in range(1,11):
print(x," x 5 = ",x*5)
3. Write program to display the sum of the numbers 1 to 5
# pgm to display the sum of the numbers 1 to 5
s=0
for i in range(1,6):

13
s=s+i
print("sum = ",s)

Home work
1. Write program to display the even numbers between 20 and 50

2. Write program to enter a number and display the numbers in


reverse order till zero. Eg: If number is 10 display 10,9,8,....0

Loop else statement


The else of loop executes only when the loop ends normally. It will not
execute when a loop is terminating because of break statement.
1.
for i in range(1,6):
print(i)
else:
print("Loop ends")
2.
for a in range(10,3):
print(" In loop")
else:
print("Exiting loop")
3.
while 1>5:
print(" In loop")
else:
print("Exiting loop")

14
4.
while 1<5:
print(" In loop")
else:
print("Exiting loop")
Note :
To stop execution of infinite loop you have to press Ctrl + c.

Jump statements
They are used inside a loop to jump out of loop iterations. There are 2
jump statements.
1. Break statement : is used to terminate the loop.
a) for i in range(10): #Exit the loop when i is 7
print(i)
if i == 7:
break
b) Exit the loop when i is 3:

i=1
while i < 6:
print(i)
if i == 3:
break
i =i+ 1

c)
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
else:

15
print("Out of loop")

The continue Statement: stop the current iteration, and continue with
the next iteration:

Example 1

Continue to the next iteration if i is 3:

i=0
while i < 6:
i += 1

if i == 3:
continue
print(i)

2.

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
else:
print("out of loop")
Questions
1. Write program to accept a character and display whether it is a
vowel or consonant.
#program to accept a character and display whether it is a vowel
or consonant.
ch=input("Enter a character : ")
if ch=='a' or ch=='A':
print(" vowel")

16
elif ch=='e' or ch=='E':
print(" vowel")
elif ch=='i' or ch=='I':
print(" vowel")
elif ch=='o' or ch=='O':
print(" vowel")
elif ch=='u' or ch=='U':
print(" vowel")
else:
print(" Consonant")
2. Find error from the following code and rewrite the correct code
c=input(“Enter season code :”)
if c=w:
print(winter season)
elif c==’r’
print(“Rainy season”)
else:
print(“Summer season”)
Answer
c=input("Enter season code :")
if c=='w':
print('winter season')
elif c=="r":
print("Rainy season")
else:
print("Summer season")

17
3. Predict output
for i in range(20,30,2):
print(i)
Answer
20
22
24
26
28
4. c="INDIA"
for s in c:
print(s,sep="*")
Output
I*N*D*I*A
5. c="INDIA"
for s in c:
print(s,sep="@",end="%")
output
I@N@D@I@A%

Home work
Predict output
1. for x in [4,5,6,90]:
print(x)
2. for i in range(1,8):
print(i)

18
3. for p in range(-10,100,10):
print(p)
4. x=10
y=5
for z in range(x-y*2):
print(“%”,z)
5. for a in range(10,0):
print(a)
6. for a in range(0,10):
pass # It is an empty statement
print(a)
7. Under what condition will this code fragment print “water”?
if t<32:
print(“ice”)
elif t<212:
print(“water”)
else:
print(“steam”)
8. Predict output
x=1
if x>3:
if x>4:
print(“A”,end=” ”)
else:
print(“B”,end=” ”)
elif x<2:

19
if x!=0:
print(“C”,end=” ”)
print(“D”)
9. Predict the output of the following code, if the initial value of x is :
i) 8 ii) 7 iii) 10 iv) 9
if x>8:
if x>9:
print("S", end='-')
else:
print("U", end='-')
else:
if x==7:
print("P", end='-')
else:
print("E", end='-')
print("R", end='*')
1) if x=8
2) if x=7
3) if x=10
4) if x=9
10. Write a while loop to print the following series :
10 13.5 17 20.5 24 27.5 31 34.5

20

You might also like