0% found this document useful (0 votes)
18 views19 pages

CH 6 FLOW OF CONTROL+code

Chapter 6 discusses the flow of control in Python programming, detailing how programs can execute in a sequence, selectively, or iteratively using control structures like if-else statements, for loops, and while loops. It explains different types of statements, including simple and compound statements, and introduces jump statements such as break and continue. The chapter also includes examples and exercises to illustrate the concepts of decision-making, branching, and looping in Python.

Uploaded by

ai.crimson158
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views19 pages

CH 6 FLOW OF CONTROL+code

Chapter 6 discusses the flow of control in Python programming, detailing how programs can execute in a sequence, selectively, or iteratively using control structures like if-else statements, for loops, and while loops. It explains different types of statements, including simple and compound statements, and introduces jump statements such as break and continue. The chapter also includes examples and exercises to illustrate the concepts of decision-making, branching, and looping in Python.

Uploaded by

ai.crimson158
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

CHAPTER-6

FLOW OF CONTROL
Generally, a program executes from beginning to end. Some
programs do not execute in order. As per the requirements, execution order of the program can be
changed and it is also possible to execute a program repeatedly.
Python provides control structures to manage the order of
execution of a program, which are if-else, for, while and jump statements like break and continue.

Types of Statements
There are three types of Statements provided by Python.
❖ Empty Statement(pass)
❖ Simple Statement
❖ Compound Statement
Statements are the instruction given to the computer to perform any kind of action, be it data
movements, making decisions or repeating actions.

Simple Statement
Any single executable statement is a simple statement in Python.
Eg. name=str(input(“Enter your name:”))

Compound Statement
A Compound Statement represents a group of statements executed as a unit. In Python, Compound
Statements have headers ending in colon, and a body containing a set of statements to be executed.
Eg. if x>y:
print(x)

Statement Flow Control


Statements can be executed in three different ways or three types of control structures are there:

1. Sequential
The statements will be executed sequentially (one after the other), which represents the default flow
of control. It is the normal flow of control in a program, where Python program begins with the first
statement, followed by the second, till the final statement of the program is executed. Sequence
Statement Flow is the simplest flow of control.
Statement 1

Statement 2

Statement 3

2. Selective
The Selection construct was a condition test to determine the execution of statements. If a condition
is True, a set -of -statements is followed. Otherwise, a different set of statements is followed. This
construct is also called decision construct because it helps in making a decision about which set- of -
statements is to be executed.
TRUE FALSE
Condition?

Statement 1 Statement 3

Statement 2 Statement 4

3. Iterative (Looping)
The iteration construct means repetition of a set – of – statements depending upon a condition test.
The statement gets executed till the time a condition is True. As soon as the condition becomes
False, the repetition stops.
TRUE FALSE
Condition?
Once False, the loop will exit

Statement 1

Statement 2

Decision Making and Branching


There are three types of conditions in Python:
1. if-Statement
2. if-else Statement
3. elif – Statement

if-Statement
It is also called Selection Construct. The if statement selects a particular condition, if the
condition evaluates to True, a course of action is followed i.e. a set of statements are executed.
Otherwise, another set of statements gets executed.
Syntax:
if<conditional expression>:
Statement
Eg. ch=input (“Enter a single character:”)
If ch==’ ‘:
print (“You entered a space”)
if ch>=’0’ and ch<=’9’:
print (“Entered character is a digit”)
if-else Statement
The if-else statement tests a condition. If the condition evaluates to True, a set of instructions will be
executed, and if it evaluates to False, another set of instructions are executed.

Syntax:

if<conditional expression>:

Statement

else:

Statement

Eg. if a>0:

print (a, “is a positive number”)

else:

print (a,” is a negative number”)

Q 1. Write a program to check whether a number is odd or even.

num=int(input(“Enter an integer:”))

if num%2==0:

print (num,” is an even number”)

else:

print (num,” is an odd number”)

Q 2. Write a program to compare three numbers and give the largest of the three.

x=float (input (“Enter the first number:”))

y=float (input (“Enter the second number:”))

z=float (input (“Enter the third number:”))

max=x

if y>max:

max=y

if z>max:

max=z

print (“Largest number is “, max)


