x = 5
if x < 10:
# Your code here# As many lines as you need# Continue unconditional code here
- This will run the indented code if the condition is true
- To continue code that is not conditional afterwards, just don't put an indent for the new code
Else statment:
x = 15
if x < 5:
# Your code here
else:
# Code here will run when condition isn't met
- This allows for an alternative action
Else If:
x = 30
if x < 10:
# Your code here
elif x < 50:
# Your code here
- Elif statements allow for alternative actions to be taken in different conditions
- The code will run for only the first condition that is met
- You can put many elif statements, and an else condition after all of them
Types of Conditions:
True not False # "not" makes it opposite3 == 3 # == checks if values are equal3 != 4 # != checks if not equal3 < 4 # < checks if value on left is less than value on right3 > 2 # > checks if value on left is greater than value on right3 <= 4 # <= means less than or equal to3 >= 2 # >= means greater than or equal tonot (3 == 4) # not () will negate the value within parenthesis3 == 9 or 3 < 7 # True if the conditions on EITHER side are true3 > 2 and 3 < 5 # True if the conditions on BOTH sides of the "and" are true1 | False # | means bitwise Or (treats True and False as 1 and 0)1 & True # & means bitwise And (treats True and False as 1 and 0)3 > 2 and (3 > 5 or 6 > 2) # Complex combinations can be made
- All of the above examples have the value of true (or 1 in the case of bitwise operations)
Challenge
Write a program that stores an age as a variable. If it is less than 18, have it display "Must be 18 to pass".
If it is an invalid value (negative), have it say "Invalid input", otherwise have it say "Welcome".
Run it with different values for the age.