Week 2: Expressions

Reading: Think Python Chapter 2 (Review)

Notes

Arithmetic

The Python interpreter is much more than a calculator. We can see how it works by looking at some elementary math.

Consider the mathematical expression \((4 + 2) \times 3\). We can express this in Python in a very similar way:

(4 + 2) * 3
18

The parentheses are important, without them, we would be evaluating a different operation:

4 + 2 * 3
10

In the conventional order of operations, multiplication occurs before addition. Without the parentheses, Python firsts evaluates the simple expression 2 * 3:

2 * 3
6

and then ‘replaces’ that expression with its result before evaluating the next expression:

4 + 6
10

By adding the parentheses, we tell Python to evaluate the expression inside the parentheses first, and then replace that expression with its result.

6 * 3
18

You will never explicitly see a sub-expression replaced by its result. This only happens “under the hood” when Python runs your code. However, you can always try out sub-expressions using the interpreter to make sure your code is doing what you want it to do.

Remember: when in doubt, use parentheses to explicitly instruct Python the order for evaluating expressions. You will end up using parentheses for much more than just simple math.

Operators

A basic way to craft expressions in Python is with operators. Many operators look and behave (almost) the same way in Python as they do in math.

Operator Function (with numbers)
+ Addition
- Subtraction
* Multiplication
/ Division
** Exponentiation
// Quotient
% Remainder

You should know how these operators work with numbers. They will work differently (or not work at all) with other kinds of data, which we will see later. For exams in the class, you will never need to do anything more than basic arithmetic and counting.

Whitespace

  • “Whitespace” refers to characters in a text (or .py) file that appear to be blank, such as spaces, tabs, and carriage returns.
  • Whitespace is important in Python, because it separates different logical operations
    • Carriage return (“enter”) ends a logical line
    • Additional spaces are usually optional if there is no ambiguity
    • Tabs organize and associate code (you will see this later)

These expressions are equivalent:

2+4*(3+1)
18
2 + 4 * (3 + 1)
18

Python does not care if your code is easy for humans to read, but you should care. The code below will run, but you should avoid inconsistent spacing, because it makes the code difficult to read. If you start working on a problem, stop, and come back to it later, you will want to be able to read your own code.

2+ 4    * ( 3 +1        )
18

Text

In Python, by placing characters (including numbers) between quotation marks, we form strings, text data. You can use single or double quotation marks, but they must match.

Both of these will work:

"Hello!"
'Hello!'
'Hi.'
'Hi.'

But this gives us an error:

"Hello'

We can use some mathematical operators with strings, but the behavior may not be intuitive. Strings are not numbers.

For now, let’s use the + operator. It concatenates (attaches end-to-end) two strings.

'view' + "point"
'viewpoint'

Wrapping numeric characters with quotation marks means those numbers are interpreted as text:

'1' + "2"
'12'

Mixing numbers and strings with the + operator will give you an error.

1 + "2"

Printing

Remember that while the interpreter will always show you the result of an expression, you need to use print statements for your programs (in the editor) to have any output.

concatenate_print.py
print("1" + "2")
print("three")

Whatever is inside the parentheses of the print function will be evaluated, and the result will be printed to the console. The expression (or value) inside the print statement does not need to result in (or be) a string!

add_print.py
print(1 + 2)
print(3)

Notice that after each print statement, the next print statement appears on a new line.

Variables

The result of an expression can be assigned to a variable for later use.

x = 3 + 1

Variable x has been assigned the value 4. When we reference x in an expression, that value is retrieved:

print(x)
4

The assignment operator = is not the same as mathematical equality. It works like this:

  • The expression to the right of the = is evaluated
  • After evaluation, the result is assigned to the variable left of the =

This means that we can write Python code that doesn’t translate directly to a math equation:

x = 3 + 1

3 + 1 was evaluated and x was assigned 4.

x = x + 1

x + 1 was evaluated: x was 4, so x + 1 became 4 + 1. After evaluation, x was assigned 5.

print(x)
5

The idea of variables having different values at different times during program execution is called state. In the interpreter, state is maintained (variable names are saved) until you change them with a new assignment, or you restart the interpreter. When running a program you write in the editor, state is reset each time you run the program.

Variables do not exist until you first assign them. Referencing a variable you haven’t assigned will yield an error:

print(y)


Variable names are text, but they are not interpreted as text. However, if you put a variable name in between quotation marks, that tells Python to interpret the name literally, as a string, with no connection to the variable.

print('y')
y

Not all ‘names’ are valid for variables: the textbook goes into more detail. In general, start variable names with a letter.

This is a place that whitespace is important: the space after a variable name indicates the end of the name. This means you cannot have a space in the name. To get around this, use underscores:

coffee type = 'espresso'

coffee_type = 'espresso'

Practice

Practice Problem 2.1

Practice Problem 2.1

This program was intended to multiply 3 by 4, subtract one from the result, and then multiply that result by 2.

operations_order.py
x = 3 * 4 - (1 * 2)
print(x)

Fix the program so it works. Your result should be 22.

Practice Problem 2.2

Practice Problem 2.2

This program was intended to subtract 4 from 9, then print the result added to 2.

variable_reference.py
value = 9 - 4
print("value" + 2)

Fix the program so it works. The printed output should be 7.

Practice Problem 2.3

Practice Problem 2.3

The area of a circle is given by \(\pi r^2\), where \(r\) is the radius of the circle. This program attempts to define \(r\), and then perform the calculation using an approximate value of \(\pi\).

Something went wrong - fix it!

circle_area.py
r = 4
pi = 3.141
area = pi * R ** 2
print("The area is: " + "area")

Fix the program so it works. Your result should be The area is: 50.256.

Homework

  • Homework problems should always be your individual work. Please review the collaboration policy and ask the course staff if you have questions.

  • Double check your file names and printed output. These need to be exact matches for you to get credit.

Homework Problem 2.1

Homework Problem 2.1 (25 pts)

Printed output is one line at at time. The program below prints out a ‘triangle’ using * characters:

print("*")
print("**")
print("***")
print("****")
*
**
***
****

Write a program, box.py, that prints out the square shown below:

++++++
+    +
+    +
++++++

Inspect the desired output carefully! You need to get an exact match.

Homework Problem 2.2

Homework Problem 2.2 (50 pts)

For this problem, you will write two programs. They will take this format (read the comments!):

duplicate1.py
# your program should start with comments
# write things here, such as the name of any TA you got help from
# you can have as many comment lines as you like
# after the initial comments, there should only be 5 lines of code that run
x = 1
y = x + 1
print(x)
print(y)
print(y + 1)

The printed output of your programs should, for both, match:

1
2
3

All three programs should differ in their entirety, and the differences should be more than variable names, whitespace, and expression order. What to avoid (examples):

  • y = 2 and y=2 are logically the same
  • x + 2 and 2 + x are logically the same
  • x = 2 followed by print(x) is logically identical to y = 2 followed by print(y)

If any of the 5 lines of code that run are removed:

  • The printed output should be different, or
  • The program gets an error

Submit these two programs as duplicate2.py and duplicate3.py.

An example of two distinct programs that have the same output:

first_duplicate.py
# 
e = 2
f = 2 + e
print(e)
print(f - 1)
second_duplicate.py
# 
e = 1
f = 2 * e
print(e + 1)
print(f + 1)

Homework Problem 2.3

Homework Problem 2.3 (25 pts)

Write a program to sum the even integers between 0 and 16, using exactly three lines of code that run, similar to the previous problem. Include 16 in your sum but do not include 0.

The printed output should be:

72

Submit this program as summer.py.