Share @ LinkedIn Facebook  python, basics
Python Programming Guide For Beginners - Part 4

Python Programming Guide For Beginners - Part 4

Learning The Flow Of Control In Python

  1. Python If
  2. Python if..else
  3. Python if..elif..else
  4. Python Nested If
  5. Python for loop
  6. Python while loop
  7. Python pass
  8. Python continue
  9. Python break

The "if" statement in python are used to show the flow control. It helps the coders to run the code or provide a desired output only when the condition is satisfied. For instance, if you want to display a message on the output screen only when certain code conditions are satisfied. In such cases, you can use the "If" statement to accomplish the programming.

1. Learning The Syntax of "If statement" in Python

The syntax of if statement in Python is pretty simple.

if condition:
    block_of_code

Python Program To Understand – If statement Example

In [1]:
flag = True
if flag==True:
    print("Welcome")
    print("To")
    print("CoderzColumn.com")
Welcome
To
CoderzColumn.com

Well, in the above example, we are making use of the variable "flag" and checking its value. While using the Python's 'If' Statement, you are reuired to check whether the value is "True" or not. The most important point here is to understand is that even when we are comparing the value of the "flag" with "True", the variable is used in the place of the condition. This means if the condition is satisfied the statements below it will be printed.

Look at another example to understand the difference.

In [3]:
flag = True
if flag:
    print("Welcome")
    print("To")
    print("CoderzColumn.com")
Welcome
To
CoderzColumn.com
In [4]:
flag = False
if flag:
    print("You Guys")
    print("are")
    print("Awesome")

Now, in the above examples, the statements following the 'If' statement did not get displayed because the condition was not satisfied.

Understanding Python 'if' Example Without Boolean Variables

In the above examples, we have used the boolean variables in place of conditions. However we can use any variables in our conditions. For example:

In [5]:
num = 100
if num < 200:
    print("num is less than 200")
num is less than 200

2. Python If else Statement Example

Why We Use 'If-Else' Statements?

We use if statements when we need to execute a certain block of Python code when a particular condition is true. If..else statements are like extension of ‘if’ statements, with the help of if..else we can execute certain statements if condition is true and a different set of statements if condition is false. For example, you want to print ‘even number’ if the number is even and ‘odd number’ if the number is not even, we can accomplish this with the help of if..else statement.

Python – Syntax of if..else statement

if condition:
   block_of_code_1
else:
   block_of_code_2

block_of_code_1: This would execute if the given condition is true

block_of_code_2: This would execute if the given condition is false

If-else example in Python

In [6]:
num = 22
if num % 2 == 0:
    print("Even Number")
else:
    print("Odd Number")
Even Number

3. Python 'If elif else' Statement Example

if condition:
   block_of_code_1
elif condition_2:
   block_of_code_2
elif condition_3:
   block_of_code_3
..
..
..
else:
  block_of_code_n
  1. There can be multiple ‘elif’ blocks, however there is only ‘else’ block is allowed.
  2. Out of all these blocks only one block_of_code gets executed. If the condition is true then the code inside ‘if’ gets executed, if condition is false then the next condition(associated with elif) is evaluated and so on. If none of the conditions is true then the code inside ‘else’ gets executed.
In [7]:
num = 1122
if 9 < num < 99:
    print("Two digit number")
elif 99 < num < 999:
    print("Three digit number")
elif 999 < num < 9999:
    print("Four digit number")
else:
    print("number is <= 9 or >= 9999")
Four digit number

4. Python 'Nested If else' Statement

When there is an if statement (or if..else or if..elif..else) is present inside another if statement (or if..else or if..elif..else) then this is calling the nesting of control statements.

In [8]:
num = -99
if num > 0:
    print("Positive Number")
else:
    print("Negative Number")
    #nested if
    if -99<=num:
        print("Two digit Negative Number")
Negative Number
Two digit Negative Number

5. Learning Python 'For Loop'

A loop is a used for iterating over a set of statements repeatedly. In Python we have three types of loops for, while and do-while. In this guide, we will learn for loop and the other two loops are covered in the separate tutorials.

Syntax of For loop in Python

for <variable> in <sequence>:
   body_of_loop that has set of statements
   which requires repeated execution

Here is a variable that is used for iterating over a . On every iteration it takes the next value from until the end of sequence is reached.

In [9]:
# Program to print squares of all numbers present in a list

# List of integer numbers
numbers = [1, 2, 4, 6, 11, 20]

