In [ ]:
cleaned_room = True
took_out_trash = False
print(cleaned_room)
print(type(took_out_trash))
You can compare values together and get a boolean result
Operator | Meaning |
---|---|
x == y | x equal to y |
x != y | x not equal to y |
x > y | x greater than y |
x < y | x less than y |
x >= y | x greater than or equal to y |
x <= y | x less than or equal to y |
x is y | x is the same as y |
x is not y | x is not the same as y |
By using the operators in an expression the result evaluates to a boolean. x and y can be any type of value
In [ ]:
print(5 == 6)
In [ ]:
print("Coke" != "Pepsi")
In [ ]:
# You can compare to variables too
allowance = 5
print(5 >= allowance)
In [ ]:
print(allowance is True)
In [ ]:
We can write programs that change their behavior depending on the conditions.
We use an if statement to run a block of code if a condition is true. It won't run if the condition is false.
if (condition):
code_to_execute # if condition is true
In python indentation matters. The code to execute must be indented (4 spaces is best, though I like tabs) more than the if condition.
In [ ]:
# cleaned_room is true
if cleaned_room:
print("Good kid! You can watch TV.")
# took_out_trash if false
if took_out_trash:
print("Thank you!")
print(took_out_trash)
You can include more than one statement in the block of code in the if statement. You can tell python that this code should be part of the if statement by indenting it. This is called a 'block' of code
if (condition):
statement1
statement2
statement3
You can tell python that the statement is not part of the if block by dedenting it to the original level
if (condition):
statement1
statement2
statement3 # statement3 will run even if condition is false
In [ ]:
# cleaned_room is true
if cleaned_room:
print("Good job! You can watch TV.")
print("Or play outside")
In [ ]:
# took_out_trash is false
if took_out_trash:
print("Thank you!")
print("You are a good helper")
print("It is time for lunch")
In alternative execution, there are two possibilities. One that happens if the condition is true, and one that happens if it is false. It is not possible to have both execute.
You use if/else syntax
if (condition):
code_runs_if_true
else:
code_runs_if_false
Again, note the colons and spacing. These are necessary in python.
In [ ]:
candies_taken = 4
if candies_taken < 3:
print('Enjoy!')
else:
print('Put some back')
Chained conditionals allow you to check several conditions. Only one block of code will ever run, though.
To run a chained conditional, you use if/elif/else syntax. You can use as many elifs as you want.
if (condition1):
run_this_code1
elif (condition2):
run_this_code2
elif (condition3):
run_this_code3
else:
run_this_code4
You are not required to have an else block.
if (condition1):
run_this_code1
elif (condition2):
run_this_code2
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.
In [ ]:
did_homework = True
took_out_trash = True
cleaned_room = False
allowance = 0
if cleaned_room:
allowance = 10
elif took_out_trash:
allowance = 5
elif did_homework:
allowance = 4
else:
allowance = 2
print(allowance)
In [ ]:
and Truth table (only true if both values are true)
val1 | val2 | val1 and val2 |
---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
or Truth table (true if at least 1 value is true)
val1 | val2 | val1 or val2 |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
not Truth table (the opposite of the value)
val1 | not val1 |
---|---|
true | false |
false | true |
In [ ]:
print(True and True)
print(False or True)
print(not False)
You can use the logical operators in if statements
In [ ]:
cleaned_room = True
took_out_trash = False
if cleaned_room and took_out_trash:
print("Let's go to Chuck-E-Cheese's.")
else:
print("Get to work!")
In [ ]:
if not did_homework:
print("You're going to get a bad grade.")
In [ ]:
In [ ]:
allowance = 5
if allowance > 2:
if allowance >= 8:
print("Buy toys!")
else:
print("Buy candy!")
else:
print("Save it until I have enough to buy something good.")
In [ ]:
try:
print("Before")
y = 5/0
print("After")
except:
print("I'm sorry, the universe doesn't work that way...")
A finally
statment can be added to the try/except block and it executes at the end whether or not there is an error. This can be useful for cleaning up resources.
try:
code
except:
code_runs_if_error
finally:
code runs at end with or without error
In [ ]:
try:
print("Before")
y = 5/0
print("After")
except:
print("I'm sorry, the universe doesn't work that way...")
finally:
print("Even if you break python, you still have to do your chores")
This can be useful when evaluating a user's input, to make sure it is what you expected.
In [ ]:
inp = input('Enter Fahrenheit Temperature:')
try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
except:
print('Please enter a number')
In [ ]:
Python (and most other languages) are very lazy about logical expressions. As soon as it knows the value of the whole expression, it stops evaluating the expression.
if (condition1 and condition2):
run_code
In the above example, if condition1 is false then condition2 is never evaluated.
In [ ]:
if (1 < 2) or (5/0):
print("How did we do that?")
We are going to build an application that recommends a car based on the user's budget.
In [ ]: