05 Control Flow

There are three control flow statements in Python- if, for, and while.


The if statement:



The if statement is used to check a certain condition. if the condition is true, we run a block of statements, else we process another block of statements.


x = int(input("Please enter your age:"))

if  x<=30:
         print("You are still young!")
else:
          print("You are getting older")


Another Example,


x = int(input("Please enter your age:"))

if  0<x<30:
print("You are still young!")
elif x<0:
        print("Sorry. Your age cant be Negative!")
elif x==0:
       print("Your are Just Born!! Congratulation.")
elif x==100:
print("Congratulation for being 100 years of old")
elif x>100:
print("Cool!")
else:
       print("You are getting older")

and you will see following output.








Simple for Statement:

The for statement in Python differs a bit from what you may be used to in C or Pascal.


for i in range(11):
    print(i)                   # it will print the number from 0 to 10


Another Example,


def fac(n):               # definition of factorial function
if   n==0:
return  1
else:
return  n*fac(n-1)

def main( ):
for  i in range(11):
print("fac({}): {}".format(i,  fac(i)))

main()



and you will see following output.















Python has built in factorial function. ie.

import math

for i in range(11):
print(math.factorial(i))