# variable to store the square of each num temporary
sq = 0

# iterating over the given list
for val in numbers:
    # calculating square of each number
    sq = val * val
    # displaying the squares
    print(sq)
1
4
16
36
121
400

Function range()

In the given example, we have made use of the "For Loop" for iterating the items. However you can even use a range() function in for loop to iterate over numbers defined by range().

range(n): generates a set of whole numbers starting from 0 to (n-1). For Instance: range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]

range(start, stop): generates a set of whole numbers starting from start to stop-1. For Instance: range(5, 9) is equivalent to [5, 6, 7, 8]

range(start, stop, step_size): The default step_size is 1 which is why when we didn’t specify the step_size, the numbers generated are having difference of 1. However by specifying step_size we can generate numbers having the difference of step_size. For instance: range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]

Understanding range() function Python for loop example using

In [1]:
# Program to print the sum of first 5 natural numbers

# variable to store the sum
sum = 0

# iterating over natural numbers using range()
for val in range(1, 6):
    # calculating sum
    sum = sum + val

# displaying sum of first 5 natural numbers
print(sum)
15

For Loop With 'else' Block

In [2]:
for val in range(5):
	print(val)
else:
	print("The loop has completed execution")
0
1
2
3
4
The loop has completed execution

Nested For Loop In Python

In [3]:
for num1 in range(3):
	for num2 in range(10, 14):
		print(num1, ",", num2)
0 , 10
0 , 11
0 , 12
0 , 13
1 , 10
1 , 11
1 , 12
1 , 13
2 , 10
2 , 11
2 , 12
2 , 13

6. Python "While Loop"

While loop is used to iterate over a block of code repeatedly until a given condition returns false. In the last tutorial, we have seen for loop in Python, which is also used for the same purpose. The main difference is that we use while loop when we are not certain of the number of times the loop requires execution, on the other hand when we exactly know how many times we need to run the loop, we use for loop.

Syntax of while loop

while condition:
    body_of_while

Python – While Loop Example

In [8]:
num = 1
# loop will repeat itself as long as
# num < 10 remains true
while num < 10:
    print(num)
    #incrementing the value of num
    num = num + 3
1
4
7

Nested While Loop

In [9]:
i = 1
j = 5
while i < 4:
    while j < 8:
        print(i, ",", j)
        j = j + 1
        i = i + 1
1 , 5
2 , 6
3 , 7

7. Python "pass" Statement

The pass statement acts as a placeholder and usually used when there is no need of code but a statement is still required to make a code syntactically correct. For example we want to declare a function in our code but we want to implement that function in future, which means we are not yet ready to write the body of the function. In this case we cannot leave the body of function empty as this would raise error because it is syntactically incorrect, in such cases we can use pass statement which does nothing but makes the code syntactically correct.

Pass statement vs comment You may be wondering that a python comment works similar to the pass statement as it does nothing so we can use comment in place of pass statement. Well, it is not the case, a comment is not a placeholder and it is completely ignored by the Python interpreter while on the other hand pass is not ignored by interpreter, it says the interpreter to do nothing.

Python pass statement example

In [5]:
for num in [20, 11, 9, 66, 4, 89, 44]:
    if num%2 == 0:
        pass
    else:
        print(num)
11
9
89

8. Python Continue Statement

The continue statement is used inside a loop to skip the rest of the statements in the body of loop for the current iteration and jump to the beginning of the loop for next iteration. The break and continue statements are used to alter the flow of loop, break terminates the loop when a condition is met and continue skip the current iteration.

In [6]:
# program to display only odd numbers
for num in [20, 11, 9, 66, 4, 89, 44]:
    # Skipping the iteration when number is even
    if num%2 == 0:
        continue
    # This statement will be skipped for all even numbers
    print(num)
11
9
89

9. Python break Statement

The break statement is used to terminate the loop when a certain condition is met. We already learned in previous tutorials (for loop and while loop) that a loop is used to iterate a set of statements repeatedly as long as the loop condition returns true. The break statement is generally used inside a loop along with a if statement so that when a particular condition (defined in if statement) returns true, the break statement is encountered and the loop terminates.

In [7]:
# program to display all the elements before number 88
for num in [11, 9, 88, 10, 90, 3, 19]:
   print(num)
   if(num==88):
	   print("The number 88 is found")
	   print("Terminating the loop")
	   break
11
9
88
The number 88 is found
Terminating the loop

Dolly Solanki  Dolly Solanki