In the last tutorial we learned how to use if statements in Python. In this guide, we will learn another control statement ‘if..else’.
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 flow control
If-else example in Python
num = 22 if num % 2 == 0: print("Even Number") else: print("Odd Number")
Output:
Even Number
Leave a Reply