Week 3: Numbers, Strings, Loops

Monday

Solutions to grad year program

Run update21 to get two sample solutions to the grad year program from last Friday.

Programming Style

As you can see from the example solutions, there are many ways to write programs that solve the same problem. Both examples use the same basic structure:

  • A main() function calls input() to read a string from the user.

  • The program converts the string to an integer so that it can perform math to compute a number of years.

  • The program converts the newly-computed integer to a string so that it can print the result.

Which solution is better or preferable is a matter of taste. Our general advice to use a simpler style until you’re very comfortable with Python syntax. Beginning students tend to over-complicate code, which makes code harder to read and more likely to have errors. For now, don’t worry about the number of lines in your program — try to keep your code simple. In this context, simple doesn’t necessarily mean short, but rather easy to understand and follow. It’s typically easier to understand several simple statements than it is to understand one complex statement that does the same thing.

Python math operators

Mathematical calculations are one of the most common uses of computer programming. Below is a quick summary of Python 3 math syntax and semantics. I encourage you to try examples in the python interpreter and ask questions about strange cases.

  • +, -, *, and / represent addition, subtraction, multiplication, and division respectively. When you add, subtract, or multiply two integers, you get an integer. When you add, subtract, or multiply two floats, you get a float. Any addition, subtraction, multiplication, or division that involves one float and one integer results in a float answer.

  • Division using / in Python 3 always results in a float, regardless of the input types. Perhaps this makes sense to you. Why wouldn’t 3/2 be 1.5? If this is the case, python3 agrees with you, but in many other programming languages, including C and C++ used in CS31 and CS35, the rules for division are a bit different.

  • Sometimes, you might want to divide an integer by another and get an integer instead of a decimal number. The // operator rounds the value down returning an integer, e.g. 3//2 produces 1.

  • Exponents: To raise a number to a power, use the exponential operator **.

  • Mod: Python also supports division with remainder using the "mod" operator %. We’ll explain this more when we need it.

You can also combine many operators in one statement e.g. 2*x+10, but note you must explicitly include the * to multiply. The algebraic form 2x+3 is a syntax error.

Interactive Python

Normally when we run a python program, we feed an entire file of python code to python3 and all the lines of code are run one after another until it gets to the end of the file.

However, there is another way we can use python3; if you don’t give it the name of a file, it will give you an interactive prompt and wait for you to type python code directly. This lets you run a single line of python code at a time, and you can also see the output of each line as it gets run. Most of the time this is actually pretty annoying, since if you want to run something again or make a change you need to re-type everything. However, occasionally it can be useful for quickly testing things.

When running in interactive mode, whatever value an expression evaluates to will be automatically printed out if you don’t store it in a variable. This is nice if you want to use Python as a calculator, as shown in the following examples:

Note You’ll need to run the command quit() (including the parens) in order to stop running python and get back to the normal unix terminal.

Examples

$ python3
Python 3.8.10 (default, June 2 2021, 10:49:15)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> 5+2
7

>>> 5-2
3

>>> 5*2
10

>>> 5/2
2.5

>>> 5//2
2

>>> 2**5
32

>>> 2**32
4294967296

>>> 19/5
3.8

>>> 19//5
3

>>> 19%5
4

>>> 4*4.5
18.0

>>> 3*5 + 4
19

>>> quit()

String Operators

Some math operators can be used with strings:

  • Use + for string concatenation.

  • You can use <str>*<int> to repeat a string multiple times

>>> hw = "hello" + "world!"
>>> print(hw)
helloworld!

>>> "hello"*3
'hellohellohello'

Some other math operators can also be used with strings, but in somewhat more complicated ways. We will explore these operators a little later in the semester. Stay tuned!

Expressions and Operator Precedence

An expression is a combination of values, variables, operators, outputs of Python commands like int or input, and even other expressions! The evaluation of an expression produces a value. For example, the evaluation of 2*19+3 is 41. Producing a value allows expressions to appear on the right-hand side of assignment statements — the value gets assigned to a variable. Large mathematical expressions are common in Python.

Order of Operations

When more than one operator appears in an expression, which gets executed first depends on the rules of precedence. Python 3 uses a version of the order of operations that you’re probably familiar with from math classes: Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction (the acronym PEMDAS is often used with a mnemonic such as "Please Excuse My Dear Aunt Sally").

  1. Parentheses have the highest precedence and can be used to force the expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2*(3-1) produces 4, and (5-2)**(2+2) produces 81.

  2. Exponents have the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27.

  3. Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 2//3-1 is -1, not 1 (remember that in integer division, 2//3=0).

  4. Operators with the same precedence are evaluated from left to right. So in the expression minute*100//60, the multiplication happens first. If minute=59, this would yield 5900//60, which in turn yields 98. If the operations had been evaluated from right to left, the result would have been 59*1, which is 59, which is wrong.

A good rule of thumb when using expressions with lots of operators is to keep things simple. Use parentheses rather than relying on operator precedence rules. Better yet, if you have large math expressions, divide your Python statement into multiple lines of code.

Library Imports

Python supports many other useful mathematical functions, but these are stored in separate library. A library is a separate collection of functionality not part of the main Python language.

  • To load math functions, include from math import pi, sin, cos, sqrt once at the top of your program, even before the def main(): block

  • Once you’ve loaded the library you can call a math function as follows: sqrt(64)

>>> from math import pi, sin, cos, sqrt
>>> sqrt(25)
5.0

Programming Exercise

Write a program to compute the area of a circle. First, ask the user for a radius. Then, print out the area using the formula:

  • \(A=\pi r^2\) (area = pi * r**2)

$ python3 circle.py
Enter the radius of a circle: 3
The area of a circle of radius 3 equals: 28.274334

