Lab 01 - Booleans, Conditionals, & Console I/O

Due by 11:59pm on January 14, 2025

In this lab you will work on two things. Like every lab from here forward, you will have the opportunity to practice working with the Python language and class concepts discussed in lecture. This lab will also walk you through the procedure for submitting your code assignments to Gradescope.

Reminder

With this lab and every assignment in the class, you should read through the entire assignment before you start doing any coding.

Often many questions students have about the assignments are in the instructions but we find that they just try to dive in without reading. If you go to a TA for help and the answer is in the instructions, they will probably just refer you to the assignment to find the solution.

Do yourself a favor and always completely read the assignment first.

Working together

In your lab sections, it is encouraged and expected that you will work together with other students to come up with solutions to the problems. Talk with one another about what is working and what doesn’t. Discuss why you chose the solution you did. Find out how others are thinking about the problem and share your ideas. Make friends.

One of the most important things you can do while in school is build a network of peers and friends that can support you and rely on you for support as well. They don’t need to be in your major. The lab sections provide a way for you to meet and work with others and start to build those connections.

Additionally, you can use this (and every) lab as a way to try out pair programming. Check out the pair programming page.

Starter Files

After you’ve read through the entire assignment, come back here and download lab01.zip. Inside the archive, you will find starter files for the questions in this lab. Let’s get going.

Logistics Review

This section is just a quick reminder on how to actually run your python code and run the tests. Feel free to skip to the next section: Topics Review if you’re already comfortable with these topics.

Using Python

