0% found this document useful (0 votes)
4 views10 pages

6.Flow Controls in Python Updated

The document provides an overview of flow control statements in Python, including conditional statements (if, if-else, if-elif-else), iterative statements (for and while loops), and control statements (break, continue, pass). It includes syntax, examples, and explanations of how to use these statements effectively in programming. Additionally, it covers the use of else clauses with loops and demonstrates various programming exercises related to these concepts.
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)
4 views10 pages

6.Flow Controls in Python Updated

The document provides an overview of flow control statements in Python, including conditional statements (if, if-else, if-elif-else), iterative statements (for and while loops), and control statements (break, continue, pass). It includes syntax, examples, and explanations of how to use these statements effectively in programming. Additionally, it covers the use of else clauses with loops and demonstrates various programming exercises related to these concepts.
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/ 10

Leela Soft Python3 Madhu

Flow Control Statements


Flow control describes the order in which statements will be executed at runtime.

Control Flow

Conditional Statements Transfer Statements Iterative Statements

if, else, elif break, continue, pass for, while

Conditional Statements
1. if Statement (Simple if)
If condition is true then statements will be executed.

Syntax:
if <condition>: statement
or
if <condition>:
statement-1
statement-2
statement-3

Example:
name = input("Enter User Name:")
if name == "leela" :
print("Hello", name, "Good Morning")

print("How are you!!!")

2. if-else statement:
If condition is True then if block will be executed otherwise else will be executed.

Syntax:
if <condition>:
statements
statements
else:
statements
statements

www.leelasoft.com Cell: 78-42-66-47-66 1


Leela Soft Python3 Madhu

Example:
name = input("Enter a Name:")
if name == "leela" :
print("Hello", name, "Good Morning")
else:
print("Hello Guest Good Moring")

print("How are you!!!")

3. if-elif-else statement:
Based on the condition the corresponding action will be executed.

Syntax:
if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
Action-3
elif condition4:
Action-4
...
else:
Default Action

Example:
brand = input("Enter Your Favourite Brand:")
if brand == "RC" :
print("It is childrens brand")
elif brand == "KF":
print("It is not that much kick")
elif brand == "FO":
print("Buy one get Free One")
else :
print("Other Brands are not recommended")

Note:
1. else part is always optional
Hence the following are various possible syntaxes.
 if
 if - else

www.leelasoft.com Cell: 78-42-66-47-66 2


Leela Soft Python3 Madhu

 if-elif-else
 if-elif

2. There is no switch statement in Python


Q. Write a program to find biggest of given 2 numbers from the command prompt?
n1 = int(input("Enter First Number:"))
n2 = int(input("Enter Second Number:"))
if n1 > n2:
print("Biggest Number is:", n1)
else :
print("Biggest Number is:", n2)

Q. Write a program to find biggest of given 3 numbers from the command prompt?
n1 = int(input("Enter First Number:"))
n2 = int(input("Enter Second Number:"))
n3 = int(input("Enter Third Number:"))
if n1 > n2 and n1 > n3:
print("Biggest Number is:", n1)
elif n2 > n3:
print("Biggest Number is:", n2)
else :
print("Biggest Number is:", n3)

Q. Write a program to check whether the given number is even or odd?


n = int(input("Enter Number:"))
if n % 2 == 0:
print("The number", n, "is Even Number")
else:
print("The number", n, "is Odd Number")

Q. Write a program to check whether the given number is in between 1 and 10?
n = int(input("Enter Number:"))
if n >= 1 and n <= 10 :
print("The number", n, "is in between 1 to 10")
else:
print("The number", n, "is not in between 1 to 10")

Q. Write a program to take a single digit number from the key board and print is value in
English word?
n = int(input("Enter a digit from o to 9:"))
if n == 0 :
print("ZERO")
elif n == 1:
print("ONE")
elif n == 2:

www.leelasoft.com Cell: 78-42-66-47-66 3


Leela Soft Python3 Madhu