Extra challenge: write a program that computes the radius of a circle, given the area.

Wednesday

Repetition using for loops

To this point, all of our programs have been sequential - with one line of code following the other. Often, we need to repeat a task several times. If we know the number of times, we use definite loops, which are called for loops in Python. The syntax is:

for VAR in SEQUENCE:
    BODY

For example, we can print numbers 1 through 5:

for i in [1,2,3,4,5]:
    print(i)

i is our loop variable - it keeps track of where we are in the sequence. Defining the sequence explicitly does not scale to large numbers (e.g., 1000) so we instead use range(x):

for i in range(5):
    print(i)

which outputs:

0
1
2
3
4

Exercise: What do these loops do?

What is the output of this loop?

for i in [0,1,2,3]:
    print(i*2)

What is the output of this loop?

for i in range(10):
    print(10-i)

Notice the special syntax that uses brackets around a comma separated list to create a sequence. The range() statement genreates a sequence of numbers automatically.

Now try this example where the list consists of a sequence of strings:

print("Ice Cream Flavors:")

for flavor in ["Vanilla", "Mint Chocolate Chip", "Cookie Dough"]:
    print(flavor)

print()
print("Done!")

Loop Example

In a for loop, the loop sets the loop variable, i, to the first value in the sequence, executes the body, and then repeats. That is, it sets the loop variable to the next value in the sequence and then executes the body. It continues until it gets through every value in the sequence.

Each time the loop sets the loop variable to an item in the sequence and executes the body is known as one iteration of the loop.

def main():
    for i in range(5):
        print("You're awesome!")
        print(i)

main()

Reference Examples

You can find many more loop examples in the loopExamples.py file of your w03 directory.

Exercise: loop.py

cd
cd cs21/inclass/w03
vim loop.py

Open loop.py to get some practice writing loops by completing one or more of the following tasks:

  1. Print the string tricky three times, once per line, using a loop. Would your design change if you were asked to print tricky 1000 times?

  2. Print the squared value of the integers 1 through 5 (i.e. 1, 4, 9, 16, 25). Use the range function to define your sequence, and then manipulate i by adding 1 and squaring the value.

    Note: While it’s not necessary to solve this problem, there’s an alternate version of the syntax you can use if you want: you can pass a second input parameter to range to control where the number start and stop. range(a,b) produces a sequence of numbers starting at a and ending right before b. For example, range(4,8) produces [4,5,6,7]

  3. Write a loop that repeats three times and asks the user for a number that you then square. Note that this loop shows that the loop variable isn’t always used to do the calculation.

  4. Ask the user for an integer \(n\) and then print the values from \(n\) to 1 in reverse, with one number per line.

    Note: Again, it’s not necessary to solve this problem, but if you want you can pass a third input parameter to range to control the step of the sequence it generates. For example, range(0, 10, 2) produces [0, 2, 4, 6, 8] (0 to less than 10, counting by twos). You can also give it a negative step to count backwards. For example, range(5, 0, -1) produces [5, 4, 3, 2, 1].

Friday

Accumulator Pattern

A very common use of loops is to aggregate, or combine, the result of a repetitive set of steps. For example, we may want to sum the numbers from 1 to \(n\). To create an accumulator pattern, we should first answer these questions to help us code the solution:

  • What are we accumulating? (should create a variable to store this)

  • Where does the accumulator start? (initialize variable; not always 0)

  • How many iterations/times do we loop? (use to set the range)

  • What do we need to calculate inside the loop? How do we update the accumulator (updating the variable must be a part of the loop)

  • What do we do with result of accumulation?

Together, we will show in avg.py how to use an accumulator pattern to average a series of numbers entered by a user.

Exercise: factorial

Work with a neighbor and sketch out your solution to calculating the factorial of a number. Do not start to code until you have answered all of the questions above for designing an accumulation pattern. Your program should ask the user for a number (integer) and calculate the factorial. The factorial of a number is \(n! = n \cdot (n-1) \cdot (n-2) \cdot \ldots \cdot 2 \cdot 1\) e.g., \(5! = 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 = 120\). Begin by answering the accumulator questions above and then start to write your program in factorial.py.

More String Operations

You’ve seen several instances of strings already this semester, and you’ve likely used string concatenation to build up a string. There are many other useful string operations. Here are some highlights:

  1. length. To get the length of a string, use the len command e.g. len("cs21") = 4

  2. indexing. Access a single character in a string using its position indexing from zero. For example, if name="Punxsutawney", then name[1] is the string value "u".

  3. concatenation. Concatenate with the + operator. "hello" + "world" produces "helloworld"

Exercise: str_practice.py

Open str_practice.py to complete four tasks and a couple of extensions if you desire. Be sure to incrementally develop — complete one task, run your program to see if that tasks works, and then move onto the next. Tasks 4 and bonus will require for loops and accumulators.

$ python3 str_practice.py 
Task 1:
Enter first name: Tina
Enter last name: Fey

Hello Tina Fey

Task 2:
There are 7 characters in your name

Task 3:
Initials: T.F.

BONUS:
Last initials: a.y.

Task 4:
T
i
n
a

T
Ti
Tin
Tina

Accumulator Pattern - Strings

Just as we saw with numbers, you can use a for loop and the accumulator pattern to build strings. To start with an empty string, initialize a variable with two quote marks that have nothing inside them (not even a space):

result = ""

You can then build up the result string by accumulation with the + operator. Let’s practice together by writing a program interests.py that asks the user for three things they like and then prints them back:

$ python3 interests.py
Tell me three things you like!

Thing 1: plants
Thing 2: video games
Thing 3: CS 21

You like: plants video games CS 21