My Blog
Articles related to programming, computer science, technology and research.

19/04/2018 Categories: Python Programming. No Comments on Control Statements in Python Programming

Contents1 Introduction2 if Statement3 if…else Statement4 if…else Ternary Expression5 while Loop6 for Loop7 break and continue Introduction   Generally, a Python script executes in a sequential manner. If a set of statements should be skipped or repeated again, we should alter the flow of control. The statements which allow us to alter the flow of […]

Introduction

 

Generally, a Python script executes in a sequential manner. If a set of statements should be skipped or repeated again, we should alter the flow of control. The statements which allow us to alter the flow of control are known a control statements. Python supports the following control statements:

 

  • if
  • if..else
  • elif ladder
  • while
  • for
  • break
  • continue

 

if Statement

 

A if statement can be used as a one way decision making statement. The syntax of if statement is as follows:

 

 

if…else Statement

 

A if…else statement can be used as a two way decision making statement. The syntax of if…else statement is as follows:

 

 

if…else Ternary Expression

 

Python supports if…else ternary expression. Its syntax is as follows:

 

 

Following is an example which demonstrates if…else ternary expression:

 

 

while Loop

 

A while loop can be used to repeat a set of statements based on a condition. The syntax of while loop is as follows:

 

 

As mentioned above, else part is optional. The else part executes only when break is not used.

 

for Loop

 

A for loop can be used to repeat a set of statements. The syntax of for loop is as follows:

 

 

The object in the above syntax should be a collection of values like a list, string, tuple, etc. Like while loop, the else part is optional and executes only when break is not used.

 

break and continue

 

Both break and continue and jump statements which are used inside while loop or for loop. When break is used inside the loop, the control moves to the statement outside the enclosing loop. When continue is used inside the loop, the control moves to the first statement of the enclosing loop skipping all the remaining statements after the continue statement inside the enclosing loop.

Related Links:

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up