Conditional Statements

✅ Conditionals let your code make decisions. With if, elif, and else, you can control which blocks of code run based on whether a condition is True or False.

1 The if Statement

Runs a block of code only if the condition is True.

semesters = 4
if semesters == 4:
    print("Data Science Master's program is 4 semesters.")  # Data Science Master's program is 4 semesters.
Data Science Master's program is 4 semesters.

2 The else Statement

Use else to run code when the if condition is False.

classes = 1
if classes >= 3:
    print("Full-time student.")
else:
    print("Not a full-time student.")  # Not a full-time student.
Not a full-time student.

3 The elif Statement

Use elif (short for “else if”) to check additional conditions.

classes = 3
if classes > 3:
    print("Overachieving full-time student.")
elif classes == 3:
    print("Full-time student.")  # Full-time student.
else:
    print("Not a full-time student.")
Full-time student.

4 Logical Operators

You can combine conditions using and, or, and not.

gpa = 3.7
has_internship = True
has_research_experience = False
number_of_projects = 6

if gpa > 3.0 and has_internship:
    print("You have good chances of finding a full-time job!")  # You have good chances of finding a full-time job!

if gpa > 3.5 or has_research_experience:
    print("You have good chances of finding a research opportunity!")  # You have good chances of finding a research opportunity!

if not number_of_projects < 5:
    print("You have completed a solid number of projects!")  # You have completed a solid number of projects!
You have good chances of finding a full-time job!
You have good chances of finding a research opportunity!
You have completed a solid number of projects!

5 Nested Conditional Statements

You can nest conditionals inside each other.

gpa = 4.0

if gpa > 3:
    print("Great GPA!")  # Great GPA!
    if gpa % 4.00 == 0:
        print("😲")  # 😲
Great GPA!
😲

6 Truthy and Falsy Values

In conditionals, Python treats certain values as False:

  • False, None, 0, "", [], {}, set()

All other values are truthy.

if "":
    print("Empty string is truthy.")
else:
    print("Empty string is falsy.")  # Empty string is falsy.
Empty string is falsy.
if ['Non-empty']:
    print("Non-empty list is truthy.")  # Non-empty list is truthy.
Non-empty list is truthy.

Common Errors

Some frequent errors encountered when dealing with Conditional Statements in Python.

semesters = 4
if semesters == 4
    print("Missing colon.")
  Cell In[8], line 2
    if semesters == 4
                     ^
SyntaxError: expected ':'
semesters = 4
if semesters = 4:
    print("Using assignment instead of comparison.")
  Cell In[9], line 2
    if semesters = 4:
       ^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?