Q3. Write a program to calculate the area or circumference of a circle.

radius=float (input (“Enter the radius of the circle:”))

print (“””1-Calculate Area

2-Calculate Perimeter”””)

ch=int(input(“Enter your choice 1 or 2:”)

if ch==1:

area=22/7*radius*radius

print(“Area of the circle of given radius is “,area)

else:

perm=2*22/7*radius

print(“Perimeter of the circle with the given radius is:”, perm)

if-elif Statement
It is the short form of else-if statement. If the previous conditions were not True, then do this condition.

Syntax:

if<conditional expression>:

Statement

elif<conditional expression>:

Statement

elif<conditional expression>:

Statement

else:

Statement

Q. Write a program to calculate the absolute value of a number or an integer using if-elif conditional
statement.

num=float(input(“Enter the number”))

if num>=0:

print(num, ”is the absolute value”)

elif num<0:

print(num*-1,”is the absolute value”)


Q. Write a program that reads two numbers and operator and displays the computation.

num1=float(input(“Enter the first number:”))

num2=float(input(“Enter the second number:”))

op=input(“Enter operator[+-*/%]:”)

if op==’+’:

result=num1+num2

elif op==’-‘:

result=num1-num2

elif op==’*’:

result=num1*num2

elif op==’/’:

result=num1/num2

elif op==’%’:

result=num1%num2

else:

print(“Invalid operator!”)

print(num1,op,num2,’=’,result)

Nested if Statement
The nested if-else statement allows you to check for multiple text expressions and execute different codes for
more than two conditions.

Syntax:

if < conditional expression>:

if <conditional expression>:

Statement

else:

Statement

elif <conditional expression>:

Statement

else:

Statement
Q. Program that reads three numbers(integers and print them in ascending order.

num1=int(input(“Enter first number:”))

num2=int(input(“Enter the second number:”))

num3=int(input(“Enter the third number:”))

min=mid=max=None

if num1< num2 and num1< num3:

if num2< num3:

min,mid,max= num1, num2, num3

else:

min,mid,max= num1, num3, num2

elif num2< num1 and num2< num3:

if num1< num3:

min,mid,max= num2, num1, num3

else:

min,mid,max= num2, num3, num1

else:

if num1< num2:

min,mid,max= num3, num1, num2

else:

min,mid,max= num3, num2, num1

print(“Numbers in ascending order :”,min,mid,max)

Range () function
The range() function of Python is used with the for loop. It generates a list which is a special
sequence type. A sequence in Python is a group of values bounded by a single name.
The common use of range () is in the form: range (<lower limit>,<upper limit>) or range (l,u) ,
where l and u being integers
The above range function will produce a list having values starting from l, (l+1), (l+2),……(u-2),(u-1)
An empty list has no numbers falling in the arithmetic progression.
Eg: range(5,0) gives[ ] (an empty list)
The range function with different step value should use the following syntax: range(<lower
limit,<upper limit>,<step value>) or range(l,u,s)
This will produce a list having values:l,l+s,l+2s……<=(u-s)
Q. Give the values generated for the following:

Iteration and looping statements


The iteration statements allow a set of instructions to be performed repeatedly
until a certain condition is fulfilled. These statements are also called repetitive statements, loops or
looping statements.
Python provides two kinds of loops: for loop and while loop to represent two categories of loops
which are:
➢ Counting loops: The loops that repeat a certain number of times. Python’s ‘for loop’ is a
counting loop.
➢ Conditional loops: The loop that repeat until a certain condition becomes false. They keep
repeating as long as the condition is true. Python’s ‘while loop’ is a conditional loop.
1. for loop Flowchart:
Syntax: for <variable> in <sequence>:
Statements _to_ repeat

Eg. for i in [1,4,7]:


print(i)
print(i*i)

Output:
1
1
4
16
7
49
Q. Write a program to print multiplication table of any number.

num=int(input(“Enter the number:”))

for i in range(1,11):

print(num’x’,i,’=’,num*i)

Q. Write a program to print sum of natural numbers between 1 and 5.Print the sum progressively, i.e., after
adding each natural number, print sum so far.

sum=0

for i in range(1,6):

sum+=i

print(“Sum of natural numbers up to”,i,”is”,sum)

Output

Sum of natural numbers up to 1 is 1

Sum of natural numbers up to 2 is 3

Sum of natural numbers up to 3 is 6

Sum of natural numbers up to 4 is 10

Sum of natural numbers up to 5 is 15

Q. Write a program to print sum of natural numbers between 1 and 5.

sum=0

for i in range(1,6):

sum+=i

print(“Sum of natural numbers up to”,i,”is”,sum)

Output:

Sum of natural numbers up to 5 is 15

Note : The value of the loop variable after the for loop is over, is the highest value of the list.

2. while loop
A while loop is a conditional loop that will repeat the instructions Flowchart:

within itself as long as a conditional remains true.

Syntax: while <logical expression>:

loop-body
➢ The loop body may contain a single, multiple or an empty statement.
➢ The loop repeats until the condition becomes false. When the condition
becomes false, the control passes to the next line after the loop body.

Eg. a=5

while a>0:

print(“a=”,a)

a=a-3

print(“loop over!”)

Output:

a=5

a=2

loop over!

Note: The variable used in the condition of while loop must have the same value before entering into the while
loop.

Anatomy of a while loop


A while loop has 4 elements that have different purposes:

• Initialization Expression Eg. n=10


• Test Expression while n>0
• Body-of-the-loop print(n)
• Update Expression n-=3

Important points to be noted in while loop are:

❖ In a while loop, a loop control variable should be initialized. This must be done before the loop begins
as an uninitialized variable cannot be used in a test expression.
❖ The loop variable must be updated inside the body of the loop. If the test condition does not become
false, the loop will result in an endless loop or an infinite loop.

a=5

while a>0:

print(a)

print(“Loop over!”)

The above loop is an infinite loop as the value of ‘a’ remains 5 and the test condition a>0
remains true always. In this case ‘break’ statements help to break the loop.
Q. Write a program to calculate the factorial of a number.

num=int(input(“Enter a number:”))

fact=1

a=1

while a<=num:

fact*=a

a+=1

print(“The factorial of “,num,”is”,fact)

Output:

Enter a number: 3

The factorial of 3 is 6

Q. Write a program to calculate and print the sums of the even and odd integers of the first ‘n’ natural
numbers.

n=int(input(“Up to which natural number=”))

a=1

sumE=sumO=0

while a<=n:

if a%2==0:

sumE+=a

else:

sumO+=a

a+=1

print(“The sum of even integers is “,sumE)

print(“The sum of odd integers is”,sumO)

Output:

Up to which natural number? 10

The sum of even integers is 30

The sum of odd integers is 25


Jump Statements
Python offers two jump statements to be used within loops to jump out of loop iterations:

➢ Break
➢ Continue

1.Break Statement:-The break statement enables a program to skip over a part of the code. A break
statement terminates the very loop it lies within. Execution resumes at the statement immediately following
the body of the terminated statement.

Syntax: Flowchart:

Eg.
In while loop In for loop

i=1 language=[‘java’,’python’,’c++’]
while i<6: for x in language:
print(i) if x==’python’:
i+=1 break
if i==3: print(x)
break

Output: Output:
1 python
2

Note: If the break statement appears in a nested loop, then it will terminate the very loop it is in. If the break
statement is inside the inner loop, then it will terminate the inner loop only and the outer loop will continue as
it is.

2.Continue Statement:-With the continue statement we can stop the current location and continue with the
next iteration.

Syntax:
Eg.

In while loop In for loop Flowchart:


i=0 language=[‘java’,’python’,’c++’]
while i < 6: for x in language:
i += 1 if x==’python’:
if i == 3: continue
continue print(x)
print(i)
Output: Output:
1 java
2 c++
4
5
6

Loop else Statement


The else statement of a Python loop executes when the loop terminates normally. The else
statement of the loop will not execute when the break statement terminates the loop. The else clause of a
loop appears all the same indentation as that of the loop keyword while or for.

Syntax:

Eg: for i in range(1,4): Output: 1

print(i) 2

else: 3

print("Ending loop") Ending loop

Q. Write a program to test a number is prime or not.

num=int(input(“Enter a number:”))

N=int(num/2)

for i in range(2,N+1):

R=num%i

if R==0:
print(num,”is a composite number”)

break

else:

print(num,”is a prime number”)

Nested loops
A loop may contain another loop in its body. This form of a loop is called nested loop.But in a nested loop, the
inner loop must terminate before the outer loop.

Syntax:

for <variable-name> in<sequence>:


for<variable-name>in<sequence>:
statement1
statement2

Q. Write a program to print the following pattern.

**

***

****

num=int(input(“Enter the no. of rows”))


for i in range(1,num+1):
for j in range(1,i+1):
print(“*”,end=’’)
print()

Q. Program to generate the pattern


A
A B
A B C
A B C D
n=int(input(“Enter the no. of rows=”))
for i in range(1,n+1):
k=65
for j in range(1,i+1):
print(chr(k),end=” “)
k+=1
print()

Q. Write a program to print the following pattern.

12345
1234
123
12
1
n=int(input(“Enter the no. of rows=”))
for i in range(n,0,-1):
for j in range(1,i+1):
print(j,end=” “)
print()

Q. Write a program to check whether a year is leap year or not.

year=int(input("Enter the year:"))


if year%400==0 or (year%100!=0 and year%4==0):
print("It is a leap year")
else:
print("It is not a leap year")
Q. Write a program to print Fibonacci series up to 10 elements.

Print(“First 20 terms in Fibonacci series:”)


first=0
second=1
print(first,second,end=” ”)
for i in range(1,19):
third=first+second
print(third,end=” ”)
first,second=second,third

Output: First 20 terms in Fibonacci series:


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
Q. Program to determine whether a number is an Armstrong number or not.

num=int(input("Enter a number="))
num1=num
n=len(str(num))
sum=0
while num>0:
digit=num%10
num=num//10
sum+=digit**n
if sum==num1:
print(num1,"is an Armstrong number")
else:
print(num1,"is not an Armstrong number")
Q. Program to determine whether a number is Palindrome or not.
num = int(input("Enter an integer (>1000): "))
num1=num
reverse=0
while num>0:
digit=num%10
num=num//10
reverse=reverse*10+digit
if num1==reverse:
print(num1,"is a Palindrome")
else:
print(num1,"is not a Palindrome")

Q. Program to input two numbers and print their LCM and HCF.

num1=int(input("Enter the first number="))


num2=int(input("Enter the second number="))
if num1>num2:
smaller=num2
else:
smaller=num1
for i in range(1,smaller+1):
if num1%i==0 and num2%i==0:
HCF=i
LCM=(num1*num2)/HCF
print("LCM of",num1,"and",num2,"=",LCM)
print("HCF of",num1,"and",num2,"=",HCF)

Q. Program to determine whether a no. is a perfect no. or not.


num=int(input("Enter the number="))
sum=0
for i in range(1,num):
if num%i==0:
sum+=i
if num==sum:
print(num,"is a perfect number")

else:
print(num,"is not a perfect number")
Q. Program to find the sum of the series 1+x+x2+x3…..+xn

x = float(input("Enter the value of x= "))


n=int(input("Enter the value of n (for x**n)="))
sum=0
for i in range(n+1):
sum+=x**i
print("Sum of first" ,n+1,"terms=",sum)

Q. Program to find the sum of the series, 1-x+x2-x3+…..+xn

x = float(input("Enter the value of x= "))


n=int(input("Enter the value of n (for x**n)="))
sum=0
for i in range(n+1):
sum+=(-x)**i
print("Sum of first" ,n+1,"terms=",sum)

Q. Write a program that takes the name and age of the user as input and displays a
message whether the user is eligible to apply for a driving license or not. (the
eligible age is 18 years).
name = input("Enter your name: ")
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to apply for a driving license.")
else:
print(“Not eligible to apply for a driving license.")
Q. Write a program to find the grade of a student when grades are allocated as
given in the table below. Percentage of the marks obtained by the student is input
to the program.
n = float(input('Enter the percentage of the student: '))
if(n > 90):
print("Grade A")
elif(n > 80):
print("Grade B")
elif(n > 70):
print("Grade C")
elif(n >= 60):
print("Grade D")
else:
print("Grade E")

*********************************

You might also like