Skip to content

Simple if-else statement:

x = 5
if x > 0:
    print("x is positive")
else:
    print("x is not positive")
Output: x is positive

If-elif-else statement:

x = 5
if x > 0:
    print("x is positive")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")
Output: x is positive

Nested if-else statement:

x = 5
y = 10
if x > 0:
    if y > 0:
        print("x and y are both positive")
    else:
        print("x is positive, y is not positive")
else:
    print("x is not positive")
Output: x and y are both positive

If-else statement with multiple conditions using and/or:

x = 5
y = 10
if x > 0 and y > 0:
    print("x and y are both positive")
else:
    print("x and/or y are not positive")
Output: x and y are both positive

If-else statement with a list:

numbers = [1, 2, 3, 4, 5]
if 3 in numbers:
    print("3 is in the list")
else:
    print("3 is not in the list")
Output: 3 is in the list

If-else statement with a dictionary:

students = {
    "Alice": 22,
    "Bob": 25,
    "Eve": 26
}
if "Alice" in students:
    print("Alice is a student")
else:
    print("Alice is not a student")
Output: Alice is a student

If-else statement with a while loop:

x = 0
while x < 5:
    if x % 2 == 0:
        print(x)
    x += 1
else:
    print("x is no longer less than 5")
Output: 0, 2, 4, x is no longer less than 5

If-else statement with a for loop:

for x in range(5):
    if x % 2 == 0:
        print(x)
    else:
        break
else:
    print("Loop completed")
Output: 0

If-else statement with a try-except block:

try:
    x = int(input("Enter a number: "))
except ValueError:
    print("That was not a valid number")
else:
    print("The number you entered was", x)

If-else statement with a function:

def is_even(x):
    if x % 2 == 0:
        return True
    else:
        return False

print(is_even(2))  #