Python If Statements – Making Decisions in Your Code

If statements allow your Python programs to make decisions based on different conditions. They’re like the decision-making brain of your code.

Basic If Statement

The simplest form checks if a condition is true:

age = 18
if age >= 18:
    print("You can vote!")

If-Else Statements

Handle both true and false conditions:

temperature = 75
if temperature > 80:
    print("It's hot outside!")
else:
    print("It's nice weather!")

If-Elif-Else Statements

Check multiple conditions in sequence:

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(f"Your grade is: {grade}")

Comparison Operators

Use these operators to compare values:

==  # Equal to
!=  # Not equal to
>   # Greater than
<   # Less than
>=  # Greater than or equal to
<=  # Less than or equal to

Logical Operators

Combine multiple conditions:

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive!")

if age < 16 or not has_license:
    print("You cannot drive yet.")

Remember that Python uses indentation to group code blocks, so make sure your code inside if statements is properly indented.

Author

  • Mohammad Golam Dostogir, Software Engineer specializing in Python, Django, and AI solutions. Active contributor to open-source projects and tech communities, with experience delivering applications for global companies.
    GitHub

    View all posts
Index