Conditional statements are a fundamental part of programming, allowing code to make decisions based on certain conditions. In Python, the if/else statement helps control the execution flow by running different blocks of code depending on whether a condition is met or not.
This Python tutorial provides steps on using if/else statements, covering syntax, multiple conditions, nested statements, common mistakes, and the best practices.
An if/else statement in Python is a control structure that executes a block of code if a condition evaluates to True, otherwise, it executes an alternative block of code.
if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False
Example:
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
if-elif-else
for Multiple ConditionsWhen dealing with multiple conditions that need to be evaluated, Python’s if-elif-else
structure is particularly useful. The elif
clause (short for “else if”) allows you to specify additional conditions to check if the initial if
condition is not met. This enables a more structured and efficient way to handle complex decision-making processes within your code.
Example:
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")
In Python, you can use a concise syntax for simple if/else
statements. This is known as the Ternary Operator. It’s a one-liner conditional expression that evaluates to a value based on a condition.
Example:
num = int(input("Enter a number: "))
result = "Even" if num % 2 == 0 else "Odd"
print(result)
Nested if
statements allow you to evaluate multiple conditions within a single if
block. This is particularly useful when you need to check a series of conditions before executing a specific block of code. By nesting if
statements, you can create a more structured and efficient way to handle complex decision-making processes within your code.
Example:
num = int(input("Enter a number: "))
if num > 0:
if num % 2 == 0:
print("Positive Even Number")
else:
print("Positive Odd Number")
else:
print("Negative Number or Zero")
and
, or
, not
Python provides logical operators to combine multiple conditions in a single expression. This allows for more complex decision-making processes within your code. The logical operators available in Python are and
, or
, and not
.
Example:
temp = int(input("Enter the temperature: "))
if temp > 30 and temp < 40:
print("It's a hot day!")
else:
print("It's not a hot day.")
# Example using 'or' operator
if temp > 30 or temp < 10:
print("Temperature is extreme!")
# Example using 'not' operator
if not (temp > 30 and temp < 40):
print("It's not a hot day.")
if/else
vs. match-case
(Python 3.10+)With Python 3.10, the match-case
statement provides an alternative for certain conditional checks. This new feature is particularly useful when you have a series of conditions to check and want to avoid the nested if/else
statements. The match-case
statement is more concise and easier to read, making your code more maintainable and efficient.
Example of match-case
:
def get_day_name(day):
match day:
case 1:
return "Monday"
case 2:
return "Tuesday"
case _:
return "Invalid day"
if/else
and match-case
StatementsFeature | if/else Statements |
match-case Statement |
---|---|---|
Syntax | More verbose | More concise |
Readability | Can be complex for multiple conditions | Easier to read for multiple conditions |
Use Cases | Suitable for simple conditional checks | Ideal for checking multiple values of a single variable |
Performance | No significant difference | No significant difference |
Python Version | Supported in all Python versions | Introduced in Python 3.10 |
if/else
statements for simple conditional checks or when working with Python versions prior to 3.10.match-case
statements when you need to check multiple values of a single variable, especially in Python 3.10 or later.Python uses indentation to define blocks of code. Missing indentation will cause an error.
Example:
if True:
print("This will cause an error!") # IndentationError
Fixed Example:
if True:
print("This will not cause an error!")
Incorrect logical operations can lead to unexpected results.
Example:
if age >= 18 and age <= 60: # Correct
if age >= 18 or <= 60: # Incorrect
Use exception handling when dealing with user input.
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input! Please enter a number.")
You can use error handling with if else statements in Python. Here’s an example of how to do this:
try:
# Code that may raise an exception
num = int(input("Enter a number: "))
except ValueError:
# Code to handle the exception
print("Invalid input! Please enter a number.")
else:
# Code to execute if no exception is raised
print("You entered a valid number.")
finally:
# Code to execute regardless of whether an exception was raised
print("Thank you for using this program.")
elif
conditions in Python?Yes, you can add as many elif
conditions as needed to check multiple scenarios.
if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition2 is True
elif condition3:
# code to execute if condition3 is True
else:
# code to execute if all conditions are False
if
and elif
in Python?An if
statement is always checked first. If if
is false, then elif
conditions are evaluated in order.
Here’s a table highlighting the differences:
if Statement |
elif Statement |
---|---|
Always checked first | Evaluated only if if is false |
Can have multiple if statements |
Can have multiple elif statements |
Can have an else block |
Can have an else block |
Remember, only one block of code will be executed. If the if
statement is true, the elif
and else
blocks will be skipped. If the if
statement is false, the elif
block will be executed. If the elif
statement is false, the else
block will be executed.
Here’s an example of how to use if
, elif
, and else
in Python:
num = int(input("Enter a number: "))
if num > 0:
print("The number is positive.")
elif num == 0:
print("The number is zero.")
else:
print("The number is negative.")
Make sure each block of code is properly indented using four spaces or a tab.
if/else
conditions?For readability, break down complex conditions into smaller functions or use logical operators.
Here’s an example of how to use logical operators in Python:
num = int(input("Enter a number: "))
if num > 0 and num % 2 == 0:
print("The number is positive and even.")
elif num > 0 and num % 2 != 0:
print("The number is positive and odd.")
elif num == 0:
print("The number is zero.")
else:
print("The number is negative.")
switch-case
alternative in Python?Yes, Python 3.10 introduced match-case
, which behaves similarly to a switch
statement.
Here’s an example of how to use match-case
in Python:
def match_case_example(argument):
match argument:
case 1:
print("You chose 1.")
case 2:
print("You chose 2.")
case 3:
print("You chose 3.")
case _:
print("Invalid choice.")
Understanding if/else
statements is crucial for decision-making in Python programming. By mastering conditional logic, you can write more efficient and error-free code.
If you want to learn more about Python, check out these tutorials:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!