Conditionals

An Expected Failure

Let’s try something new that we’ve never done before and don’t yet know how to do.

Copy-paste this code into a file called grade.py (either overwrite your existing grade.py program or make a new file with a different name):

percent = float(input("Grade: "))

if 90 < percent:
    print('A')

# TODO Handle B: 80 and up

# TODO Handle C: 70 and up

# TODO Handle D: 60 and up

# TODO Handle F: Below 60

Now try to modify this program to print out a letter grade for the given percent.

For example entering 95 currently results in A being printed:

$ python grade.py
Grade: 95
A

Make it so B, C, D, and F are printed at appropriate times as well.

For example, entering 76 should result in C being printed out:

$ python grade.py
Grade: 76
C

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

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
>>> "a" in "abcde"
True

There is also a special two-word operator not in, the boolean reverse of in:

>>> "a" not in "abcde"
False
>>> "x" not in "abcde"
True

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.

>>> year = 2020
>>> if year == 2019:
...     print("Time to convert to Python 3!")
... elif year > 2019:
...     print("Python 2 is dead, long live Python 3!")
... else:
...     print("Python 2 is still OK!")
...
Python 2 is dead, long live Python 3!

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

Note

Python’s if statements do a bit more than a True/False check. See Truthiness, which we will discuss later.

Conditional Exercises

Hint

If you’re stuck for more than a few minutes, some of these links might be helpful for some of the exercises below:

Writing code at the Python REPL can be tedious at times, but it’s very handy to know how to work in the REPL. See if you can write these code blocks correctly in the Python REPL.

Temperature Conditionals

Write some code that:

  1. sets a temperature variable

  2. prints out “Nice and cozy” if the temperature is between 65 and 75

  3. prints out “Too extreme” if the temperature is outside that range

Not a Robot

Write some code that:

  1. Sets a variable sentence to a sentence

  2. Prints “Hi! I’m not a robot.” if the sentence includes the word “hello”

  3. Prints “Sure, why not” if the sentence includes the phrase “can I”

  4. Prints “I’m sorry, could you repeat that?” otherwise

Alphabetical Ordering

Write some code that:

  1. Sets a my_name variable equal to your first name

  2. Sets a their_name variable to the name of one of the people sitting next to you

  3. Prints “Before me in line” if their name comes before yours alphabetically

  4. Prints “After me in line” if their name comes after yours alphabetically

  5. Prints “We have the same name!” if your name is the same

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