When running a Python file, you can use options on the command line to inspect your code further. Here are a few that will come in handy. If you want to learn more about other Python command-line options, take a look at the documentation.

  • Using no command-line options will run the code in the file you provide and return you to the command line. For example, if we want to run lab01.py this way, we would write in the terminal:

    python3 lab01.py
  • -i: The -i option runs your Python script, then opens an interactive session. In an interactive session, you run Python code line by line and get immediate feedback instead of running an entire file all at once. To exit, type exit() into the interpreter prompt. You can also use the keyboard shortcut Ctrl-D on Linux/Mac machines or Ctrl-Z Enter on Windows.

    If you edit the Python file while running it interactively, you will need to exit and restart the interpreter in order for those changes to take effect.

    Here’s how we can run lab01.py interactively:

    python3 -i lab01.py
  • -m doctest: Runs doctests in a particular file. Doctests are surrounded by triple quotes (""") within functions.

    Each test in the file consists of >>> followed by some Python code and the expected output (though the >>> are not seen in the output of the doctest command). We’ll talk more about these types of tests in a future lecture, but for now, you can run the ones we give you to verify that your code is working.

    To run doctests for lab01.py, we can run:

    python3 -m doctest lab01.py

Topics Review

Consult this section if you need a refresher on the material for this lab. It’s okay to skip directly to the questions and refer back here should you get stuck.

The topics in this section are all material you should be familiar with from your prior programming experiences. This section is just a quick overview of the Python syntax for all of these topics. If any of the topics here are unfamiliar, or you feel uncomfortable with them, you may consider switching to the CS 110, Introduction to Programming class.

  • Basic Math
  • Booleans and Conditional Expressions
  • Console Input and Output
  • Error Messages

Addition, Subtraction, and Multiplication

There really shouldn’t be anything surprising here as these work the same as they do in most programming languages.

  • a + b - adds a & b
  • a - b - subtracts b from a
  • a * b - muliplies a & b - the asterisk (*) is the multiplication operator in most languages.

Division, Floor Div, and Modulo

Division is a little trickier. Let’s compare the different division-related operators in Python 3:

True Division: /
(decimal division)
Floor Division: //
(integer division)
Modulo: %
(remainder)
>>> 1 / 5
0.2

>>> 25 / 4
6.25

>>> 4 / 2
2.0

>>> 5 / 0
ZeroDivisionError
>>> 1 // 5
0

>>> 25 // 4
6

>>> 4 // 2
2

>>> 5 // 0
ZeroDivisionError
>>> 1 % 5
1

>>> 25 % 4
1

>>> 4 % 2
0

By default the division operator (/) does floating point division returning a decimal value. To do integer division, (returning the quotient without any fractional part) we use the floor division operator (//). The modulus operator (%) return the remainder that is left after doing the integer division.

Notice that Python outputs ZeroDivisionError for certain cases. We will go over this later in this lab under Error Messages.

One useful technique involving the % operator is to check whether a number x is divisible by another number y:

x % y == 0

For example, in order to check if x is an even number:

>>> x = 1234 + 5678 * 9
>>> x % 2 == 0
True

Boolean Operators

Python supports three boolean operators: and, or, and not:

>>> a = 4
>>> a < 2 and a > 0
False
>>> a < 2 or a > 0
True
>>> not (a > 0)
False
  • and evaluates to True only if both operands evaluate to True. If at least one operand is False, then and evaluates to False.
  • or evaluates to True if at least one operand evaluates to True. If both operands are False, then or evaluates to False.
  • not evaluates to True if its operand evaluates to False. It evaluates to False if its operand evaluates to True.

What do you think the following expression evaluates to? Try it out in the Python interpreter.

>>> True and not False or not True and False

It is difficult to read complex expressions, like the one above, and understand how a program will behave. Using parentheses can make your code easier to understand. Python interprets that expression in the following way:

>>> (True and (not False)) or ((not True) and False)

This is because boolean operators, like arithmetic operators, have an order of operation:

  • not has the highest priority
  • and
  • or has the lowest priority

Truthy and Falsey Values: It turns out and and or work on more than just booleans (True, False). Python values such as 0, None, '' (the empty string), and [] (the empty list) are considered false values. All other values are considered true values.

Short Circuiting

What do you think will happen if we type the following into Python?

1 / 0

Try it out in Python! You should see a ZeroDivisionError. But what about this expression?

True or 1 / 0

Consider this expression as well.

True and 0 and 1 / 0

The first one evaluates to True and the second will evaluate to 0, because Python’s and and or operators short-circuit. That is, they don’t necessarily evaluate every operand.

OperatorChecks if:Evaluates from left to right up to:Example
andAll values are trueThe first false valueFalse and 1 / 0 evaluates to False
orAt least one value is trueThe first true valueTrue or 1 / 0 evaluates to True

Short-circuiting happens when the operator reaches an operand that allows them to make a conclusion about the expression. For example, and will short-circuit as soon as it reaches the first false value because it then knows that not all the values are true.

If and and or do not short-circuit, they just return the last value; another way to remember this is that and and or always return the last thing they evaluate, whether they short circuit or not. Keep in mind that and and or don’t always return booleans when using values other than True and False.

Try doing Q1: WWPD: Veritasiness

If Statements

Conditional statements let programs execute different lines of code depending on certain conditions. Let’s review the if-elif-else syntax. The general form looks like this.

if <conditional expression>:
    <suite of statements>
elif <conditional expression>:
    <suite of statements>
else:
    <suite of statements>
  • The elif (short for ‘else if’) and else clauses are optional, and you can have any number of elif clauses, but only 1 else.
  • A conditional expression is an expression that evaluates to either a truthy value (True, a non-zero integer, etc.) or a falsy value (False, 0, None, “”, [], etc.).
  • Only the first if/elif expression that evaluates to a truthy value will execute its indented code block.
  • If none of the conditional expressions evaluate to a true value, then the else suite is executed.

You can review the syntax of if statements further in Section 1.5.4 of Composing Programs.

Tip

We sometimes see code that looks like this:

if x > 3:
    return True
else:
    return False

This can be written more concisely as return x > 3. If your code looks like the code above, see if you can rewrite it more succinctly!

Console Input and Output

We often want to have the user input data while a program is running or print things to the screen.

Input

We can get input from the user using the input() function.

value = input(<prompt>)

The input function takes an optional input parameter, a string that will be displayed to the user as a prompt. It the waits for the user to press the Enter/Return key and returns all the characters the user typed as a string which we can then store. For example, the following code:

fName = input("Enter your first name. => ")

would result in the string Enter your first name. => being displayed on the screen with the cursor just after the last space printed. After the user typed something and then hit Enter, that string would be bound to the variable name fName and you could use it in your program.

Converting numbers

The input() function always returns a string. If you know that the user is typing in a number, and want to use it in calculations in your program, you need to convert it to a number type (float or int). This is done using the float() and int() functions. i.e.

stringNum = '22'
intNum = int(stringNum)     # converts '22' to 22
floatNum = float(stringNum) # converts '22' to 22.0

stringNum = '2.718'
intNum = int(stringNum)     # generates an error
floatNum = float(stringNum) # converts '2.718' to 2.718
Note

Calling int() on a non-integer number results in an error.

Output (#output)

To display something to a user, we use the print() function. The print() function takes a comma-separated list of expressions and prints them each in turn separated by spaces. Here are some examples:

>>> print("Hello world!")
Hello world!
>>> print("Welcome", "to", "CS 111.")
Welcome to CS 111.
>>> a = 3
>>> b = 4
>>> print("The sum of",a,"and",b,"is",a+b,'.')
The sum of 3 and 4 is 7 .

Formatted Strings

Notice in that last example there is a space between the 7 and the period. That’s probably not what we wanted. Plus that comma-separated lists is a little unwieldy. Python also provides us with a formatted string (f-string) option that we can use to create strings.

It works by starting the string with an f before the opening quotation mark. You can then put Python expressions inside braces ({}) and Python will evaluate the expression and put the value in place of the expression when it prints. We could rewrite the last example above using an f-string like this:

>>> a = 3
>>> b = 4
>>> print(f"The sum of {a} and {b} is {a+b}.")
The sum of 3 and 4 is 7.

Notice that the extra space is now gone. Additionally, we can add formatting commands to the expressions. The one you’ll be using in this class is to format floating point numbers. You can add a formatting code to an expression by following it with a colon (:) and then the format you want. For formatting floating point numbers the formatting code looks like this:

:<num spaces>.<num_decimal>f

where <num_spaces> is the amount of spaces to print the number in and <num_decimal> is the number of digits after the decimal point to print.

Note

We typically leave <num_spaces> blank so it just uses up the minimum space needed.

Some examples:

e = 2.718281828459045
>>> print(f"To two decimal places: {e:.2f}")
2.72
>>> print(f"To ten decimal places: {e:.10f}")
2.7182818285

Error Messages

By now, you’ve probably seen a couple of error messages. They might look intimidating, but error messages are very helpful for debugging code. The following are some common types of errors:

Error TypesDescriptions
SyntaxErrorContained improper syntax (e.g. missing a colon after an if statement or forgetting to close parentheses/quotes)
IndentationErrorContained improper indentation (e.g. inconsistent indentation of a function body)
TypeErrorAttempted operation on incompatible types (e.g. trying to add a function and a number) or called function with the wrong number of arguments
ZeroDivisionErrorAttempted division by zero

Using these descriptions of error messages, you should be able to get a better idea of what went wrong with your code. If you run into error messages, try to identify the problem before asking for help. You can often Google unfamiliar error messages to see if others have made similar mistakes to help you debug.

For example:

>>> square(3, 3)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: square() takes 1 positional argument but 2 were given

Note:

  • The last line of an error message tells us the type of the error. In the example above, we have a TypeError.
  • The error message tells us what we did wrong – we gave square 2 arguments when it can only take in 1 argument. In general, the last line is the most helpful.
  • The second to last line of the error message tells us on which line the error occurred. This helps us track down the error. In the example above, TypeError occurred at line 1.

Required Questions

What Would Python Display? (WWPD)

Q1: WWPD: Veritasiness

The “What Would Python Display?” (WWPD) questions are designed to test your knowledge and understanding of what the given Python code is doing. You should read the code and try to determine what would be displayed by the Python interpreter. After you’ve made your guess, or if you are completely stumped on what it is doing, type the code in to the interpreter and see what happens and if you were correct. If not, spend some time figuring out what was wrong.

Use the following “What Would Python Display?” questions to test your knowledge on logical operators and short-circuiting:

>>> True and 13
______
>>> False or 0
______
>>> not 10
______
>>> not None
______
>>> True and 1 / 0 and False
______
>>> True or 1 / 0 or False
______
>>> True and 0
______
>>> False or 1
______
>>> 1 and 3 and 6 and 10 and 15
______
>>> -1 and 1 > 0
______
>>> 0 or False or 2 or 1 / 0
______
>>> not 0
______
>>> (1 + 1) and 1
______
>>> 1/0 or True
______
>>> (True or False) and False
______

Discuss the following with your group:

  • What didn’t make sense?
  • What surprised you?
  • Are there any that you still don’t understand? Ask someone to explain it for you.

Q2: WWPD: If Statements

Use the following “What Would Python Display?” questions to test your knowledge on if statements.

If you ran the following code what would be printed?

a = 10
b = 6
if a == 4:
    print('6')
elif b % 2 == 0:
    print(a // 2)
else:
    print(3 * b + 1)

What about if a = 4 and b = 6?

What about if a = 0, and b = 3?

What would print out if you ran the following with x = 7?

if x > 10:
    print('huge')
elif x > 5:
    print('big')
elif x > 0:
    print('small')
else:
    print("nothing")

What if x = 12?

What if x = -1?

What values of x would cause ‘small’ to be printed?

If there is something happening in either of these examples that you find confusing, discuss it with the others in your group or the TAs so you can understand what is going on.

Coding Practice

Q3: Mad Libs

For this question, you will write a little Python script in the lab01.py file that prompts the user for some input, and then uses that input to fill in a Mad Libs style statement. We’ll throw in some math, conditionals, and formatting along the way as practice.

Your program should perform the following in this order:

  • Prompt the user for an integer divisible by 20
  • Check if the integer is divisible by 20
    • If the integer is not divisible by 20, the program should print the error message:

      <integer> is not divisible by 20!
      

      where <integer> is the number entered.

      Then your program should stop executing code after printing the error message.

      Hint

      Don’t call exit() as this will hard exit the program and break the autograder. Try to see if you can find another way to make sure the program won’t execute any more code.

  • Prompt the user for a floating point number
  • Prompt the user for a singular family member (i.e. mother, father, cousin, grandmother, uncle, etc.)
  • Prompt the user for a noun
  • Prompt the user an adjective

The program should then print out the following sentence filling in the values provided by the user:

<integer // 20> score and <floating point number> years ago, our fore<familymember>s brought forth upon this <noun> a <adjective> nation.

The floating point number should be printed with 3 decimal places.

A successful example run might look like this:

$ python lab01.py
Enter an integer divisible by 20 => 100
Enter a floating point number => 3.1
Enter a family relationship (mother, grandfather, cousin, etc.) => aunt
Enter a noun => tricycle
Enter an adjective => glowing

5 score and 3.100 years ago, our foreaunts brought forth upon this tricycle a glowing nation.
$

A failing example might look like this:

$ python lab01.py
Enter an integer divisible by 20 => 57

57 is not divisible by 20!
$

Run the pytest provided for you for this lab once you’ve gotten it working to verify that you are doing everything correctly.

pytest -vv

Fix any errors that come up. Discuss with your group and the TAs if you don’t understand any errors you encounter.

The tests are only checking the output so you can use whatever wording in the prompts you want but you do need to prompt in the correct order. The tests will also provide bad integer input to verify that you are printing the correct error code.

Submitting your work

For each lab, homework, and project assignment you will submit your work to the auto-grader to get your final score. We’ll walk you through the process in this lab.

  1. Make sure you are passing the pytests we provided with the lab on your local machine. These are the exact same tests that the auto-grader runs so if it is working on your machine, it should work in the auto-grader.
  2. Go to the class in Canvas and navigate to the assignment there. In this case, ‘Lab 01’. All the assignments are linked from the main home page for the class in Canvas
  3. Click on the “Load Lab 01 in a new window” button. This will open the assignment submission page in Gradescope.
  4. In the bottom right of the page there is an “Upload Submission” button. Click on that. A dialog box will appear to upload your file.
  5. Select the file or files that need to be uploaded for the assignment. In this case it is just your lab01.py file. You can either drag the file from a file explorer window or click on the dialog that appears to open a file browser window.
Note

Do not upload everything in the folder where your assignment code is. You should only submit the specific files requested. Submitting more might work but might also cause the autograder to fail and you may not receive credit.

  1. Once all the files are selected, click on the “Upload” button in the dialog box. This will send your file(s) to Gradescope for grading.
  2. Wait for the results. This typically only takes 10-15 seconds but for larger assignments, busy times, or assignments with errors, this can take longer.
  3. Review the results. Most of the time this should just tell you that you received all the points. If there are errors, check the error messages to see why it is failing. If you successfully ran the tests on your computer and the auto-grader is failing, contact a TA or your professor.
  4. You are done. We transfer scores from Gradescope to Canvas weekly.

In future assignments, we will just provide the link to Canvas and tell you what files you should submit. You can always refer back here if you don’t remember exactly how to submit your code.