print("TWO")
elif n == 3:
print("THREE")
elif n == 4:
print("FOUR")
elif n == 5:
print("FIVE")
elif n == 6:
print("SIX")
elif n == 7:
print("SEVEN")
elif n == 8:
print("EIGHT")
elif n == 9:
print("NINE")
else:
print("PLEASE ENTER A DIGIT FROM 0 TO 9")

Iterative Statements
If we want to execute a group of statements multiple times then we should go for Iterative
statements.

Python supports 2 types of iterative statements.


1. for loop
2. while loop

1) for loop:
If we want to execute some action for every element present in some sequence (it may be
string or collection) then we should go for “for” loop.
Syntax:
for x in sequence:
body

Where sequence can be string or any collection. Body will be executed for every element
present in the sequence.

Example 1: To print characters present in the given string


s = "Python language"
for x in s :
print(x)

Example 2: To print characters present in string index wise


s = input("Enter some String: ")

www.leelasoft.com Cell: 78-42-66-47-66 4


Leela Soft Python3 Madhu

i = 0
for x in s :
print("The character present at ", i, "index is :", x)
i = i + 1

Example 3: To print “Python” 10 times


for x in range(10):
print("Python")

Example 4: To display numbers from 1 to 10


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

Example 5: To display odd numbers from 0 to 20


for i in range(0, 20):
if i % 2 == 1:
print(i)

Example 6: To display numbers from 10 to 1 in descending order


for i in range(10, 0, -1):
print(i)

Example 7: To print sum of numbers present inside a list


li = eval(input("Enter a List:"))
sum = 0;
for x in li:
sum = sum + x;

print("The Sum is :", sum)

while loop:
If we want to execute a group of statements iteratively until some condition false, then we
should go for while loop.

Syntax:
while condition:
body

Example: To print numbers from 1 to 10 by using while loop


a = 1
while a < 11:
print(a)
a += 1

www.leelasoft.com Cell: 78-42-66-47-66 5


Leela Soft Python3 Madhu

Example: To display the sum of first n numbers


n = int(input("Enter number:"))
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i + 1
print("The sum of first", n, "numbers is :", sum)

Example: write a program to prompt user to enter some name until entering Python
name = ""
while name != "Python":
name = input("Enter Name:")
print("Thanks for confirmation")

Infinite Loops:
Example 1: If condition is fixed to True
i=0;
while True :
i = i + 1;
print("Hello", i)

Example 2: If we missing increment or decrement value


a = 0;
while a < 5 :
print("Hello", a)

Nested Loops:
Sometimes we can take a loop inside another loop, which are also known as nested loops.

Example:
for i in range(2):
for j in range(2):
print("i=", i, " j=", j)

Q. Write a program to display *'s in Right angled triangle form


n = int(input("Enter number of rows:"))
for i in range(1, n + 1):
for j in range(1, i + 1):
print("*", end=" ")
print()

Same Program in Another way:


n = int(input("Enter number of rows:"))

www.leelasoft.com Cell: 78-42-66-47-66 6


Leela Soft Python3 Madhu

for i in range(1, n + 1):


print("* " * i)

Q. Write a program to display *'s in pyramid style (also known as equivalent triangle)
n = int(input("Enter number of rows:"))
for i in range(1, n + 1):
print(" " * (n - i), end="")
print("* "*i)

Python break statement


Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes,
there may arise a condition where we want to exit the loop completely, skip an iteration or
ignore that condition. These can be done by loop control statements. Loop control statements
change execution from its normal sequence. When execution leaves a scope, all automatic
objects that were created in that scope are destroyed.

Python supports the following control statements:


 Continue statement
 Break statement
 Pass statement

Break statement
Break statement in Python is used to bring the control out of the loop when some external
condition is triggered. Break statement is put inside the loop body (generally after if condition).

Example: 1 # Python program to demonstrate break statement # Using for


loop

s = 'AGSG College'
for letter in s:

