Conditionals¶
Booleans¶
Python has boolean values. Booleans can be true or false.
>>> True
True
>>> False
False
Python spells True and False with a capital first letter. Lowercase doesn’t work.
>>> true
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
Booleans use a type of bool:
>>> type(True)
<class 'bool'>
Python has conditionals that return boolean values. Python supports == for “equal” and != for “not equal”.
>>> 0 == 1
False
>>> 0 == 0
True
>>> 0 != 1
True
>>> "a" == "A"
False
>>> "a" == "a"
True
Other comparisons on numbers are just as you’d expect:
>>> 1 > 0
True
>>> 2 >= 3
False
>>> -1<0
True
>>> .5 <= 1
True
One thing you might not expect is the ability to chain comparisons, unlike languages such as C++ or Java:
>>> x = 5
>>> y = 4
>>> 1 < y < x
True
Comparisons also work for strings and a number of other types:
>>> "a" < "b"
True
>>> "apple" < "animal"
False
>>> "Apple" < "apple"
True
>>> "Apple" < "apple"
Another boolean operator is “in” which can be used to check for containment:
>>> "H" in "Hello"
True
>>> "lo" in "Hello"
True
>>> "x" in "Hello"
False
If Statements¶
Python has “if” statements that allow us to execute code conditionally:
>>> x = 6
>>> y = 5
>>> if x > y:
... print("x is greater than y!")
...
x is greater than y!
Whenever some code will be conditionally executed, the line defining the condition is terminated with a colon. This tells Python that a block is to follow. The REPL signals its understanding with the three dots prompt. In Python, whitespace at the beginning of a line is significant. This whitespace indicates that the line is part of the block of code that is executed when the if statement is true. The convention is to use 4 spaces per indentation level, so we type 4 spaces before typing the print statement. After the print statement, we enter a blank line to tell the REPL that our block is finished. This convention is used throughout the Python language.
We can also have else statements to execute code when our condition is false:
>>> x = 1
>>> y = 100
>>> if x > y:
... print("x is greater than y!")
... else:
... print("y is greater than x!")
...
y is greater than x!
Python also has a special “elif” statement for chaining a number of conditionals together.
>>> temperature = 80
>>> if temperature < 65:
... print("Too cold")
... elif temperature > 75:
... print("Too hot")
... else:
... print("Nice and cozy")
...
Too hot
Python has boolean logical operators and and or:
>>> 1 < 2 and "x" in "abc"
False
>>> 1 < 2 or "x" in "abc"
True
In addition to and and or, Python also has a not operator for negation.
>>> not (1 < 2)
False
>>> not True
False
>>> not False
True
>>> "a" not in "abcde"
False
Conditional Exercises¶
Temperature Conditionals¶
Write some code that:
- sets a temperature variable
- prints out “Nice and cozy” if the temperature is between 65 and 75
- prints out “Too extreme” if the temperature is outside that range
Not a Robot¶
Write some code that:
- Sets a variable
sentenceto a sentence - Prints “Hi! I’m not a robot.” if the sentence includes the word “hello”
- Prints “Sure, why not” if the sentence includes the phrase “can I”
- Prints “I’m sorry, could you repeat that?” otherwise
Line Ordering¶
Write some code that:
- Sets a
my_namevariable equal to your first name - Sets a
their_namevariable to the name of one of the people sitting next to you - Prints “Before me in line” if their name comes before yours alphabetically
- Prints “After me in line” if their name comes after yours alphabetically
- Prints “We have the same name!” if your name is the same
Less, Greater, Equal¶
Write some code that:
- Creates two variables:
- sister_age: pick your favorite number from 0 to 100
- brother_age: pick your second favorite number in that range
- Write an if statement that prints out one of these three statements as appropriate:
- “Sister is older”: printed when sister_age is greater than brother_age
- “Brother is older”: printed when brother_age is greater than sister_age
- “Sister and brother are twins”: printed when sister_age is equal to brother_age
De Morgan¶
Rewrite this if statement to use or instead of and:
>>> user = "taylor"
>>> level = 2
>>> if user != "root" and level < 3:
... print("Permission denied")
...
Permission denied
Truthiness¶
Booleans are not the only value that can go in an if statement condition. Python has a concept of truthiness that is greater than just True and False.
Let’s try out truthiness on strings.
>>> word = "bird"
>>> if word:
... print("word is truthy")
...
word is truthy
>>> word = ""
>>> if word:
... print("word is truthy")
...
Strings evaluate as truthy if they contain text. They are falsey if they do not.
>>> number = 1000
>>> if number:
... print("number is truthy")
...
number is truthy
>>> number = 0
>>> if number:
... print("number is truthy")
...
Numbers are truthy if they are non-zero and falsey if they are zero.
Truthiness is not the same thing as boolean True or False. For example, a number that is truthy is not True. Truthiness can be determined by using the bool constructor to convert a value to a boolean:
>>> bool("")
False
>>> bool("hello")
True
>>> bool(0)
False
>>> bool(-1)
True
None¶
Sometimes you want to represent purposeful emptiness.
Let’s say we want to represent that we have a name variable representing the user’s name but we don’t actually have the user’s name yet.
We could do this:
>>> name = ""
>>> name
''
Are there any problems with this?
Problem: how can we tell whether the user entered a blank (empty) name or whether they were never even asked for a name?
Some languages have a concept of “null” or “undefined”. In Python we call this None:
>>> name = None
>>> name
>>>
None represents nothingness. If you think of an empty string or the number 0 as being like air, then None is like a vacuum.
None is falsey:
>>> name = None
>>> if name:
... print("there is a name")
...
None has a special NoneType:
>>> type(None)
<class 'NoneType'>
Sometimes you will want to determine whether something is exactly equal to None. You can use is for this:
>>> meaning = None
>>> if meaning is None:
... print("there is no meaning")
...
there is no meaning
The is operator should be used when comparing singletons. None, True, and False are all singletons. That means there is exactly one copy of each of these objects floating around in your Python program.
You can also use is to check for equality to True or False but this is often considered poor form in Python because relying on truthiness is typically preferred:
>>> meaning = "be good"
>>> if meaning is True:
... print("meaning is true")
... elif meaning:
... print("meaning is truthy")
...
meaning is truthy