Saturday, November 21, 2020

Control Flow Statements (if-else-for-while-jump)

                                          Conditional Statements


The if statement is the conditional statement in Python. There are 3 forms of if statement:
1.Simple if statement
2.The if..else statement
3.The If..elif..else statement

Simple if statement

The if statement tests a condition & in case the condition is True, it carries out some instructions and does nothing in case the condition is False.
Syntax
   if <condition>:
     statement
    [statements]
e.g.
   if  amount>1000:
    disc = amount * .10
The if-else statement
The if - else statement tests a condition and in case the condition is True
it carries out statements indented below if and in case the condition is False, it carries out statement below else
Syntax
   if <condition> :
       statement
    [statements]
   else :
    statement
  [statements]
e.g.
  if  amount>1000:
    disc = amount * 0.10
   else:
     disc = amount * 0.05

The if..elif statement
The if - elif statement has multiple test conditions and in case the condition1 is True, it executes statements in block1, and in case the condition1 is False, it moves to  condition2, and in case the condition2 is True, executes statements in block2, so on. In case none of the given conditions is true, then it executes the statements under else block  
Syntax
   if <condition1> :
       statement
    [statements]
   elif <condition2> :
        statement
  [statements]
    elif <condition3> :
        statement
  [statements]
     :
     : 
   else :
    statement
  [statements]

Example of if-elif statement

#Prog to find discount (20%) if amount>3000, disc(10%) if Amount <=3000 and >1000, otherwise (5%).

     Price = float (input(“Enter Price ? ” ))
     Qty = float (input(“Enter Qty ? ” ))
     Amt = Price* Qty
     print(“ Amount :” , Amt)
     if Amt >3000 :
        disc = Amt * .20                          
        print(“Discount :”, disc)
     elif Amt>1000:
        disc = Amt * .10                           
        print(“Discount :”, disc) 
     else : 
        disc = Amt * .05                          
        print(“Discount :”, disc)

Example of Nested if statement
#Program to find Largest of Three Numbers (X,Y,Z)

     X = int (input(“Enter Num1 ? ” ))
     Y = int (input(“Enter Num2 ? ” ))
     Z = int (input(“Enter Num3 ? ” ))
  if     X > Y :
           if   X > Z: 
          Largest = X
  else:
          Largest = Z
     else:
     if   Y > Z: 
        Largest = Y
  else:
        Largest = Z  
    print(“Largest Number :”, Largest)


Assignments

WAP to input a number and check whether it is Even or Odd.
WAP to input a number print its Square if it is odd, otherwise print its square root.
WAP to input a Year and check whether it is a Leap year.
WAP to input a number check whether it is Positive or Negative or ZERO.
WAP to input Percentage Marks of a students, and find the grade as per following criterion:
Marks  Grade
>=90  A
75-90  B
60-75  C
Below 60  D

LOOPS
•It is used when we want to execute a sequence of statements (indented to the right of keyword for) a fixed number of times.
•Syntax of for statement is as follows:
–i) with range() function
–ii) with sequence




The range() function
   range( 1 , n):
    will produce a list having values starting from 1,2,3… upto n-1.
  The default step size is 1
 range( 1 , n, 2):
    will produce a list having values starting from 1,3,5… upto n-1.
  The  step size is 2

more Examples: 
 1)  range( 1 , 7):    will produce 
       1, 2, 3, 4, 5, 6.
  2) range( 1 , 9, 2): will produce
       1, 3, 5, 7.
  3)  range( 5, 1, -1): will produce
       5, 4, 3, 2.
  3)  range(5): will produce
        0,1,2,3,4.
       default start value is 0


for loop implementation

Example - 1

Sum=0
for  i  in range(1, 11):
    print(i)
    Sum=Sum + i
print(“Sum of Series”, Sum)
OUTPUT:
1
2
3
4
5
6
7
8
9
10
  Sum of Series: 55
*******************************************

Example-2 

Sum=0
for   i   in range(10, 1, -2):
    print(i)
    Sum=Sum + i
print(“Sum of Series”, Sum)
OUTPUT:
  10
   8
   6
   4
   2
  Sum of Series: 30

for loop: Prog check a number for PRIME
(A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself.)

METHOD 1
num= int(input(“Enter Num?”))
flag=1
for  i  in range(2, num//2+1):
    if num%i == 0:
            flag = 0 
            break
if   flag == 1:
      print(“It is Prime No.”)
else:
  print(“It is Not a Prime No.”)


Note :Flag variable is used as a signal in programming to let the program know that a certain condition has met. It usually acts as a boolean variable indicating a condition to be either true or false.

METHOD 2: using loop else
num= int(input(“Enter Num?”))
for  i  in range(2, num//2+1):
    if num%i == 0:
          print(“It is Prime No.”)  
          break
else:
      print(“It is Not a Prime No.”)
Note: the else clause of a loop will be executed only when the loop terminates normally (not when break statement terminates the loop)

Nested for Loop
 for  i  in range ( 1, 6 ):
    print( )
    for j  in range (1,  i + 1):
    print(“*”, end=“ ”)
Will produce following output
  *
  **
  ***
  ****
  *****

The while Loop
It is a conditional loop, which repeats the statements with in itself as long as condition is true.
The general form of while loop is:
        while <condition> :
       Statement  loop body
      [Statements] 
(these statements repeated until  condition becomes false)

Example:
k = 1, sum=0
while  k <= 4 :
print (k) 
sum=sum + k
k=k+1
print(“Sum of series:”, sum) 

OUTPUT
1
2
3
4
Sum of series: 10


   while loopImplementation
#Program to find digit sum
  num = int(input(“No.?”))
  ds = 0
  while num>0 :
   ds = ds +num % 10
  num = num // 10
   print(“Digit Sum :”, ds)

#Program to find reverse
  num = int(input(“No.?”))
  rev = 0
  while num>0 :
   d =  num % 10
      rev = rev*10 + d
  num = num // 10
  print(“Reverse :”, rev)

Jump Statements

Jump statements are used to transfer the program's control from
one location to another. Means these are used to alter the flow of
a loop like-to skip a part of a loop or terminate a loop

There are three types of jump statements used in python.
1.break
2.continue
3.pass

1.break

   it is used to terminate the loop.

e.g. 1

for val in "string":
if val== "i":
break

print(val)
print("The end")

Output
s
t
r


The end

e.g 2
  
for i in range(1,11):
     if i %3==0:
        break
        print(i)

output:
1
2

2.continue

It is used to skip all the remaining statements in the loop and
move controls back to the top of the loop.

e.g.1
for val in "init":
    if val== "i":
        continue
        print(val)
print("The end")



Output
n
t

The end

e.g. 2


    for i in range(1,11):
      if i %3==0:
       continue
    print(i)

output:
         1
         2
        4
        5
        7
       8
       10

3.pass Statement

This statement does nothing. It can be used  when a statement is required syntactically but the program requires no action.

Use in loop

while True:
pass                #Busy-wait for keyboard interrupt(Ctrl+C)

In function

It makes a controller to pass by without executing any code.
e.g.

def myfun():
             pass        # if we don’t use pass here then error message  
                                                 will be shown 
print(‘my program')


OUTPUT

my program

1 comment: