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.
The syntax of if statement in Python is pretty simple.
if condition: block_of_code
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.
flag = True if flag: print("Welcome") print("To") print("CoderzColumn.com")
Welcome To CoderzColumn.com
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.
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:
num = 100 if num < 200: print("num is less than 200")
num is less than 200
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.
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
num = 22 if num % 2 == 0: print("Even Number") else: print("Odd Number")
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
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
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.
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
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
# 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
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]
# 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)
for val in range(5): print(val) else: print("The loop has completed execution")
0 1 2 3 4 The loop has completed execution
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
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
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
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
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
for num in [20, 11, 9, 66, 4, 89, 44]: if num%2 == 0: pass else: print(num)
11 9 89
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.
# 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
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.
# 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