Lab 1: Your first program

Programming Rules

There are two things we can ask Python to do: simplify an expression to get a value, or store a value (perhaps created by simplifying an expression) into a variable. Type the following code into the Python shell (the bottom window in Thonny, called the shell):

1 + 2

Python will simplify that expression and show you the value: 3. Next, try this:

x = 1 + 2

This time, Python doesn't show you the result, because it stored the result into the variable x instead. To see the value of x, just type x and then hit enter.

Next, try these:

1 + 2 = x
x + y = 4
x = y + 4

None of these commands will work, but x = 1 + 2 did. With your partner, discuss what you think are the limitations of Python? Why might those limitations be in place?

Click here to show the answers

Python can only assign a value to one variable at once, and it must be on the left-hand side of the equals sign. Other variables can appear on the right, but they must be variables that have already been assigned values.

These limitations ensure that when Python is simplifying an expression, there aren't any variables left over: every variable in the expression can be replaced with a value, so the whole expression can be reduced down to a single number (or some other kind of value). Python only has to keep track of the current value of each variable, and it never has to remember an equation.

Now, try this:

y = 5
x = y + 4

If you ask for the value of x, it should give you 9. Python can simplify, as long as all variables are known in advance. What happens if we change the value of y now?

y = 10

With your partner, discuss what you think the value of x will be after running this statement, and why.

Click here to show the answer

What we said above gives a clue: Python remembers values, but not equations. So Python doesn't remember that the value of x is y + 4, it just remembers that the value is 9. When we change y, Python doesn't update x, and its value will still be 9. This is an important difference between mathematical equations and programming statements.

Next, try this, but before you hit enter, discuss with your partner: Will this work, and if so, what would be the value of y afterwards?

y = y + 1
Click here to show the answer

Indeed, this does work, and sets the value of y to 11 (or if you run it again, 12, and then 13, etc.). Python first simplifies the right-hand side using the old value of y, and then updates y to get the new value.

There are a variety of operators available to use in expressions (try these):

2 - 3
3 * 4
15 / 5

And a few special operators:

5 // 4
12 % 10
3 ** 2

Try different values with //, %, and **. What do these operators do?

Click here to show the answer

// does division, but rounds down to the nearest integer. % computes the remainder after division, which is also called the modulus. ** does exponentiation, raising the number before to the power of the number after.

Functions

In addition to mathematical operations like +, Python can simplify functions, and it comes with some built-in. Just like in math, we write the name of the function, then a pair of parentheses, and then the input values for the function (which we call "arguments" in programming).

One of the built-in functions is print, which causes the program to display a value.

So far, we've been writing code in the shell, and whenever we write an expression, Python shows us the result, but when we created a variable, we had to ask for the value separately. When we write a whole program however, Python won't show us anything unless we ask it to.

Create a new file in Thonny, save it as lab01.py, and copy/paste the following code into the file; then run it:

x = 1 + 2
y = x + 4
print("x + y is:")
print(x + y)

This program simplifies two expressions to create two variables, which hold the values 3 and 7. Then, it simplifies two more expressions which use the print function to display values (code in a program runs from top to bottom, one line at a time). The output should look like this:

x + y is:
10

Why do you think Python replaced x + y with 10 in the second print, but not the first one?

Click here to show the answer

In the first line, we used quotation marks. This tells Python to use that text as-is, without simplifying it. On the second line, we didn't, so Python interpreted x + y as an expression to be simplified.

Working with text

We can define text within a program by surrounding it with quotation marks. Pieces of text (a.k.a. strings) can be stored in variables, and we can also use '+' to combine them.

Here's a simple program that uses text (you can replace your current program with this code):

name = 'Peter'
print("Welcome to CS111," + name)

How could you use your own name instead of 'Peter' in this program? What's the issue with the output, and how can we fix it?

Try to make these changes yourself.

Click here to show the answers

On the first line, put your name in quotes instead of Peter. The issue with the output is that there's no space between the command and the name. To fix this, we can simply add a space inside the quotation marks, just after the comma, so that when we add the strings together, the space ends up in the middle.

In addition to using '+' to combine strings, we can also use '*' with a string and an integer. What do you think this code will do?

print('HA'*8)
Click here to show the answer

When we use * with text and an integer, Python will repeat the text that many times to make a longer piece of text. In this case, the result is "HAHAHAHAHAHAHAHA".

There's one more important built-in function that works with text: input. Try this code in your file:

name = input("What is your name? ")
print("Hi, " + name)

Now, when you run the program, Python pauses after displaying "What is your name? ". Try typing something and hitting Enter. What do you think is the significance of the input function?

Click here to show the answer

input lets us write programs that do something different each time we run them, based on what is typed by whoever runs the program. Without input, anyone using the program would have to modify its code to change what it does, but with input, only the original programmer needs to know how to program.

Next, try this program, but before you run it, try to predict what it will do:

result = input("First number: ") + input("Second number: ")
print("The result is: " + result)
Click here to show the explanation

