Conditional / Selection / Branching Statements
The purpose of Conditional / Selection / Branching Statements is to "perform a certain operation only once, depending on condition evaluation."
In other words, perform a certain X-operation when the condition is True, or perform a Y-operation only once when the condition is False.
In Python programming, we have 5 types of Conditional / Selection / Branching Statements. They are.
- if statement
- if-else statement
- if-elif-else statement.
- nested if statement.
- match-case statement
- if is a keyword.
- If the test condition is True, the PVM (Python Virtual Machine) executes the indented block of statements, then proceeds to execute the other statements in the program.
- If the test condition is False, the PVM skips the indented block and only executes the other statements in the program.
# if statement
if condition:
# Indented block of statements (executes if condition is True)
# Other statements in the program (execute regardless)
x = 10
if x > 5:
print("x is greater than 5")
print("This runs no matter what")
# moviee.py
# Prompt user for ticket status and store input in 'tkt' variable
tkt = input("D u have a ticket(yes/no): ")
# Check if the input (converted to lowercase) is exactly "yes"
if(tkt.lower() == "yes"):
# If condition is True, allow entry and print theater-related messages
print("Enter into theater")
print("watch movee")
print("Enjoy..")
# This line executes regardless of the if condition, instructing user to go home
print("\nGoto Home and Read PYTHON NOTES")
# posnegzero.py
# Prompt user to enter a number and convert the input to an integer, store in 'n'
n = int(input("Enter a number: ")) # Example: n = 10
# Check if the number is greater than 0
if (n > 0):
# If True, print that the number is positive using string formatting
print("{} is Possitive".format(n))
# Check if the number is less than 0
if (n < 0):
# If True, print that the number is negative using string formatting
print("{} is Negative".format(n))
# Check if the number is exactly 0
if (n == 0):
# If True, print that the number is zero using string formatting
print("{} is Zero".format(n))
# Print a message indicating the program has finished (runs regardless of conditions)
print("Program completed")
- if and else are keywords.
- If the test condition is True, the Python Virtual Machine (PVM) executes the Indentation Block of statements-I (under if), then proceeds to execute the Other statements in Program (outside the if..else block).
- If the test condition is False, the PVM executes the Indentation Block of statements-II (under else), then executes the Other statements in Program (skipping the if block).
- At any point, the PVM executes either the if block or the else block, but not both, and then continues with the remaining program statements.
# if statement
if condition:
# Indented block of statements (executes if condition is True)
else:
executes
# even_or_odd.py
# Prompt user to enter a number and convert it to an integer
num = int(input("Enter a number: "))
# Check if the number is even or odd using the modulo operator
if num % 2 == 0:
# If number is divisible by 2 (remainder 0), it's even
print(f"{num} is Even")
else:
# If number is not divisible by 2 (remainder 1), it's odd
print(f"{num} is Odd")
# driving_license.py
# Prompt user to enter their age and convert it to an integer
age = int(input("Enter your age: "))
# Check if the user is eligible for a driving license (age 18 or older)
if age >= 18:
# If age is 18 or more, user is eligible
print("You are eligible for a driving license.")
else:
# If age is less than 18, user is not eligible
print("You are not eligible for a driving license.")
# driving_license.py
# Prompt user to enter their name as a string
name = input("Enter your name: ")
# Prompt user to enter their age and convert it to an integer
age = int(input("Enter your age: "))
# Prompt user to confirm if they have a learner's permit (string input)
permit = input("Do you have a learner's permit (yes/no)? ")
# Check eligibility: age must be 18 or more AND permit answer must be "yes"
if age >= 18 and permit.lower() == "yes":
# If both conditions are True, user is eligible, include name in message
print(f"{name}, you are eligible for a driving license.")
else:
# If either condition is False, user is not eligible, include name in message
print(f"{name}, you are not eligible for a driving license.")
- If test condition 1 is True, the Python Virtual Machine (PVM) executes Block of statements-1 and proceeds to the Other statements in the Program.
- If test condition 1 is False, it evaluates test condition 2. If test condition 2 is True, the PVM executes Block of statements-2 and proceeds to the Other statements in the Program.
- If test cond2 is False, it evaluates test cond3. If test condition 3 is True, the PVM executes Block of statements-3, then proceeds to the Other statements in the Program.
- This process continues until all test conditions are evaluated.
- If all conditions are False, the PVM executes the else block (if present), then proceeds to the Other statements in the Program.
- The else block is optional.
# syntax
if condition1:
# Code block for condition1
elif condition2:
# Code block for condition2
elif condition3:
# Code block for condition3
else:
# Code block if no conditions are True
# bigex1.py
# Program for accepting 3 integers and finding the biggest among them
# Prompt user to enter three numbers and convert them to integers
a = int(input("Enter First Number: ")) # Example: a = 10
b = int(input("Enter Second Number: ")) # Example: b = 13
c = int(input("Enter Third Number: ")) # Example: c = 2
# Find the largest number using if..elif..else
if (a > b) and (a > c):
# If a is greater than both b and c, a is the largest
print("max({},{},{})={}".format(a, b, c, a))
elif (b > a) and (b > c):
# If b is greater than both a and c, b is the largest
print("max({},{},{})={}".format(a, b, c, b))
elif (c > a) and (c > b):
# If c is greater than both a and b, c is the largest
print("max({},{},{})={}".format(a, b, c, c))
elif (a == b) and (c == b) and (c == a):
# If all numbers are equal, print a special message
print("ALL Values are Equal:")
# digitex2.py (Improved)
# This program accepts a digit and prints its name
# Prompt user to enter a digit and convert it to an integer
d = int(input("Enter a digit: ")) # Expected: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# Check the value of the digit and print its name
if d == 0:
print(f"{d} is ZERO")
elif d == 1:
print(f"{d} is ONE")
elif d == 2:
print(f"{d} is TWO")
elif d == 3:
print(f"{d} is THREE")
elif d == 4:
print(f"{d} is FOUR")
elif d == 5:
print(f"{d} is FIVE")
elif d == 6:
print(f"{d} is SIX")
elif d == 7:
print(f"{d} is SEVEN")
elif d == 8:
print(f"{d} is EIGHT")
elif d == 9:
print(f"{d} is NINE")
elif d < 0 and d >= -9:
# Check if the number is a negative single digit
print(f"{d} is a Negative Digit")
elif d not in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
# Check if the number is not a single digit (0-9)
print(f"{d} is not a single digit (must be between 0 and 9)")
- The outer if condition (condition1) is evaluated first.
- If condition1 is True, the code enters the outer if block.
- Inside this block, the inner if condition (condition2) is evaluated.
- If condition2 is True, its code block executes; otherwise, the inner else (if present) executes.
- If condition1 is False, the outer else (if present) executes, and the inner if is skipped.
if condition1:
# Code block for condition1
if condition2:
# Code block for condition2
else:
# Code block if condition2 is False
else:
# Code block if condition1 is False
age = 20
has_license = True
if age >= 18:
print("You are old enough to drive.")
if has_license:
print("You can drive legally!")
else:
print("You need a driver's license.")
else:
print("You are too young to drive.")
- The match-case statement is a feature available in Python 3.10 and later, designed to handle decision-making for predefined operations.
- It’s ideal for scenarios with fixed, predictable choices, offering clearer and more structured code compared to nested if statements.
- Uses match (choice expression) followed by multiple case labels, each with a block of statements to execute if the label matches.
- The expression after the match can be an integer, character, string, or boolean, determining which case block runs.
- Labels (e.g., Label1, Label2) can be integers, characters, strings, or booleans, and are compared against the choice expression
- If the choice expression matches a case label, the Python Virtual Machine (PVM) executes the corresponding block of statements and skips others.
- The PVM compares the choice expression against labels in order; the first matching label’s block is executed.
- An optional case _ block executes if no labels match the choice expression, acting as a fallback (similar to else).
- Writing case _ is not mandatory; if omitted and no labels match, no case block executes.
- Match-case simplifies complex decision trees, making code more maintainable for scenarios like menu systems or pattern matching.
wkn = input("Enter the week name: ").strip()
match wkn.lower():
case "monday":
print(f"{wkn} is working day")
case "tuesday":
print(f"{wkn} is working day")
case "wednesday": # Corrected spelling
print(f"{wkn} is working day")
case "thursday":
print(f"{wkn} is working day")
case "friday":
print(f"{wkn} is working day")
case "saturday":
print(f"{wkn} is Week End")
case "sunday":
print(f"{wkn} is Holiday day")
case _:
print(f"{wkn} is not week day")
print("\tArithmetic Operations")
print("\t1. Addition:")
print("\t2. Substraction:")
print("\t3. Multiplication:")
print("\t4. Division:")
print("\t5. Modulo Division:")
print("\t6. Exponetiation:")
print("\t7. Exit:")
ch=int(input("Enter Ur Choice:"))
match(ch):
case 1:
a,b=float(input("Enter First Value for Addition:")),float(input("Enter Second Value for Addition:"))
print("sum({},{})={}".format(a,b,a+b))
case 2:
a=float(input("Enter First Value for Substraction:"))
b=float(input("Enter Second Value for Substraction:"))
print("sub({},{})={}".format(a,b,a-b))
case 3:
a=float(input("Enter First Value for Multiplication:"))
b=float(input("Enter Second Value for Multiplication:"))
print("mul({},{})={}".format(a,b,a*b))
case 4:
a=float(input("Enter First Value for Division:"))
b=float(input("Enter Second Value for Division:"))
print("div({},{})={}".format(a,b,a/b))
print("floor div({},{})={}".format(a,b,a//b))
case 5:
a=float(input("Enter First Value for Modulo Division:"))
b=float(input("Enter Second Value for Modulo Division:"))
print("mod({},{})={}".format(a,b,a%b))
case 6:
a=float(input("Enter Base:"))
b=float(input("Enter Power:"))
print("exp({},{})={}".format(a,b,a**b))
case 7:
print("\nThanks for Using Program!")
sys.exit()
case _:
print("Ur Choice of selection is wrong!")