Introduction
In this article, I will explain conditional statements in Python. Conditional statements are also called decision-making statements. We use those statements while we want to execute a block of code when the given condition is true or false.
Type of condition statement in Python:
If statement
If statement is most usually used as a conditional statement.
Syntax
Example
Program for if statement,
- a = 10
- b = 20
- if a<b:
- print("a is less than b")
Output
If else statement
If else is a conditional statement. The statement itself says that if a given condition is true or false. True means executing the “if” statement to the output. False means executing the “else” statement to the output.
Syntax
- if(condition):
- {
-
- }
- else:
- {
-
- }
Example
Program for if else statement,
- a = 10
- b = 20
- if a==b:
- print("a and b are equal")
- else:
- print("a and b are not equal")
Output
Elif statement
Elif is a shortcut of else if condition statements. In Python one or more conditions are used in the elif statement.
Syntax
- if(condition):
- {
-
- }
- elif(condition):
- {
-
- }
- else:
- {
-
- }
Example
Program for elif statement
- a = 10
- b = 10
- if a < b:
- print("a is greater than b")
- elif a == b:
- print("a and b are equal")
- else:
- print("b is greater than a")
Output
Nested if statement
In python is using "if" statements inside other if statements it is called nested if statement.
Syntax
- if(condition):
- {
- if(condition):
- {
-
- }
- }
Example
Program for nested if statement,
- a= 1001
- if a> 100:
- print("Above 100")
- if a > 1000:
- print("and also above 1000")
Output
Nested if else statement
In Python is using one “if else” statement inside other if else statements it is called nested if else statement.
Syntax
- if(condition):
- {
- if(condition):
- {
-
- }
- else:
- {
-
- }
- }
- else:
- {
-
- }
Example
Program for nested if else statement,
- a=int(input("enter the a value"))
- if a> 100:
- print("Above 100")
- if a > 1000:
- print("and also above 1000")
- else:
- print("and also below 1000")
- else:
- print("below 100")
Output
Conclusion
In this article, we have seen conditional statements. I hope this article was useful to you. Thanks for reading!