Python – Control Statements

The if  and else statements are the most well known and commonly used of the control statements. When the condition in the if statement is TRUE then the nested code will be executed. It is possible for there to be multiple eif statements to denote additional conditions. When none of the conditions are met then code nested in the else statement will be executed.

Sample Code:

x = input("Input a number: ")

if ( x = 2 ) :
    print(x , "is 2")

else:
    print("x is not 2")

The for statement is used to iterate through items of any sequence like a string or a list.

names = ['john', 'bob', 'scott']

for n in names:

      print(w)

The break statement breaks out the innermost enclosing of a for or while loop. An example of using the break statement would be to loop through a list to look for an element. Once that element is found then break out of the loop to move onto the next step.

The continue statement continues with the next iteration in the loop even when an element is found in a nested if statement.

The pass statement does nothing. It can be used when syntactically there is required code but no required action. It also can be used in a minimalist class or in scenarios where your class is still in progress as a placeholder.

**This article is written for Python 3.6

<< Data Structures

Defining Functions >>

%d bloggers like this: