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')
else:
    print('x is zero, neither positive or ngegative')

Output:

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')
else:
    print('You are an alien.Maybe NASA loves you')

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

guest
0 Comments
Inline Feedbacks
View all comments

Related Articles

0
Would love your thoughts, please comment.x
()
x