Python if/else/elif examples

June 20, 2020 Goodman Loading... Post a comment

A few examples of how to use if/else/elif statements in Python.

Important notes:

  • Unlike other programming languages, Python doesn’t use brackets to separate block of code execution statements. Instead, it uses whitespace.
  • The keyword ‘elif’ is short for ‘else if’.
  • There can be zero, one or more “elif” parts, and the “else” part is optional.

Example 1

x = 1
# Replace 1 with whatever number you want

if x > 0:
    print('x is a positive number')
elif x < 0:
    print('x is a negative number')
    print('x is zero, neither positive or ngegative')


x is a positive number

Example 2

age = int(input("Please enter your age: "))

if(age < 0):
    print('The age you entered is invalid')
elif(age < 3):
    print('You are a baby')
elif(age < 16):
    print('You are a child')
elif(age < 35):
    print('You are a young adult')
elif(age < 60):
    print('You are a middle-aged adults')
elif(age < 250):
    print('You are an old person')
    print('You are an alien.Maybe NASA loves you')

Execute the code, enter your age, hit “Enter” then check the output.

Inline Feedbacks
View all comments

Related Articles

Would love your thoughts, please comment.x