Python is a dynamically typed programming language. It offers all the bells and whistles one would expect in a modern, high-level programming language. Python is both easy to learn and easy to use. Its simple, yet powerful syntax enables quick development cycles.
Python’s ‘if’ statement is used to control the flow of code based on a condition. Whenever a program has multiple conditions and we want to execute the specific block of code based on some condition, you can use the ‘if’ statement to achieve it.
The Basic Syntax
if some_condition: # Do something here
The keyword if determines if the conditions of the statement are true. If it is true, execute the code inside the if-block. If it is not true, then just skip the code inside the block and continue on.
Besides if
, there are two other conditional statements in Python: else
and elif
.
The “else” and “elif” Keywords
The if-else statement allows you to define a block of code that is executed when the condition of the if statement is false. To use the if-else statement, you incorporate the keyword else
.
if some_condtion: # Do something here else: # Do something else here
The elif
statement allows you to test multiple conditions without having to use multiple if statements. To use the elif
statement, you must place it between an if
statement and an else
statement.
if some_condition: # Do something here elif some_other_condition: # Do something else here else: # Do something else entirely here
Examples
Example 1: Using if statement
The following code snippet prints “I am smart” if the variable “x” is equal to “3” and “I am not smart” if the variable “x” is not equal to “3”.
x = 3 if x == 3: print("I am smart") else: print("I am not smart")
Output:
I am smart
Example 2: Using if-elif statement
The code below takes an integer input from the user and checks whether the input is even or odd using an if-elif statement.
num = int(input("Enter a number: ")) if num % 2 == 0: print("The number is even") elif num % 2 != 0: print("The number is odd")
Output:
Enter a number: 6 The number is even
Example 3: Using nested if-else statement
This program will ask for a user’s age, and then determine whether or not they can vote.
age = int(input("How old are you? ")) if age >= 18: country = input("What country do you live in? ") if country != "US": print("You cannot vote.") else: state = input("What state do you live in? ") if state == "Texas": print("You cannot vote.") else: print("You can vote.") else: print("You cannot vote.")
Output:
How old are you? 19 What country do you live in? US What state do you live in? Texas You cannot vote.
Conclusion
The ‘if’ statement in Python is a crucial component, especially for decision-making purposes. It is the technique or the process by which one can execute a block of code based on some condition. In this tutorial, we learned about the ‘if’ statement’s syntax and its variants, namely ‘else’ and ‘elif’.