» Quick Introduction to Python » 1. Basics » 1.4 Condition Control

If Statement

Single Condition

a, b = 5, 8
if a < b:
    print("smaller")

Compound Condition

In Python, you can use logical operators to join mulitple conditions into a single compound one.

Below code shows a compound condition joined by and logical operator.

a, b, c = 5, 8, 10
if a < b and a < c:
    print(a, "is less than", b "and", c)

Nested If Statement

a = 5
if a > 0:
    if a > 3:
        print(a, "is greater than 3")
    if a % 2 == 1:
        print(a, "is odd")

If Else Statement

a = 5
if a % 2 == 0:
    print(a, "is even")
else:
    print(a, "is odd")

Elif Statement

year = 1998
if year < 1980:
    print("old times")
elif year < 1990:
    print("80s")
elif year < 2000:
    print("90s")
else:
    print("21st century")

Or Logical Operator

animal = 'cat'
if animal == 'cat' or animal == 'dog':
    print("Pet")

And Logical Operator

year = 2024
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print(f"{year} is a leap year")

Not Logical Operator

lucky = True
if not lucky:
    print("Don't buy lottery")

Ternary

Python Ternary operator selects one of the two values based on a condition. Similar to ?: operator in C-like languages.

a, b = 5, 8
max_num = a if a > b else b
print(f"max: {max_num}")

Code Challenge

Try to modify the code provided in the editor to make it print It's weekday..

Loading...
> code result goes here
Prev
Next