Control statements and loops in Python

Control statements and loops in Python

Control statements are used to take a decision based on the condition. Python supports following control statements:
  • if 
  • if .. else
Loos are used to execute the specific set of instructions 'n' number of times. Python supports the following loops:
  • for
  • while
  • nested loops
-------------------------------

if, if .. else statements in python:

Control statements can be used as in the example below:

var_1 = input("Enter var_1:")
var_2 = input("Enter var_2:")

if var_1 < var_2:
  print("var_1 is less than var_2")
elif var_1 == var_2:
  print("var_1 and var_2 are equal")
else:
  print("var_1 is greater than var_2")

In the above program, var_1, var_2 are prompted from command line. Once entered the if, elif,else conditional statements check the condition and respective output is printed. 

-------------------------------

Loops in Python:

syntax for using for loop is,

for variable in sequence:
    statements

syntax for using while loop is,

while condition:
    statements

for loop used as below:

num_list = [1,2,3,4,5]

for i in num_list:
    print(i)

while loop used as below:

k = 0

while k<5:
    k = k+1

print("Looping completed")

Post a Comment

0 Comments