Python if/else/elif examples
A few examples of how to use if/else/elif statements in Python.
- 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.
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')
x is a positive number
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.