Conditional and Loop Statements

2 minute read

If Else statements

In Python the if else statements look like below.

number = 3

if number == 0:
    print('zero')
elif number % 2 == 0:
    print('event')
else:
    print('odd')

Note here it is elif and not else if, also instead of curly braces we have colon as the denotion of start of block. In Python indentation is very important if program is to compile and work, for this the statements under if and other constructs are indented properly. Also there is no need for parantheses for stating if conditions.

Ternary Operators

There is no ? : operator in Python, instead it has following construct.

number = 3
odd_or_even = 'odd' if number % 2 != 0 else 'even'
print(odd_or_even)

The construct is basically

expression1 if condition else expression2

For loop

Unlike Java, Python does not have a for loop construct where we can initialize a counter i and loop until i breaks some condition. In Python, for loop is used to iterate over the elements of a sequence(such as string, list). It’s syntax is as belows :

for i in range(1, 5):
    print(i)

This will print numbers from 1 to 4. Below is for loop with break statement.

for i in range(1, 5):
    print(i)
    if i == 3:
        break

This will print numbers from 1 to 3. In Python else block can be used with looping constructs, idea is that whenever the looping condition becomes false the else block is executed unless the loop was not exited using break. Below is an example:

for i in range(1, 5):
    print(i)
else:
    print('outside range')

This will print numbers from 1 to 4 and then outside range will be printed. Now note the below code, there is a break statement. In this case numbers from 1 to 3 will be printed and that else block will not be executed.

for i in range(1, 5):
    print(i)
    if i == 3:
        break
else:
    print('outside range')

While loop

While loops has similar construct as for loops, only difference being that instead of iterating over sequence, it executes until the condition is being met. Let’s have a look:

num = 10
while num > 0:
    print(num)
    num = num - 1
    if num == 2:
        break
else:
    print('num not greater than 0 anymore')

Here else statement will not be executed since break will come into play.
The looping constructs can also have continue statements and they work same as Java.

Switch Statement

There are no switch statements in Python !

Comments