Expedia Code Academy
We have seen two types of data already:
A really useful data type is a Boolean
It can represent two values - True or False
my_boolean = 5 > 2
print(my_boolean)
another_boolean = 3.14 < -3
print(another_boolean)
We can also test for equality using ==
first_number = 12 / 3
second_number = 2 * 2
are_equal = first_number == second_number
print(are_equal)
We can also do "less-than-or-equal" and "greater-than-or-equal" comparisons:
2 <= 5 # but not 2 =< 5, order matters!
242 >= 242 # but not 242 => 2
Think of the program powering Hotels.com. A user can only get exclusive deals if they're a Silver Member...
This means we need to change the price depending on whether this condition is True or not!
if x > 0:
print('x is positive')
Syntax is important! You'll need these:
if x > 0:
print('x is positive')
print('a message that always gets printed')
if x > 0:
print('x is positive')
print('a message that gets printed only when x is positive')
if x > 0:
print('x is positive')
else:
print('x is negative')
The code under else gets executed when the if boolean is False.
They are mutually exclusive!
Sometimes there are more than two possibilities, so you need more than True/False or if/else.
if x > 0:
print('x is positive')
elif x == 0:
print('x is equal to 0')
else:
print('x is negative')
elif is an abbreviation of “else if”
Please note that only one branch will be executed, and priority starts from the top!
How would we write code to print all numbers between 10 and 0?
What about 100? Or 1000?
number = 10
while number > 0:
print(number)
number = number - 1
print("Blast Off!")
number = 10
while number > 0:
print(number)
# number = number - 1
print("Blast Off!")
(⭐️) 2c. print numbers up to 10 (including 0 and 10)
(⭐️⭐️) 2d. Program Bob! See here for instructions.
# Use `and` to use multiple True conditions at once
# You need to use the `number` variable in each boolean statement
if number > 5 and number < 10:
print('This number is between 6 and 9')
# Use `or` to only require one True condition
if there_is_free_food or i_am_hungry:
print('Time to eat!')