Numbers and Strings

Monday

Solution to grad year program

Run update21 to get a sample solution to the grad year program from last Friday.

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 python3 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 C35, 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 returns 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.

Quick practice

Take a minute or two, open up a python interpreter window, and play around with math operators. Do they do anything unexpected? Try to combine them in larger expressions. What happens?

$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.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
>>> 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, 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. e.g. the evaluation of 2*19+3 is 41. This is why expressions can appear on the right-hand side of assignment statements. 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 are evaluated first, 2*(3-1) is 4, and (5-2)**(2+2) is 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

With the remaining time, 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)

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

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

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 the range(x) operator:

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

which outputs:

0
1
2
3
4

Wednesday

Today’s Topics

  • for loop syntax/semantics

  • range() function

  • loop practice

  • introduction to accumulator pattern

Loop syntax recap

Exercise: What do these loops do?

What is the output of this loop?

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

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("Pets:")
for animal in ["Corgis", "Cavaliers", "Mini Ponies"]:
  print(animal)
print()
print("Done!")

You can see examples similar to these and a few extras in your w02-numstr folder.

$ cd
$ cd cs21/inclass/w02-numstr
$ atom ./
$ python3 loopExamples.py

Exercise: loop.py

cd
cd cs21/inclass/w02-nums-strs-loops
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.

  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.

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?

Friday

Today’s Topics

  • Accumulator practice

  • Looping over strings

  • String accumulators

Exercise: Average

Use the example solution for total to complete the program in avg.py and 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 \$x! = x \cdot (x-1) \cdot (x-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] = "u".

  3. concatenation. Concatenate with the + operator. "hello" + "world" == "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

Welcome 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