In Python, Conditionals statement are used to execute different blocks of code based on certain conditions.
The primary conditional statements in Python are if, elif (short for "else if"), and else.
if-else: If condition provided in the if statement is false, then the else statement will be executed.
The if statement is used to execute a block of code if a specified condition is true.
if expression: statement
if-elif-else: when we have a series of if-elif-else statements to emulate the behaviour of a switch statement.
xyz = 1010 if xyz > 1010: print("xyz is greater than 1010")
The if-else statement is used to execute one block of code if the condition is true, and another block of code if the condition is false.
xyz = 2323 if xyz > 2323: print("xyz is greater than 2323") else: print("xyz is less than or equal to 2323")
The if-elif-else statement allows you to check multiple conditions. It executes the first block of code whose condition is true.
xyz = 2020 if xyz > 2020: print("xyz is greater than 2020") elif xyz == 2020: print("xyz is equal to 2020") else: print("xyz is less than 2020")
Note: We can have multiple elif blocks to check additional conditions as needed.
We can also nest conditions within each other to handle more complex scenarios.
xy = 2020 yz = 1010 if xy > 1010: if yz > 505: print("Both xy and yz are greater than their respective thresholds") else: print("xy is greater than 1010, but yz is not greater than 505") else: print("xy is not greater than 2020")
Python does not have a built-in switch statement like some other programming languages (e.g., Java, C/C++, JavaScript).
However, we can achieve similar functionality using alternative approaches.
We can use a series of if-elif-else statements to emulate the behaviour of a switch statement.
def switch_case(argument): if argument == 1: print("Case 1") elif argument == 2: print("Case 2") elif argument == 3: print("Case 3") elif argument == 4: print("Case 4") else: print("Default case") switch_case(3) // Output: Case 3
We can use a dictionary to map case values to corresponding functions or values.
def case1(): print("Case 1") def case2(): print("Case 2") def case3(): print("Case 3") def case4(): print("Case 4") switch_dict = { 1: case1, 2: case2, 3: case3, 4: case4, } argument = 3 switch_dict.get(argument, lambda: print("Default case"))()