Python If-Else – Python Conditional Syntax Example
As a Python developer, one of the first control flow tools you‘ll need to master is the if-else statement. If-else allows you to make decisions in your code based on whether certain conditions are met. It‘s a fundamental building block for writing programs that can adapt their behavior based on input data or the state of variables.
In this article, we‘ll take an in-depth look at the syntax and usage of if-else in Python. We‘ll start with the basics and gradually explore more advanced concepts and best practices. Whether you‘re a beginner or an experienced Pythonista, I hope you‘ll find some valuable insights here!
If-Else Syntax in Python
The core syntax of an if statement in Python looks like this:
if condition:
# code block executed if condition is true
Here, condition
is an expression that evaluates to either True
or False
. If condition
is true, the indented code block under the if
line will be executed.
Python uses indentation (usually 4 spaces) to define code blocks, unlike curly braces in languages like Java or C++. The colon (:
) at the end of the if
line signals the start of the indented block.
An else
clause can be added to specify a code block that should run if the condition is false:
if condition:
# run if condition is true
else:
# run if condition is false
You can check multiple exclusive conditions by chaining elif
(short for "else if") clauses in between if
and else
:
if condition1:
# run if condition1 is true
elif condition2:
# run if condition1 is false and condition2 is true
else:
# run if both condition1 and condition2 are false
Here‘s a concrete example using comparison operators:
x = 10
if x > 20:
print("x is greater than 20")
elif x > 5:
print("x is greater than 5 but not greater than 20")
else:
print("x is less than or equal to 5")
Since x
is 10, the output will be "x is greater than 5 but not greater than 20".
Nested If Statements
If statements can be nested inside each other to make more complex decisions. Here‘s an example:
age = 25
has_license = True
if age >= 18:
if has_license:
print("You can drive!")
else:
print("You need to get a license first.")
else:
print("You‘re too young to drive.")
With an age
of 25 and has_license
set to True
, this code will output "You can drive!".
Nested if statements can be harder to read, so it‘s often better to use logical operators like and
and or
to combine conditions:
if age >= 18 and has_license:
print("You can drive!")
elif age >= 18:
print("You need to get a license first.")
else:
print("You‘re too young to drive.")
This is more concise and avoids the "arrow anti-pattern" of deeply nested code.
Logical Operators: and, or, not
Python provides three logical operators for combining or inverting boolean expressions:
and
: ReturnsTrue
if both operands are true,False
otherwiseor
: ReturnsTrue
if at least one operand is true,False
otherwisenot
: Returns the opposite boolean value of its operand
Some examples:
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False
print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False
print(not True) # False
print(not False) # True
Logical operators allow you to write more expressive conditions and minimize nested if statements. For example:
if score >= 60 and time_taken <= max_time:
print("You passed the level!")
Truthiness and Falsiness
In Python, every value can be evaluated as either "truthy" or "falsy" in a boolean context like an if statement. The following values are considered falsy:
False
None
0
(integer zero)0.0
(float zero)‘‘
or""
(empty string)[]
(empty list){}
(empty dictionary)
Any other value is considered truthy, including non-empty strings, lists, dictionaries, and custom objects.
This allows you to write concise conditions like:
name = input("Enter your name: ")
if name:
print(f"Hello, {name}!")
else:
print("You didn‘t enter a name.")
If the user enters an empty string for name
, it will be evaluated as falsy and the else
block will run.
One-Line If-Else
If you have a simple if-else statement that can fit on one line, you can use this shorthand syntax:
x = 5
result = "Positive" if x > 0 else "Non-positive"
print(result) # "Positive"
This is equivalent to:
x = 5
if x > 0:
result = "Positive"
else:
result = "Non-positive"
print(result) # "Positive"
One-line if-else statements (also known as ternary expressions) should be used sparingly, as they can reduce readability if overused or nested.
Match-Case Statements
Python 3.10 introduced a new match
statement that can be used as an alternative to complex if-elif chains for comparing a value against multiple patterns. Here‘s a simple example:
http_status = 404
match http_status:
case 200:
print("OK")
case 404:
print("Not Found")
case 500:
print("Internal Server Error")
case _:
print("Unknown status code")
This will output "Not Found". The _
acts as a catch-all pattern that matches any value.
Match-case is a powerful feature, but it‘s still quite new, so you may want to stick with traditional if-elif-else for maximum compatibility.
Real-World Examples
If-else statements have countless applications in real-world Python code. Here are just a few examples:
- Checking user input for validity before processing it
- Giving different responses based on the value of an API status code
- Applying different discounts based on customer loyalty tiers
- Customizing app behavior based on user-selected settings
- Handling different types of exceptions in a try-except block
- Implementing game logic and win/loss conditions
Whenever your program needs to make a decision based on some condition, if-else is the go-to tool.
Comparison with Other Languages
Python‘s if-else syntax is quite similar to other C-style languages like Java, C++, and JavaScript. The main difference is the use of indentation instead of curly braces to define code blocks.
Here‘s how you might write a simple if-else statement in a few other popular languages:
Java:
if (x > 0) {
System.out.println("Positive");
} else {
System.out.println("Non-positive");
}
C++:
if (x > 0) {
std::cout << "Positive" << std::endl;
} else {
std::cout << "Non-positive" << std::endl;
}
JavaScript:
if (x > 0) {
console.log("Positive");
} else {
console.log("Non-positive");
}
As you can see, the basic structure is very similar across languages. Python‘s use of indentation makes the code a bit cleaner and enforces a consistent style.
Best Practices and Tips
Here are some tips and best practices to keep in mind when working with if-else statements in Python:
- Keep your conditions simple and focused. If you find yourself writing very complex conditions, consider breaking them down into helper variables or functions.
- Avoid deeply nested if statements. If you have more than 2-3 levels of nesting, try to refactor your code using logical operators, helper functions, or polymorphism.
- Use parentheses around conditions if it improves readability, especially for compound conditions with
and
andor
. - Follow the "Flat is better than nested" principle from the Zen of Python. Prefer flat if-elif-else chains over nested if statements when possible.
- Be consistent with your indentation. Most Python style guides recommend using 4 spaces per indentation level.
- Use meaningful names for boolean variables, like
is_valid
orhas_access
. Avoid generic names likeflag
orcheck
. - Consider using a match-case statement (Python 3.10+) for comparing a value against multiple literal patterns.
- If you find yourself repeating the same if-else logic in multiple places, consider refactoring it into a function.
Conclusion
If-else statements are a fundamental tool for controlling the flow of execution in Python programs. They allow you to make decisions based on the values of variables and the results of expressions.
In this article, we‘ve covered the syntax and usage of if, elif, and else, as well as related concepts like logical operators, truthiness, and one-line if-else expressions. We‘ve also looked at some best practices and real-world examples.
Remember, the key to writing effective if-else statements is to keep your conditions simple, your code flat, and your indentation consistent. With these principles in mind, you‘ll be able to write clear, concise, and maintainable Python code.
I hope this article has been helpful in deepening your understanding of if-else statements in Python. Happy coding!