PYCS 04 - Boolean and If Statements - Colaboratory
PYCS 04 - Boolean and If Statements - Colaboratory
This Python Notebook is part of a sequence authored by Timothy R James - feel free to modify, copy,
share, or use for your own purposes.
In this Notebook file, we'll talk about a new data type - the boolean type - and see how we can use
these in if statements to make decisions.
Boolean values are pretty simple. They can only have the values True and False . We often use
Boolean values with comparison operators. Some common comparison operators you might see:
You can try some of these operators by running the code block below. See if you can guess the
output before you run it.
print(3 > 5)
print(12 / 3 != 4)
Note that in Python, we use capital letters to start True and False - this is different from many
other programming languages.
m = True
n = True
p = False # we don't like to use "o" because it's easily mistaken for zero!
https://colab.research.google.com/drive/1-iy-6J8SJbTVyYB1N_k9YipSbqcZUoKN?usp=sharing#scrollTo=cs_JQOFrG4WV&printMode=true 1/8
1/10/23, 1:16 PM PYCS 04 - Boolean and If Statements - Colaboratory
q = False
print(n)
It's pretty common to see comparison operators - we'll use them for a few purposes in the next
several lessons. You can also create variables and assign them to boolean comparisons.
m = 5 > 3
n = 3 <= 5
print(m)
print(n)
Note that boolean values have the same problems as float values and int values when we try to
concatenate them with strings. We will need to convert them before they're concatenated.
m = True
n = False
# The line below is commented because it won't work.
# s = 'Our boolean values are ' + m + ' and ' + n + '.'
s = 'Our boolean values are ' + str(m) + ' and ' + str(n) + '.'
print(s)
s = '%s is a boolean value.' % True
print(s)
In addition to the comparison operators, you can use and as well as or to combine Boolean
comparison.
https://colab.research.google.com/drive/1-iy-6J8SJbTVyYB1N_k9YipSbqcZUoKN?usp=sharing#scrollTo=cs_JQOFrG4WV&printMode=true 2/8
1/10/23, 1:16 PM PYCS 04 - Boolean and If Statements - Colaboratory
m = True
n = True
p = False
q = False
print(m and p) # p is False, so this will be False
print(m or p) # m is True, so this will be True
print(m and n) # both are True, so this will be True
print(p or q) # both are False, so this will be False
There's also not , for negation. This just makes True false, and False true.
print(not q)
print(m or not p)
print(m and not n)
Input
Before we go farther, it's important to note that we can use the built-in Python input function to
collect input from the user. This will allow us to make our code here more interactive.
The input function prompts the user, and then returns whatever the user enters as a string. Try it
yourself below.
some_input = input("Type anything.")
print("You typed: %s" % some_input)
If Statements
Now that we know about boolean values and we can collect input from a user, we can write
programs that are a bit more interesting - instead of just entering a bunch of numbers and running
the same program over and over again.
https://colab.research.google.com/drive/1-iy-6J8SJbTVyYB1N_k9YipSbqcZUoKN?usp=sharing#scrollTo=cs_JQOFrG4WV&printMode=true 3/8
1/10/23, 1:16 PM PYCS 04 - Boolean and If Statements - Colaboratory
condition is true.
Unlike in Java, JavaScript, C#, and C++, in Python we typically see if statements without
parentheses. Note that the body of your if statement requires indentation - that's how Python
knows it's part of that block of execution.
something = input('Type something.')
if something != "something":
# note the use of whitespace here; we're indenting these lines 4 spaces.
# we say this code is *in* the if-block, or in the body of the if statement.
print("You didn't type 'something'!")
In the example above, we're using 4 spaces. You can also use tabs or different numbers of spaces,
but the important thing is to be consistent. Otherwise it can become really difficult to understand
what your code is doing (since tabs and spaces usually look the same). Basically: If you use tabs,
always use tabs. If you use 4 spaces, always use 4 spaces. If you use 2 spaces, always use 2
spaces.
Personally, I like 4 spaces because it makes it easier to read and distinguish your different blocks of
code.
Try changing the next example to see what happens when you mix up the number of spaces in your
code.
something = input('Type something.')
if something != "something":
# try adding one more space to the indentation of the next line...
print("You didn't type 'something'!")
# ...and try removing a space from the indentation of the next line
print('This indentation is mixed up.')
Here's another simple example using if ; note that the last line - print('This is the end of the
program.') - it always runs, regardless of the condition in the if statement.
some_input = input('Enter a number.')
# note - input will give us a string, and we need to convert that to an int.
num = int(some_input)
if num == 0:
print("That number is definitely 0.")
# this code is not in the if-block - it's outside the body of the if statement.
print('This is the end of the program.')
https://colab.research.google.com/drive/1-iy-6J8SJbTVyYB1N_k9YipSbqcZUoKN?usp=sharing#scrollTo=cs_JQOFrG4WV&printMode=true 4/8
1/10/23, 1:16 PM PYCS 04 - Boolean and If Statements - Colaboratory
p ( p g )
Nesting If Statements
Note that if statements can be easily nested (this means we can put an if statement inside another
if statement); you just need to make sure you're indenting properly and that your code lines up
correctly.
some_input = input('Enter a number.')
num = int(some_input)
if num > 1000:
print('That\'s a really big number!.')
if num > 10000:
# this line is indented 8 spaces.
print('That\'s a really really big number!')
# To continue this level of execution, just remove the indent.
print('This is part of the first if statement; if num > 1000.')
Notice in the code above that we are inserting single quotes into a string that starts and ends with
single quotes; we do that with an escape character. Basically, when we enter a backslash followed
by a single quote ( \' ) it tells Python that we're not using the single quote to end the string; this
allows us to insert single quotes into a string that we start and end with single quotes, and it allows
us to insert double quotes (using \" ) into a string that we start and end with double quotes.
It's also possible to write code with a nested if statement that could never execute, like this.
color = input('What is your favorite color?')
if color == 'green':
print('I had a feeling you would pick green.')
if color == 'purple':
# This line can't execute, because color won't be 'green' *AND* 'purple'
print('purple is OK.')
If we don't want to have that unreachable code, it would probably be better to rewrite it like this:
color = input('What is your favorite color?')
if color == 'green':
print('I had a feeling you would pick green ')
https://colab.research.google.com/drive/1-iy-6J8SJbTVyYB1N_k9YipSbqcZUoKN?usp=sharing#scrollTo=cs_JQOFrG4WV&printMode=true 5/8
1/10/23, 1:16 PM PYCS 04 - Boolean and If Statements - Colaboratory
print( I had a feeling you would pick green. )
if color == 'purple':
print('purple is OK.')
We may have code that may or may not execute a nested if statement.
an_input = input('Enter a number')
num = int(an_input)
if num < 100:
print('That number is less than 100.')
if num < 50:
print('That number is also less than 50.')
if num < 75:
print('That number is less than 75, too.')
One challenging situation that can happen is "arrow code" - when you keep nesting if statements,
and your if statements keep moving inward and inward and inward. Generally this is a bad practice
and can be refactored using functions, better conditional evaluation, or more modular code (we'll
cover all of these in the next few lessons).
# note - we can combine conversion and input in one statement, like this.
num = float(input('Hey, give me a number!'))
# % is the 'modulo' operator for numbers; it gives us the remainder of division.
if num % 2 == 0:
print("The number is even.")
if num > 0:
print("The number is positive.")
if int(num) == num:
print("The number is an integer.")
if num > 7:
print("The number is larger than one octal digit.")
if num > 15:
print("The number is larger than one hexadecmial digit.")
if num > 100:
print("The number is greater than 100.")
if num > 1000000:
print("The number is greater than a million.")
We can use if statements to do something, and another if statement to also do the opposite, like
what you see below.
num = int(input('Enter a number.'))
if num % 2 == 0:
https://colab.research.google.com/drive/1-iy-6J8SJbTVyYB1N_k9YipSbqcZUoKN?usp=sharing#scrollTo=cs_JQOFrG4WV&printMode=true 6/8
1/10/23, 1:16 PM PYCS 04 - Boolean and If Statements - Colaboratory
print('That number is even.')
if num % 2 != 0:
print('That number is odd.')
That could lead to problems though - it's duplicated code, which is usually not a great indicator that
we're doing things the best way. It also could be error-prone; what if we make a mistake and don't
evaluate the same thing? This example is simple, but what if our if statements are more complex?
Fortunately, Python gives us a way to run one set of statements if what we evaluate is True , and a
different set of statements if it is False . We'll look at this in the next lesson.
Try It!
The code below checks to see if an integer number is divisible by prime numbers less than 10 (2, 3,
5, and 7). Add additional if statements to see if the integer number is divisible by prime numbers
less than 20 (11, 13, 17, and 19).
number = int(input('Please enter an integer number.'))
if number % 2 == 0:
print('That number is divisible by 2.')
if number % 3 == 0:
print('That number is divisible by 3.')
if number % 5 == 0:
print('That number is divisible by 5.')
if number % 7 == 0:
print('That number is divisible by 7.')
# add your code.
Try retrieving the user's input, evaluating it with an if statement, and telling the user if they guessed
the number properly; give them a message telling them they guessed incorrectly if they don't guess
7.
correct_number = 7
print('Guess a number between 1 and 10.')
How would you write code that can tell a user if a number is odd or even?
https://colab.research.google.com/drive/1-iy-6J8SJbTVyYB1N_k9YipSbqcZUoKN?usp=sharing#scrollTo=cs_JQOFrG4WV&printMode=true 7/8
1/10/23, 1:16 PM PYCS 04 - Boolean and If Statements - Colaboratory
# your code here
https://colab.research.google.com/drive/1-iy-6J8SJbTVyYB1N_k9YipSbqcZUoKN?usp=sharing#scrollTo=cs_JQOFrG4WV&printMode=true 8/8