Introduction
Before we begin talking about Python if..else Statement, let's briefly understand – What is Python?
One of the most important concepts in computer programming is decision-making. With slight adjustments, Python supports the common flow control statements seen in other languages. One of the simplest and most well-known statements for executing code depending on a specific condition is the if control statement.
In Python, if-else
is a control structure that allows you to conditionally execute different blocks of code based on certain conditions. It is used to perform branching in a program, where different actions are taken depending on whether a condition is True or False.
In this tutorial, you will understand Python if..else Statement. We will also address a few FAQs on Python if..else Statement.
Python if
Statement
The simplest if
statement in Python looks like this:
if EXPRESSION:
STATEMENT
The if
statement begins with the if
keyword and is followed by the conditional expression.
The colon (:
) must come after the EXPRESSION
. The STATEMENT
is executed if the EXPRESSION
evaluates to True
. When EXPRESSION
returns False
, the STATEMENT
is ignored and nothing happens. STATEMENT
can refer to any statement, including numerous statements or nested if
statements. Use the pass
statement to carry out no statements.
The STATEMENT
block begins with an indentation and concludes with the first unintended line. Most individuals either prefer to indent 4-space or 2-space. The official Python Code Style Guide suggests using 4-spaces per indentation level and avoiding mixing tabs and spaces for indentation.
Consider the following example script, which determines whether a given number is greater than 5.
number = int(input('Enter a number: '))
if number > 5:
print(number, 'is greater than 5.')
Save the code in a file and execute it from the command line:
python test.py
You will be prompted to input a number by the script. For instance, if you enter 10, the conditional expression will evaluate to True
(10 is greater than 5), and the print
function will be called.
Output
10 is greater than 5.
Standard comparison operations are supported by Python:
a == b
- True if variablesa
andb
are equal.a != b
- True if variablesa
andb
are not equal.a > b
- True if variablea
is greater than variableb
.a >= b
- True if variablea
is equal to or greater than variableb
.a < b
- True if variablea
is less than variableb
.a <= b
- True if variablea
is equal to or less than variableb
.
The in
keyword can also be used to determine whether a value is contained in an iterable (such as a string, list, tuple, dictionary, etc.):
s = 'vegastack'
if 've' in s:
print('True.')
Here's another example using a dictionary:
d = {'a': 2, 'b': 4}
if 'a' in d:
print('True.')
When used on a dictionary, the in
keyword determines whether the dictionary contains a specific key.
Use the logical not
operator to negate the conditional expression:
number = int(input('Enter a number: '))
if not number < 5:
print(number, 'is greater than 5.')
if..else
Statement
A condition is tested in an if..else
statement, and based on the outcome, one of the two sentences is executed.
The if..else
statement in Python takes the following form:
if EXPRESSION:
STATEMENT1
else:
STATEMENT2
If EXPRESSION
evaluates to True
, STATEMENT1
is carried out. Otherwise, STATEMENT2
is carried out if EXPRESSION
returns False
. Only one else
clause is acceptable in the statement.
The else
keyword must have a (:
) colon at the end and be indented at the same level as the corresponding if
keyword.
Let us update the previous example script to include an else
clause:
number = int(input('Enter a number: '))
if number > 5:
print(number, 'is greater than 5.')
else:
print(number, 'is equal or less than 5.')
The script will produce a different message if you execute the code and enter a number depending on whether the value is greater or less/equal to 5.
if..elif..else
Statement
else if
is shortened to form the elif
keyword.
The if..elif..else
statement in Python has the following form:
if EXPRESSION1:
STATEMENT1
elif: EXPRESSION2:
STATEMENT2
else:
STATEMENT3
The STATEMENTS1
are carried out if the evaluation of EXPRESSION1
is True
. The STATEMENTS2
are carried out if the EXPRESSION2
evaluates to True
. The STATEMENTS3
is executed if none of the expressions return True
.
The elif
keyword must have a (:
) colon at the end and be indented the same amount as the if
keyword. The statement may contain one or more elif
clauses. The else
clause is not mandatory. None of the statements are executed if the else
clause is absent and every expression evaluates to False
.
The conditions are evaluated in order. The remaining conditions are not checked once a condition returns True
, and the program control jumps to the end of the if
statements.
Let us modify the previous script by adding an elif
clause:
number = int(input('Enter a number: '))
if number > 5:
print(number, 'is greater than 5.')
elif number < 5:
print(number, 'is less than 5.')
else:
print(number, 'is equal to 5.')
In contrast to the majority of programming languages, Python lacks switch
or case
statements. The switch
or case
statements can be replaced by a series of multiple elif
statements.
Nested if
Statements
You can nest if
statements inside other if
statements in Python. In general, you should aim to use elif
rather than nesting if
statements and always try to avoid excessive indentation.
The script that follows will ask you to enter three numbers and will print the largest one.
number1 = int(input('Enter the first number: '))
number2 = int(input('Enter the second number: '))
number3 = int(input('Enter the third number: '))
if number1 > number2:
if number1 > number3:
print(number1, 'is the largest number.')
else:
print(number3, 'is the largest number.')
else:
if number2 > number3:
print(number2, 'is the largest number.')
else:
print(number3, 'is the largest number.')
This is how the output will look:
Output
Enter the first number: 455
Enter the second number: 567
Enter the third number: 354
567 is the largest number.
Multiple Conditions
You can combine numerous conditions in the if
statements using the logical or
, and, and
operators.
Here is a different script that will print the largest of the three integers. In this version, the logical and operator and elif
will be used in place of the nested if
statements.
number1 = int(input('Enter the first number: '))
number2 = int(input('Enter the second number: '))
number3 = int(input('Enter the third number: '))
if number1 > number2 and number1 > number3:
print(number1, 'is the largest number.')
elif number2 > number3 and number2 > number3:
print(number2, 'is the largest number.')
else:
print(number3, 'is the largest number.')
FAQs on Python if..else Statement
Can you have multiple else
statements in a single if
block?
No, in Python, you can only have one else
statement associated with an if
block. It is used as a final catch-all block when all preceding conditions are false.
What happens if the condition in the if
statement is not true?
If the condition in the if
statement is false, the code block within the else
statement (if present) will be executed. Otherwise, it will be skipped.
Can you nest if-else
statements within each other?
Yes, you can nest if-else
statements within each other to handle more complex conditional logic.
Can you use logical operators (such as and
, or
, not
) in the conditions of if-else
statements?
Yes, you can use logical operators to combine multiple conditions within the if
statement.
What happens if there is no else
statement in an if-else
block?
If there is no else
statement, the code block associated with the if
statement will be executed if the condition is true. If the condition is false, the program will simply move on to the next line of code.
Can the if-else
statement be used inside a function?
Yes, the if-else
statement can be used anywhere in Python code, including inside functions.
What is the difference between if-elif-else
and multiple if-else
statements?
The if-elif-else
structure allows you to check multiple conditions in sequence until one of them is true. In contrast, using multiple if-else
statements would check each condition independently, which could result in multiple blocks of code being executed.
Conclusion
By evaluating specified conditions, the if
, if..else
, and if..elif..else
statements let you manage the flow of the Python execution.
If you have any queries, feel free to post a comment below, and we'll be happy to answer them.