Wednesday, December 25, 2019

Flow control statements

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


                                                                   Control Flow 


Conditional Statements

If
If-elif
If-elif-else 


Transfer Statements 

break
continue
pass


Iterative Statements 

For 
While 

Conditional statements 

  1. If 
If condition: statement 

OR 

If condition 
     statement-1 
     statement-2
     statement-3 

If condition is true then statements will be executed 

Eg:

name=input(“Enter Name:”)
if name==“Karthik” :
print(“Hello Karthik Good Morning”)
print(“How are you!!!”)

D:\Python_classes> py test.py 
Enter Name:karthik
Hello karthik Good Morning 
How are you!!!

D:\Python_classes>py test.py
Enter Name: Karthik
How are you!!!

  1. If-else:

If condition:
     Action-1
else:
     Action-2 

If condition is true then Action-1 will be executed otherwise Action-2 will be executed.

name=input(“Enter Name:”)
if name==“karthik” :
print(“Hello Karthik Good Morning”)
else:
print(“Hello Guest Good Morning”)
print(“How are you!!!”)

D:\python_classes>py test.py
Enter Name:karthik
Hello Karthik Good Morning 
How are you!!!

D:\python_classes>py test.py 
Enter Name:kaush
Hello Guest Good Morning 
How are you!!!

if-elfif-else

if condition1:
       Action-1
elfif condition2:
         Action-2
elfif condition3:
         Action-3
elfif condition4:
         Action-4

else:
      Default Action 

Based condition the corresponding action will be executed.

brand=input(“Enter your favorite choco:”)
if brand==“Cadbury”
print(“It is rich brand”)
elif brand==“kitkat”:
print(“it is not that much sweet”)
elif brand==“ross”
print(“other brands are not recommended”)

D:\python_classes>py test.py
Enter Your  Favorite Brand:choco
It is rich brand

D:\python_classes>py test.py
Enter Your  Favorite Brand:kitkat
it is not that much sweet

D:\python_classes>py test.py
Enter Your  Favorite Brand:ross
other brands are not recommended

Note: 

Else part is always optional. Hence the following are various possible syntaxes 

if
If-else
If-elfif-else
If-elfif

There is no switch statement in python 

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)

D:\python_classes>py test.py
Enter First Number: 10 
Enter Second Number:20
Biggest Number: 20 


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)


D:\python_classes>py test.py
Enter First Number: 10 
Enter Second Number:30
Enter Second Number:20
Biggest Number: 30 

Write a program to check whether the given number is in between 1 and 100 ?

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”)

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 

For loop and while loop 

If you 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

Eg: to print characters present in the given string

s=“karthik saru”
for x in s 
print(x)

Output 

K
a
r
T
h
I
K
s
a
r
u

Eg:2 to print characters present in string index wise 

s=input(“Enter some string:”)
I=0
for x in s:
print(“The character present at “,I,”index is :”,x)
i=I+1

D:\Python_classes>py test.py

Enter some string: karthik saru

The character present at 0 index is: k
The character present at 1 index is: a
The character present at 2 index is: r 
The character present at 3 index is: t 
The character present at 4 index is: h 
The character present at 5 index is: i 
The character present at 6 index is: k 
The character present at 7 index is: 
The character present at 8 index is: s
The character present at 9 index is: a
The character present at 10 index is: r
The character present at 11 index is: u

Eg3: To print Hello 10 times 

for x in range(10):
print(“Hello”)

Eg4: To display numbers from 0 to 10 
for x in range(11):
print(x)

Eg5: To display odd numbers from 0 to 20 

for x in range(21)
if(x%2!=0):
print(x)

Eg6: To display numbers from 10 to 1 in descending order 

for x in range(10,0,-1)
print(x)

Eg7: To print sum of numbers present  inside first 

list=eval(input(“Enter List:”))
sum=0;
for x in list:
sum=sum+x;
print(“The Sum=“,sum)

D:\Python_classes>test.py 
Enter List:(10,20,30,40)
The Sum=100

D:\Python_classes>py test.py 
Enter List:[45,67]
The Sum= 112 

  1. 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


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

x = 1 
while x <=10:
print(x)
x = x+1 

Eg: 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)

Eg: write a program to prompt user to enter some name until entering karthik 

name=“”
while name!=“karthik”:
name=input(“Enter Name:”)
print(“Thanks for confirmation”)

Infinite loops 

i=0;
while True :
i=I+1;
print(“Hello”,i)

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

for i in range(4):
 for j in range(4):
print(“I=“,I,”  j=“,j)

I=0 j=0
I=0 j=1
I=0 j=2
I=0 j=3
I=1 j=0
I=1 j=1
I=1 j=2
I=1 j=3
I=2 j=0
I=2 j=1
I=2 j=3
I=2 j=4
I=3 j=0
I=3 j=1
I=3 j=2
I=3 j=3 

Write a program to display  *’s in Right angled triangled 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()

Alternative way 

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

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)

Transfer statements 

break:

We can use break statement inside loops to break loop execution based on some condition 

for i in range(10):
if I ==7:
print(“Processing Is enough…plz break”)
break
print(i)

 D:\python_classes>py test.py

0
1
2
3
4
5
6
processing is enough…plz break

Eg:

cart=[10,20,600,60,70]
for item in cart:
If item>500:
print(“To place this order insurance must be required”)
break
print(item)

D:\Python_classes>py test.py
10
20
To place this order insurance must be required

Continue 
 
We can use continue statement to skip current iteration and continue next iteration.

Eg1: To print odd numbers in the range of 0 to 9 

for I in range(10):
if I%2==0:
continue
print(i)

D:\Python_classes>py test.py

1
3
5
7
9

Eg2: 

cart=[10,20,500,700,50,60]
for item in cart:
If item>=500:
print(“We cannot process this item:”,item)
continue
print(item)

D:\Python_classes>py test.py
10
20
We cannot process this item:500
We cannot process this item:700
50
60

Eg3:

numbers=[10,20,0,5,0,30]
for n in numbers 
If n==0:
print(“Hey how we can divide with zero..just skipping”)
continue
print(“100/{} = {}”.format(n, 100/n))

Output 

100/10 = 10.0
100/20 = 5.0
Hey how we can divide with zero….just skipping
100/5 = 20.0
Hey how we can divide with zero….just skipping
100/30 = 3.333333

Loops with else block 

Inside loop execution, if break statement not executed, then only else part will be executed
Else means loop with break 

cart=[10,20,30,40,50]
for item in cart:
If item>=500:
print(“We cannot process this order”)
break
print(item)
else:
print(“Congrats…all items processed successfully”)

Output

10
20
30
40
50
Congrats…all items processed successfully

Eg: 

cart=[10,20,600,30,40,50]
for item in cart:
If item>=500
print(“We cannot process this order”)
break 
print(item)
else:
print(“Congrats…all items processed successfully”)

Output 

D:\Python_classes>py test.py 
10
20
We cannot process this order 

What is the difference between for loop and while loop in python ?

We can use loops to repeat code execution 
Repeat code for every item in sequence  —> for loop 
Repeat code as long as condition is true —> while loop 

How to exit from the loop ? By using break statement 
How to skip some iterations inside loop ? By using continue statement 
When else part will be executed wrt loops ? If loop executed without break 

Pass statement 

Pass is a keyword in python 
In our programming syntactically if block is required which won’t do anything then we can define that empty block will pass keyword.

pass
  •     It Is an empty statement 
  • It is null statement 
  • It won’t do anything 

Eg: if True
SyntaxError: unexpected EOF while parsing 
If True: pass —> valid 

def m1():

SyntaxError: unexpected EOF while parsing 
def m1(): pass 

Use case of pass 

Sometimes in the parent class we have to declare a function with empty    body and child class responsible to provide proper implementation. Such type of empty body we can define by using pass keyword. ( it is something like abstract method in java).

for I in range(100)
if I%9==0
print(i)
else:pass 

D:\Python_classes>py test.py
0
9
18
27
36
45
54
63
72
81
90
99

del statement:

del is a keyword in python 
After using a variable, it is highly recommended to delete that variable if it is no longer required, so that the corresponding object is eligible for garbage collection.

We can delete variable by using del keyword.

x = 10
print(x)
del x 

After deleting a variable we cannot access that variable otherwise we will get NameError

x = 10
del x 
print(x)

NameError: name ‘x’ is not defined 

Note: we can delete variables which are pointing to immutable objects. But we cannot delete the elements present inside immutable object.

s = “karthik”
print(s)
del s —> valid 
del s[0] —> TypeError: ’str’ object does not support item deletion

Difference b/w del and None 

In the case del, the variable will be removed and we cannot accsss that variable(unbind operation)

s = “karthik”
del s 
print(s) —> NameError: name ’s’ is not defined.

But in the case of None assignment the variable won’t be removed but the corresponding object is eligible for garbage collection ( re bind operation), Hence after assigning with none value, we can access that variable.

s = “karthik”
s = None
print(s) —> None





No comments:

Post a Comment