Lab: Basic Types and Operations

10 minute read

Preparation

These exercises should be completed with your assigned partner. Both of you will take turns playing the role of the driver (the one currently screen sharing) and the navigator. The driver’s responsibility is to type into Thonny, etc., when completing each exercise, and the navigator’s responsibility is to support the driver by reading the exercises, looking up relevant readings, and identifying errors. At all times you should be working together on the exercises rather than completing them independently.

Before you begin, you should ensure that today you perform opposite roles as the previous lab. Thus, the role of the driver should be the partner whose name comes alphabetically last.

Warning! Since Python files are programs and could be malicious, Microsoft Outlook does NOT allow you to send Python files via email. You will have to share Python files via Zoom or Microsoft Teams.

Exercise 1

In this exercise, we will experiment with using variables.

a. Open up Thonny. If you haven’t installed Thonny yet, go to the Installing Thonny page and follow the instructions to install it. Remember that the bottom pane of the Thonny editor is called the shell. We will be using it a lot in this lab (and future labs!).

b. In case you forgot, exchange your name with your partner before moving on.

c. In the shell, execute the following commands and replace the word YOUR NAME with your name and THEIR NAME with your partner’s name. (Keep the surrounding quotations.)

>>> you = "YOUR NAME"
>>> them = "THEIR NAME"
>>> pi = 3.1415

Note: Remember you do NOT need to type the >>> characters above—the shell automatically provides those for you.

d. Verify that the variables have been properly defined by executing the following commands in the shell to see what they print.

>>> print(you)
>>> print(them)
>>> print(pi)

Pro Tip: Thonny can also show you the currently defined variables through the variables toolbox. To show the toolbox, select the View -> Variables menu item.

e. Try out the following more complex expressions to see what they print. (You can copy and paste the commands.)

>>> print("hello", them, "my name is", you)
>>> print("a right angle is", pi / 2, "radians")

f. Discuss with your partner what you think will happen if you try using a variable name that hasn’t been defined before; then try verifying your prediction in the shell.

g. The built-in print subroutine is used to actually output text to the user. However, the shell will show you the result of evaluating expressions even though they normally wouldn’t be displayed in a program. Try typing out the following commands and note the results that are displayed in the shell.

>>> 2 * pi
>>> you
>>> 3 + 4 / 2

Note: Since the print function is not used above, these expressions normally would NOT be printed if the code was run in script mode. For example, if you had the above expressions in a file named test.py, opened it in Thonny and executed it, only text that is explicitly printed via the print function will be displayed.

However, the shell will always print the result of an expression–even if you did not print it with the print function.

h. Note that print itself is a variable. It’s default value is the location of the built-in subroutine that prints to the display. What do you think will happen if you type the following into the shell? Discuss with your partner; then type it in to see.

>>> print

i. The basic values stored inside a variable name can be changed by executing another assignment statement. Verify this by typing

>>> pi  = 0
>>> pi

j. Do you think you can write assignment statements backwards? Try typing

>>> 21 = pi

Remember that assignment statements are always of the form <name> = <expression> and creates (or updates) the variable associated with <name> with the result of evaluating the expression <expression>.

k. What do you think will happen if you change the value of the print variable? Discuss with your partner then execute the following to test your guess.

>>> print = "abc"
>>> print

l. What happens if you try to call the print function after you’ve changed its value now?

>>> print("Hello world!")

Warning! If you change the value of print in your program, you cannot change it back without restarting your program or the shell! Thus, it is a good idea to avoid changing the built-in functions in your program.

m. Hit the green Run button in the toolbar to refresh the shell to get access to the print function again.

n. What happens if you try to name a variable that starts with a number or special character? Try it out in the shell.

Note: All variables must start with a alphabetic character or underscore _. Any later character in the name can consist of characters, numbers, or underscores.

o. What happens if you try to use a keyword as a variable name? Try typing the following to test it out.

>>> for = 100

Note: Keywords are reserved words that have special meaning in Python. You cannot use them as variable names. These are words like for, in, while, if, else, and many others. Similar to for above, reserved words usually are displayed in a different color in Thonny.

Exercise 2

In this exercise, we will experiment with how expressions are evaluated into their basic values.

a. For each of the following expressions, evaluate the expressions by hand with your parter and guess what the result will be. Then verify your results by typing them into the shell.

