Social Media

12/29/2018

Flow Control: Iterative Control

for and while loops are used for iteration purpose.
They have a termination condition always.
range() function: 
The different types of usage of range() method is as follows:
range(100) will work from 0 to 99
range(2,100) will work from 2 to 99
range(1,100,2) will work from 1 to 99 and increment every time by 2 (1,3,5,....99)
range(100,2,-1) will work from 100 to 3

The usage of for and while are explained below using the problems given below:
Problem1: Calculate the factorial of a number using for loop

n=int(input())
ans=1
if n==0 or n==1:
    print("Factorial of {} is {}".format(n,ans))
else:
    for i in range(2,n+1):
        ans*=i
    print("Factorial of {} is {}".format(n,ans))

Problem2: Print natural numbers in reverse number where last number is supplied by the user using while loop.

n=int(input())
while n!=0:
    print(n)
    n-=1


Problem3: Write a script in Python to check whether the number entered by user is prime or  not.

n=int(input())
if n==1 or n==2:
    print("{} is Prime".format(n))
else:
    for i in range(2,n//2+1):
        if n%i==0:
            print("{} not Prime".format(n))
            break
    else:
        print("{} is Prime".format(n))

Problem4: Write a script to print the number between 1 to 100 except those which are divisible by 7.

for i in range(2,100):
    if i%7==0:
        continue
    else:
        print(i)

Problem5: Write an script which shows the use of pass statement.


pass keyword is use when we have to leave empty block. The example is as:

x=int(input())
if x<=0:
    pass
else:
    print("Number greater than 0")


Be First to Post Comment !
Post a Comment