Alphalearningschool
        

<<< Prev

Next >>>

Up
Python Flow Control

 Decision making: Suppose we may want to make a decision based on a condition. We know that an expression’s value can be True or False. We may want to do something only when a certain condition is true.

Decision making constructs includes Python if statements, if else statements, elif statements, nested if conditions and single statement conditions.  

Python if statement

Python if statement evaluates whether an expression is True or False, and executes the underlying code only if the result is True.

Given below is the syntax of Python if statement.

Syntax: 

if Logical_Expression :
    code block(statements)

 

Flowchart:

 

letters = (input("How many letters in vowels? "))
if letters == 5:
    print("You have cleared the test.")
print("Congrats!")

O/P-
How many letters in vowels ? 5
You have cleared the test.
Congrats!

 

Python If Else Statement

A Python if else statement takes action irrespective of what the value of the expression is.

If the result is True, then the code block following the expression would get executed. Otherwise, the code indented under the else clause would get run.

Given below is the syntax of Python if else statement.

Syntax: 

if Logical_Expression :
    Code Block 1
else :
     Code Block 2

 

EXAMPLE: 

Answer = input("Is Python an interpreted language? Yes or No >> ").lower()

if Answer == "yes" :
    print("You have cleared the test.")
else:
    print("You have failed the test.")

print("Thanks!")

O/P-1
Is Python an interpreted language? Yes or No >> Yes
You have cleared the test.
Thanks!

O/P-2
Is Python an interpreted language? Yes or No >> no
You have failed the test.
Thanks!

 

Flowchart:

 

Python If-Elif-Else Statement

The previous two if-else constructs would address at most two outcomes, i.e., True or False. However, the expression next to the “if” statement can also evaluate to a different value other than the boolean. It means to have more conditions, not just a single “else” block.

Python supports to specify multiple conditions by using an “elif  ” clause with each of the expression.

Given below is the syntax of Python if-elif-else statement.

Syntax: 

if Logical_Expression_1 :
     Code Block 1
elif Logical_Expression_2 :
     Code Block 2
elif Logical_Expression_3 :
    Code Block 3
...
else :
    Code Block N

 

Example: 

while True:
    response = input("Which Python data type is an ordered sequence? ").lower()
    print("You entered:", response)

    if response == "list":
        print("You have cleared the test.")
        break
    elif response == "tuple":
        print("You have cleared the test.")
        break
    else:
        print("Your input is wrong. Please try again.")

O/P-1
Which Python data type is an ordered sequence? list
You entered: list
You have cleared the test.

O/P-2
Which Python data type is an ordered sequence? tuple
You entered: tuple
You have cleared the test.

O/P-3
Which Python data type is an ordered sequence? dict
You entered: dict
Your input is wrong. Please try again.
Which Python data type is an ordered sequence? 

 

Flowchart:

 

Nested If-Else In Python

Some programs may have a code block under an “if” clause which subsequently has another conditional block as the first statement.

In such a case, Python allows nesting of an if-else or if-elif-else inside another conditional clause.

Python doesn’t limit the level of nested conditions in a program. Given below is the syntax of a multi-level nested if-elif-else statement.

Syntax: 

if Logical_Expression_1 :
    if Logical_Expression_1.1 :
        if Logical_Expression_1.1.1 :
             Code Block 1.1.1
        else
             Code Block
    elif Logical_Expression_1.2 :
         Code Block 1.2
    else :
         Code Block
elif Logical_Expression_2 :
     Code Block 2
elif Logical_Expression_3 :
     Code Block 3
...
else :
     Code Block

 

Example:

total = 100
#country = "US"
country = "AU"
if country == "US":
    if total <= 50:
        print("Shipping Cost is  $50")
elif total <= 100:
        print("Shipping Cost is $25")
elif total <= 150:
       print("Shipping Costs $5")
else:
        print("FREE")
if country == "AU":
     if total <= 50:
       print("Shipping Cost is  $100")
else:
       print("FREE")


O/P-
Shipping Cost is $25

Python Loops

While Loop

  • Continuously repeating statement until condition has true.
  • Statement of While condition as bellow,
while expression:
      statement ( anything )
  • Let understand with the flow chart of while loop.
  • Now seeing above figure you have clear about the while loop now we see the example how while loop will working. 
a=0;
while(a<9):
    print("a Value is = ",a)
    a=a+1
    print("After addition of 1 = " , a)
print("While loop end")

O/P-
a Value is =  0
After addition of 1 =  1
a Value is =  1
After addition of 1 =  2
a Value is =  2
After addition of 1 =  3
a Value is =  3
After addition of 1 =  4
a Value is =  4
After addition of 1 =  5
a Value is =  5
After addition of 1 =  6
a Value is =  6
After addition of 1 =  7
a Value is =  7
After addition of 1 =  8
a Value is =  8
After addition of 1 =  9
While loop end

 

Now see one example of infinite loop in while condition.

a=1
while (a==1):
    b=input("Enter number : ")
    print ("Your Entered Number b = ", b)

print("Good Bye")

O/p-
Enter number : 1
Your Entered Number b =  1
Enter number : 2
Your Entered Number b =  2
Enter number : 3
Your Entered Number b =  3
Enter number : 4
Your Entered Number b =  4
Enter number : 5
Your Entered Number b =  5 ……….. It will never end .

 

One more example of while , now we use if else block in while condition. 

c = 1
while (c <= 5):
    if c < 2:
        print("Less than 2")
    elif c > 4:
        print("Greater than 4")
    c=c+1

O/p- 
Less than 2
Greater than 4

 

For Loop:

  • For loop has ability to iterate the element over the any sequence, like List , array and String.
  • Now let see the example of for loop in python.
  • First, we understand the syntax and flow diagram of for loop.
for l in "alphalearning":
    print("Latter is = ", l)

print("--------------------------")

fruitsList=["Mango","Apple","Grapes","Banana"]
for fruit in fruitsList:
    print(fruit)

print("----------For finding a length-----------------")
for fruit in fruitsList:
    print(fruit,len(fruit))


O/P-
Latter is =  a
Latter is =  l
Latter is =  p
Latter is =  h
Latter is =  a
Latter is =  l
Latter is =  e
Latter is =  a
Latter is =  r
Latter is =  n
Latter is =  i
Latter is =  n
Latter is =  g
--------------------------
Mango
Apple
Grapes
Banana
----------For finding a length-----------------
Mango 5
Apple 5
Grapes 6
Banana 6
  • If and else loop inside the for loop.
print("--------Using rang keyword we can bound the rang for FOR loop------------")
for n in range (10,20):
    if(n>=18):
        print(n)
        print("you are eligible for voting")
    else:

        print(n," you are not eligible for voting")

O/P- 
--------Using rang keyword we can bound the rang for FOR loop------------
10  you are not eligible for voting
11  you are not eligible for voting
12  you are not eligible for voting
13  you are not eligible for voting
14  you are not eligible for voting
15  you are not eligible for voting
16  you are not eligible for voting
17  you are not eligible for voting
18
you are eligible for voting
19
you are eligible for voting

FlowChart

1.Odd & Even number finding from given input: 

print("---Find odd even number from given input---")
a=int(input("Enter number : "))
if(a%2==0):
    print("Your number is odd")
else:
    print("Your number is even")

O/P-1
---Find odd even number from given input---
Enter number : 2
Your number is even

O/P-2
---Find odd even number from given input---
Enter number : 3
Your number is odd

 Note** here we are doing type casting because input will take variable as string that’s why Line number 2 we are doing type casting.

2. Finding Prime number from given input: 

print("---Find odd even number from given input---")
a=int(input("Enter number : "))
if(a>1):
    for i in range(2,a):
        if(a%i==0):
            print(a," Number is not prime number")
            break
    else:
        print(a ," Number is a prime number")
else:
    print(a," Number is not a prime number")

O/P-1
---Find odd even number from given input---
Enter number : 123
123  Number is not prime number

O/P-2
---Find odd even number from given input---
Enter number : 3
3  Number is a prime number

 

Now see one more program to find the factorial of given input.

print("---Find odd even number from given input---")
a=int(input("Enter number : "))
b=int(input("Enter factorial number : "))
if(a<0):
    print("Factorial can not contain negative value")
elif(a==0):
    print("The factorial of 0 is 1")
else:
    for i in range(1,a+1):
        b=b*i
    print("The factorial of ",a," is ",b)

O/P-
---Find odd even number from given input---
Enter number : 3
Enter factorial number : 2
The factorial of  3  is  12

Python Statements

This statement are used for breaking out of loop, continue to loop and pass the loop let we discuss the statement deeply,

  1. break
  2. continue
  3. pass

Let understand how this statement gone a work in loops.

1.break: In break statement break the loop one by one. In simple word break is abort the current loop and gives control to the next line of the loop it mean loop will be end. 

l =[11,22,33,44]
count = 10;
for i in l:
    print("item matched")
    count = count + 1;
    break
print("break At count : ",count);

o/p   
item matched
break At count :  11

 

2. Ex
str = "alphalearning"
for i in str:  
    if i == 'e':
        break  
    print(i);  //after 'e' string will not print because we used break statement 
o/p
a
l
p
h
a
l

 

Continue: This statement use in python to if condition will satisfy then again give the control to the beginning of the loop.

Let understand with example.

for i in range(1,11):
    if i==5:
        continue;
    print(i);
o/p
1
2
3
4
6
7
8
9
10

 

Pass Statement: The pass statement is null operation nothing will happen when it will executes.

Pass statement can be used while overriding the super class into a subclass and we will not give specific implementation to sub class/Derived class.

In simple word, we are just passing the statement when condition is true.

 

Ex:
for l in 'alphalearning':
   if l == 'e':
      pass
      print("You are in pass Block")
   print("Latter : "+l)

print("Statement is Ended")

O/p
Latter : a
Latter : l
Latter : p
Latter : h
Latter : a
Latter : l
You are in pass Block
Latter : e
Latter : a
Latter : r
Latter : n
Latter : i
Latter : n
Latter : g
Statement is Ended