Conditional control statement type two in Python

 Looping statements in python:

  • It is used to execute continually until the condition becomes false.
Types:
  • For
  • While
1. for loop:
  • It is used to execute a set of instructions repeatedly until the condition becomes false.
Syntax:

 for variable_name in sequence or range(start,end,step):
          Statement

Example program for for loop using sequence:

#Write a program to given word has vowels or not

count=0

a=input("Enter any word : ")

for i in a:

    if i in 'AEIOUaeiou':

        count+=1

print("This word contain vowels of count is : ",count)

Output:
Example program for for loop using start value:

#Write a program to print 1 to 10

for i in range(10):

    print(i)

Output:
Example program for for loop using start and stop value:

#Write a program to print 1 to 10

for i in range(1,11):

    print(i)        

Output:
Example program for for loop using step value:

#Write a program to print 1 to 10 by even number only

for i in range(2,12,2):

    print(i)

Output:
2. While:
  • It first checks the condition then executes the result until becomes false.
  • While True condition is acts as a switch statement in c++ or java.
Syntax:

 while (condition) or True:
          Statements

Example program for while condition:

#Write a program to print 1 to 10 by even number only

i=1

while i<=10:

    print(i)

    i+=1

Output:
Example program for while condition:

l=[]

ans='y'

while ans=='y':

    bno=int(input("Enter book number :"))

    bname=input("Enter book name :")

    author=input("Enter Author Name :")

    price=float(input("Enter book price :"))

    brec=str(bno) + " \t" + bname + " \t" + author + " " + str(price)

    l.append(brec)

    ans=input("Add more records?")

print("Book details :\nNumber\tName\tAuthot\tPrice")    

for i in l:

    print(i)

Output:
Example program for while condition with true statement:

#Write a program to print 1 to 10 by even number only

a,b=input("Enter two value: ").split()

choice=1

while True:

    choice=int(input("1.Add \n2.Sub \n3.Mul \n4.Div\n5.Exit 

\nEnter your choice(1 to 4):"))

    if choice==1:

        print("Add of "+a+" and "+b+" value is: ",int(a)+int(b))

    elif choice==2:

        print("Sub of "+a+" and "+b+" value is: ",int(a)-int(b))

    elif choice==3:

        print("Mul of "+a+" and "+b+" value is: ",int(a)*int(b))

    elif choice==4:

        print("Div of "+a+" and "+b+" value is: ",int(a)/int(b))

    elif choice==5:

        break

    else:

        print("Please enter correct choice...")

Output:
Share:

No comments:

Post a Comment

Popular Posts

Search This Blog

Powered by Blogger.

Service Support

Need our help to Learn or Post New Concepts Contact me

Recent Posts

Service Support

Need our help to Learn or Post New Concepts Contact me