Control Statement in Python with examples

If, If-Else, While, Pass, Continue, Break are a few examples of the control statements in Python. These statements are used to control the sequence of the program execution hence called control statements. Purpose of control statements:

  • To make the programming easy.
  • For iterating over a range of values without the need to write them again and again.
  • Make the program efficient and cost-effective.

We can use these control statements to print a large set of values by just writing a simple statement in Python. These statements are mostly of a single line. For example: If we want to print values for ‘n’ times we can use For statement till range ‘n’.

These statements are often used for reading the input values too. A program becomes a lot easier by using control statements. The control statements which are most widely used are: If statement, If-Else, and While.

WHILE control statement:

Count = 0
while (Count < 3):    
    Count = Count+1
    print("CodeSpeedy")

Output:

CodeSpeedy
CodeSpeedy
CodeSpeedy

In the above Python program, we are using a WHILE control statement. We have taken a variable named Count whose value is assigned to be zero. Now applying the while loop condition which is the count is less than 3 the loop starts. This will run until the Count value is equal to 3. As soon as it becomes 3 the loop terminates and the program stop.

For Loop statement:

list = ["Gaurav", "a", "Programmer"]
for i in list:
    print(i)

Output:

Gaurav
a
Programmer

Above Python program uses for loop to iterate through the list and print its values.

myDict1 = { "Gaurav": "Programmer",
            "Car": "BMW"
}


for i in myDict1 :     
    print(i)

Output:

Gaurav

BMW

Here for loop is used to iterate over a dictionary in Python and print its keys. You can also refer to Loop through a Dictionary in Python to study further about for loop in the dictionary.

BREAK statement:

for i in range(0,10): 

    if (i==5):
         break
  
print (i)

Output:

5

The above program uses a break control statement. Break statement stop the program as soon as the assigned value is reached and move out of the If loop and prints the output.

CONTINUE statement:

a=0
while(a<10):
    a=a+1
    if (a==5):
        continue
    else:
        print(a)

Output:

1
2
3
4
6
7
8
9
10

Above Python code is used to print all the values from 1 to 10 without value 5. The continue statement in code allows the program to continue without printing its value at the console. This is the use of the Continue statement.

Leave a Reply

Your email address will not be published.