>>> 5 * 4 + 3
>>> 5 * (4 + 3)
>>> 2 ** 4 - 1
>>> ((15 // 2) + 2) * 3

b. If you and your partner aren’t sure what the ** and the // operators do, play around with them in the shell until you have a good idea what they are doing. Then ask the instructor to confirm your thoughts.

c. We can also have expressions that evaluate to a string literal. Try the following in the shell to see what they evaluate to.

>>> "Fall" + "Winter" + "Spring"

Note: The + operator on strings means “concatenate”. It will join two strings literals together into one.

d. What do you think will happen if we use the + on two different basic value types? Discuss with your partner what you think the following command will do and then test your prediction.

>>> num = 4
>>> "The number I am thinking of is: " + num

Note: You cannot concatenate num onto the previous string without first turning it into a string. We can do this by using the built-in str subroutine which turns basic values into their textual representations. When applied to numbers, it behaves as you might expect.

e. With your partner, predict what each of the following expressions will evaluate to; then try each of them in the shell to confirm.

>>> str(23)
>>> str(num)
>>> "The number I am thinking of is: " + str(num)
>>> 123 + 456
>>> "123" + "456"
>>> str(123) + str(456)

Exercise 3

In this exercise, we will explore the differences between the int and float types of numbers.

a. For each of the following, predict (with your partner) whether you think the expression will evaluate to a value of type int or a float.

  • a + b where a and b are both int
  • a + b where a and b are both float
  • a + b where a is an int and b is a float

b. Test your predictions in the shell with something like:

>>> 5 + 4
>>> 3.14 + 2.7
>>> 4 + 2.7

c. For each of the following, predict (with your partner) whether you think the expression will evaluate to a value of type int or a float.

  • a / b where a and b are both int
  • a / b where a and b are both float
  • a / b where a is an int and b is a float
  • a // b where a and b are both int
  • a // b where a and b are both float
  • a // b where a is an int and b is a float

d. Test your predictions in the shell.

e. Try running 15.0 // 3 in the shell. Why do you think it returns a float here? Discuss this with your partner.

f. Integers in Python are perfectly precise and can have an arbitrarily large number of digits. Notice that even the following expression will evaluate correctly:

>>> 11111111111111111111111111111111111 + 2

g. Try to generate really large integers to see if you can cause Python to struggle. (It is easy to generate large numbers with the ** operator. For example, 2 ** 100. If the shell is running for too long, you can interrupt the program by pressing Ctrl + C on the keyboard.)

h. Floats in Python are only approximate. With your partner, predict what the result of the following expression will be; then try typing it into the shell to check.

>>> 0.1 + 0.2

i. Discuss with your partner what you think happened above. What problems should we watch out for when working with imprecise numbers like floats?

j. Try experimenting with operations on various floats to see what sort of errors accumulate over time.

Exercise 4

In this exercise, we will experiment with the print function.

a. In Thonny, create a new file named print_test.py with the following text.

# A simple program to test the print function
#
# Author:
#   Titus Klinge and YOUR NAMES GO HERE
(5 + 25) / 2
print("Hello world!")
print("This", "print", "has", "multiple", "values")

b. Run the program.

c. Notice that since we are running the program in script mode, the result of (5 + 25) / 2 is not printed. Surround the expression with print(...) so that it will be printed:

print((5 + 25) / 2)

d. Modify the last print statement so that it uses string concatenation +:

print("This" + "print" + "has" + "multiple" + "values")

Rerun the program. What changed about the output?

Note: Whenever you execute print(val1, val2, ...) it will print all the values and automatically insert space characters in-between them.

Exercise 5

In this exercise we will experiment with the input subroutine.

a. Create a new file in Thonny named input_test.py with the following text:

# A simple program to test the input function
#
# Author:
#  Titus Klinge, YOUR NAMES GO HERE
x = input("Please enter a number to be stored in x: ")
y = input("Please enter a number to be stored in y: ")
print("The sum of the numbers is ", x + y)

b. Run the program and enter two numbers for x and y when prompted.

c. Was the output what you expected? Experiment with what is going on by running the program a few more times with different numbers. Also, try typing in something OTHER than numbers to see what it is doing.

Note: The input function always returns what the user types as a string. If you have a number in a string form, such as "123", you can turn it into an integer by using the int subroutine: int("123"). Similarly, you can turn a string into a float using the float subroutine: float("5.4").

d. Fix the input_test program by changing x and y into integers before adding them.

How to Submit Your Lab Work

  1. Once you are finished with the lab, you should go to codePost and log into your account with your Drake email address.
  2. Go to the CS 65 course.
  3. Go to Lab 2 and upload your print_test.py and input_test.py files.
  4. After you submit, open up your submission again. In Partners tab at the top of the submissions window, there will be a link. Send this link to your partner and have them open it while logged into their account.
  5. If all goes well, you should see both yourself and your partner as authors of the submission.

Finished Early?

If you have extra time, continue working on Assignment 2.