print(letter)
# break the loop as soon it sees 'e' or 'S'
if letter == 'e' or letter == 'S':
break

print("Out of for loop")


print()

Example: 2 # Using while loop


i = 0

while True:
print(s[i])

www.leelasoft.com Cell: 78-42-66-47-66 7


Leela Soft Python3 Madhu

# break the loop as soon it sees 'e' or 'S'


if s[i] == 'e' or s[i] == 's':
break
i += 1

print("Out of while loop")

Python Continue Statement


Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes,
there may arise a condition where you want to exit the loop completely, skip an iteration or
ignore that condition. These can be done by loop control statements. Loop control statements
change execution from its normal sequence. When execution leaves a scope, all automatic
objects that were created in that scope are destroyed.

Python supports the following control statements:


 Continue statement
 Break statement
 Pass statement

Continue statement
Continue is also a loop control statement just like the break statement. continue statement is
opposite to that of break statement, instead of terminating the loop, it forces to execute the
next iteration of the loop.

As the name suggests the continue statement forces the loop to continue or execute the next
iteration. When the continue statement is executed in the loop, the code inside the loop
following the continue statement will be skipped and the next iteration of the loop will begin.

Example: 1
# Python program to demonstrate continue statement
# loop from 1 to 10
for i in range(1, 11):

# If i is equals to 6, continue to next iteration without printing


if i == 6:
continue
else:
# otherwise print the value of i
print(i, end=" ")

Python pass Statement


The pass statement is a null statement. But the difference between pass and comment is that
comment is ignored by the interpreter whereas pass is not ignored.

www.leelasoft.com Cell: 78-42-66-47-66 8


Leela Soft Python3 Madhu

The pass statement is generally used as a placeholder i.e. when the user does not know what
code to write. So user simply places pass at that line. Sometimes, pass is used when the user
doesn’t want any code to execute. So user simply places pass there as empty code is not
allowed in loops, function definitions, class definitions, or in if statements. So using pass
statement user avoids this error.

Example 1: Pass statement can be used in empty functions


def emptyFunction():
pass

Example 2: pass statement can also be used in empty class


def emptyClass():
pass

Example 3: pass statement can be used in for loop when user doesn’t know what to code
inside the loop
n = 10
for i in range(n):
# pass can be used as placeholder # when code is to added later
pass

Example 4: pass statement can be used with conditional statements


a = 10
b = 20

if(a < b):


pass
else:
print("b<a")

Example 5: lets take another example in which the pass statement get executed when the
condition is true
li = ['a', 'b', 'c', 'd']

for i in li:
if(i == 'a'):
pass
else:
print(i)

The else statement used with loops


else Clause:
for loops also have an else clause which most of us are unfamiliar with. The else clause executes
after the loop completes normally. This means that the loop did not encounter a break
statement.

www.leelasoft.com Cell: 78-42-66-47-66 9


Leela Soft Python3 Madhu

The common construct is to run a loop and search for an item. If the item is found, we break
out of the loop using the break statement.

There are two scenarios in which the loop may end.


 The first one is when the item is found and break is encountered.
 The second scenario is that the loop ends without encountering a break statement.

Now we may want to know which one of these is the reason for a loop’s completion. One
method is to set a flag and then check it once the loop ends. Another is to use the else clause.

This is the basic structure of a for/else loop:


for item in container:
if search_something(item):
# Found it!
process(item)
break
else:
# Didn't find anything..
not_found_in_container()

Example:
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print( n, 'equals', x, '*', n/x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')

While loop with else


 Same as with for loops, while loops can also have an optional else block.
 The else part is executed if the condition in the while loop evaluates to False.
 The while loop can be terminated with a break statement. In such cases, the else part is
ignored.
 Hence, a while loop's else part runs if no break occurs and the condition is false.

Here is an example to illustrate this.


counter = 0

while counter < 3:


print("Inside loop")
counter = counter + 1
else:
print("Inside else")

www.leelasoft.com Cell: 78-42-66-47-66 10

You might also like