Python if-elif-else Statement
If statement
The if statement is used to execute a block of code based on a specific condition. The syntax of the if statement is as follows:
if condition:
code-block
The body code block is only executed if the condition is evaluated to be true. Let’s take a look at an example of using if statement.
x = 10
if x > 0:
print('x is greater than 0')
if-else statement
if-else statement is used to execute a block of code when the if condition is true otherwise it will execute the block of code of the else statement. The syntax of if-else statement is as follows:
if if-condition:
if-body
else:
else-body
Here is an example of using if-else statement:
language = 'Python'
if (language == 'Python'):
print('You are programming Python')
else:
print('What language are you programming?')
if-elif-else statement
Sometimes, you want to have multiple conditions to check to execute a specific code block. In these cases, you need to use if-elif-else statement. The common syntax of if-elif-else statement is as below:
if if-condition:
if-code-block
elif condition-1:
code-block-1
elif condition-2:
code-block-2
elif condition-n:
code-block-n
else:
code-block-else
Basically if the if-condition is evaluated to be true, the if-code-block will execute. If any condition from condition-1 to condition-n is true, the corresponding code-block-i will be executed. Otherwise the code-block-else will be executed.
Let’s take a look at an example of using if-elif-else statement.
language = "Python"
if (language == "Java"):
print("write once, run anywhere")
elif(language == "C#"):
print("another version of Java?")
elif(language == "Python"):
print("remarkable power with very clear syntax")
else:
print("What is ",language,”?”)
Note that the if, if-else,if-else-if can be nested.