Conditional Statements in Python

Conditional statements in Python are used to make decisions based on certain conditions. The basic syntax includes if, elif (short for "else if"), and else. Let's explore these statements with examples:
1. The if Statement:
Purpose: Executes a block of code if a specified condition is true.
Syntax:
#!/usr/bin/python3 if condition: # Code to execute if the condition is trueExample:
#!/usr/bin/python3 x = 10 if x > 5: print("x is greater than 5")Explanation: The code inside the
ifblock runs only if the condition (x > 5) is true.
2. The elif Statement:
Purpose: Checks additional conditions if the previous
iforelifconditions are false.Syntax:
#!/usr/bin/python3 if condition1: # Code to execute if condition1 is true elif condition2: # Code to execute if condition2 is true else: # Code to execute if none of the conditions are trueExample:
#!/usr/bin/python3 y = 3 if y > 5: print("y is greater than 5") elif y > 0: print("y is positive") else: print("y is non-positive")Explanation: The code inside the first
iforelifblock whose condition is true will execute. If none are true, theelseblock executes.
3. The else Statement:
Purpose: Defines a block of code to be executed if none of the conditions in the
iforelifstatements are true.Syntax:
#!/usr/bin/python3 if condition: # Code to execute if the condition is true else: # Code to execute if the condition is falseExample:
#!/usr/bin/python3 z = -2 if z > 0: print("z is positive") else: print("z is non-positive")Explanation: If
zis not greater than 0, the code inside theelseblock will execute.
4. Combining Conditions:
Purpose: Combine conditions using logical operators (
and,or,not).Syntax:
#!/usr/bin/python3 if condition1 and condition2: # Code to execute if both condition1 and condition2 are true elif condition1 or condition2: # Code to execute if either condition1 or condition2 is trueExample:
#!/usr/bin/python3 a = 7 if a > 0 and a % 2 == 0: print("a is a positive even number") elif a > 0 and a % 2 != 0: print("a is a positive odd number") else: print("a is non-positive")
5. Nested Conditions:
Purpose: Place one or more conditional statements inside another.
Example:
#!/usr/bin/python3 b = -5 if b > 0: if b % 2 == 0: print("b is a positive even number") else: print("b is a positive odd number") else: print("b is non-positive")Explanation: The inner
ifstatement is nested inside the outerifstatement.
Conclusion:
Conditional statements are essential for creating decision-making logic in Python. They allow your code to respond dynamically to different situations. Practice using them with various examples to reinforce your understanding.
