Week 2: Numbers, Strings, Loops

Class Recordings

To access recordings, sign in with your @swarthmore.edu account.

Monday

N/A

N/A

Wednesday

Section 1 (Joshua)

Section 2 (Kevin)

Friday

Section 1 (Joshua)

Section 2 (Kevin)

Monday

Monday is Labor Day.

Wednesday

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. They both 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.

Python math operators

Mathematical calculations are one of the most common uses of computer programming. Below is a quick summary of python3 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. 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.

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 follows the following rules

  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)

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 = π × r2 (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.

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 sequence. This is how we designate a value of type list. A list is a collection of values itself, which can be of any type (e.g., int in the above example). 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!")

Friday

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 w02 directory.

Exercise: loop.py

cd
cd cs21/inclass/w02
atom ./

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: Alternatively, 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: 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].