Conditional Statements in Python
Conditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations.
If Statement
The if
statement is the simplest form of a conditional statement. It executes a block of code if the given condition is true.
age = 20 if age >= 18: print("Eligible to vote.")
Short Hand If
The short-hand if statement allows us to write a single-line if statement.
age = 19 if age > 18: print("Eligible to Vote.")
If-Else Conditional Statements
The if-else
statement allows us to specify a block of code that will execute if the condition evaluates to false.
age = 10 if age <= 12: print("Travel for free.") else: print("Pay for ticket.")
Short Hand If-Else
The short-hand if-else statement allows you to write a single-line if-else statement.
marks = 45 res = "Pass" if marks >= 40 else "Fail" print(f"Result: {res}")
Elif Statement
The elif
statement stands for "else if" and allows us to check multiple conditions.
age = 25 if age <= 12: print("Child.") elif age <= 19: print("Teenager.") elif age <= 35: print("Young adult.") else: print("Adult.")
Nested If..Else Conditional Statements
Nested if..else means an if-else statement inside another if statement.
age = 70 is_member = True if age >= 60: if is_member: print("30% senior discount!") else: print("20% senior discount.") else: print("Not eligible for a senior discount.")
Ternary Conditional Statement
A ternary conditional statement is a compact way to write an if-else condition in a single line.
age = 20 s = "Adult" if age >= 18 else "Minor" print(s)
Match-Case Statement
The match-case
statement is Python's version of a switch-case found in other languages.
number = 2 match number: case 1: print("One") case 2 | 3: print("Two or Three") case _: print("Other number")
Conclusion
Conditional statements in Python are fundamental for controlling the flow of execution in your programs. By utilizing if
, elif
, and else
, you can create dynamic and responsive applications that behave differently based on user input or other conditions.
0 Comments