This program begins by displaying the text "First number: " and waiting for an answer. Then it gets an answer to the prompt "Second number: " and combines those two answers into one value. But it treats them as text, not as numbers, even if you type in a number! That's because Python keeps track of the type of each variable, and processes things differently depending on their types.

Text and Numbers

What happens if we try to add a string and a number together? Let's try it (in the shell):

"two" + 2

We get an error:

Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

Discuss with your partner: What do you think this error means?

Click here to show the answer

"Concatenate" means "add together", and "int" and "str" are abbreviations for "integer" and "string." Python is trying to tell us that it doesn't know how to combine a piece of text with a number into a single result using '+'.

Now try these expressions (can you guess what the results will be first?):

"two" + "two"
2 + 2
"2" + "2"

We need to keep track of types as we program, and we can use the built-in function named type to help. Try these expressions:

type(2)
type("two")
type(2.5)

We can also use conversion functions to convert some values between types. Try these:

str(5)
int('5')
int('five')
int('δΊ”')

Note that Python has a very limited ability to convert strings into integers (only Arabic digits work).

Finally, try these expressions in the shell:

len('hi')
len('hello')

Can you and your partner guess what the len function does?

Click here to show the answer

len measures the length of a piece of text, in terms of the number of letters (and spaces, digits, etc.). The result is always an integer.

Task 1: Underlining text

To practice working with expressions and variables, you'll write a program that does something simple: it asks the user for input, and then prints out that input, with a second line of dashes below that has the same length to serve as an "underline." Use input, print, and len to accomplish this. Work together with your partner, with one person writing code and the other person suggesting strategies and spotting typos. Here are three examples of how the program should work:

Example #1:

Enter a string: Hi
Hi
--

Example #2:

Enter a string: Lovely day today
Lovely day today
----------------

Example #3:

Enter a string: Sometimes you feel like a nut
Sometimes you feel like a nut
-----------------------------

Exploration Questions

You may already know the basics of programming from previous experience. If you and your partner are finished with this part of the lab early, you can move on to the next part, but if you're curious, here are a few questions to stretch your thinking about basic operators and variables (if this is your first day programming, don't worry about these!):

  1. What is the shortest possible string in Python? What is its length? How would you write it?
    Click here to show the answer

    The "empty string" can be created by writing two quotations marks next to each other, like this: ''. Its length is zero.

  2. We saw an example of an error that happened when trying to add together a string and a number. Is it possible to create an error using just numbers and mathematical operators? If so, what's an expression that would do that?
    Click here to show the answer

    Some mathematical operations aren't well-defined, and we can get errors for those. For example, dividing by zero doens't make sense, so the expression 5 / 0 will result in an error. By the same logic, the integer division and remainder operators will cause an error if their right-hand operand is 0.

  3. print is a function that causes stuff to be displayed when you simplify it, which we call a "side effect," but like every function, it also has a result value. However, unlike most results, we won't see it show up if we just type print('hi') in the shell. What is the result value of print, and what happens if we store it in a variable?

    Click here to show the answer

    The result of print is a special value called None, which is a way of indicating that even though there needs to be some result (because every function must have a result value when simplified), there isn't really anything meaningful. By default, this value is not displayed in the shell. If you try typing 5 in the shell, it will show you that 5 is the result, but if you type in None (no quotation marks), you will just see another prompt without any result displayed. If we store it in a variable, we won't be able to use that variable in other operations. For example:

    m = "hello"
    print(m * 2)
    x = print("hello")
    print(x * 2)

    The first two lines here work fine, and print hellohello. But while the third line actually prints hello, the fourth line will crash, since x will have the value None rather than "hello".

  4. What's a piece of text that you can't create using single quotes? How about using double quotes? Are there strings you can't create using either double or single quotes?
    Click here to show the answer

    A piece of text with a contraction that uses a single quote can't be enclosed in single quotes, since the quote mark inside will be interpreted as the end of the string. For example, you can write "This doesn't work." using double quotes, but not single quotes. By the same logic, a piece of text that should contain a double quote, like 'She said "Hi!"' can't be created using double quotes. And if you wanted to use both a single quote mark and a double quote mark in the same string, neither type of quote would work. Python allows something called "triple quotes" to get around this, where you use three of the same kind of quotation mark in a row to start and end a string. In addition, triple-quoted strings can contain multiple lines of text, which isn't allowed with normal single or double quotes.

  5. In general, Python will simplify expressions so fast that it basically takes no time at all. But can you think of an expression that would take a while for the computer to evaluate?
    Click here to show the answer

    There are several was to force Python to spend some time on an operation. One example: compute an extremely large number (like 2 ** 1000000). Another example: ask Python to create a huge number of repetitions of a piece of text (like 'duck' * 10000000). Note that if you try something too large you could be waiting minutes, hours, or even days for an answer, and Python might crash if it runs out of memory in the attempt. You can click the stop button (or hold the control key and press 'C') to force Python to stop what it's doing if you need to.

Table of Contents