Any non-trivial program needs to make decisions. To do this, we use conditionals—the fundamental `if`, `but`, and `maybe` of programming logic. Conditionals allow your code to ask questions and perform different actions based on the answers, making your applications dynamic and responsive.
Table of Contents
💻 The Basic `if-else` Statement
The core of conditional logic is the if-else statement. It poses a question, and your program follows one of two paths depending on the answer.
x = 5
if x == 10:
print("X is ten")
else:
print("X is NOT ten")
Key points to notice:
- The condition:
if x == 10:checks if the value of `x` is equal to 10. The double equals sign `==` is crucial; it’s a comparison, not an assignment. - The `else` block: This code runs only if the `if` condition is false.
- Indentation: In Python, the code to be executed within the `if` or `else` block must be indented.
💻 Comparison Operators and `elif`
You can ask more than just “is it equal?”. Python provides a full suite of comparison operators:
>: Greater than<: Less than>=: Greater than or equal to<=: Less than or equal to!=: Not equal to
When you have more than two possible paths, you can use the elif (else if) statement to chain multiple checks together:
if x == 1:
puts("One")
elif x == 2:
puts("Two")
else:
puts("Something else")
This structure is much cleaner than nesting multiple `if-else` statements inside each other.
More Topics
- Python Project Guide: NumPy & SciPy: For Science!
- Python Project Guide: Times, Dates & Numbers
- Python Project Guide: Making Scripts
- Python Project Guide: Build an FTP Client & Server
- Python Project Guide: Using Functions in Python 3
- Python Project Guide: How to Get Started with Python 3
- Coding Concepts Explained: Avoid Common Coding Mistakes

