Tips/Tricks

Atom

Terminal

Reminders

Today

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. Exponents are an exception; they are evaluated right to left.

Remember to be specific with your Python code: 2x+3 is a SyntaxError. 2*x+3 multiplies x by 2 and then adds 3.

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.

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

Does this do what you expected? It turns out that range(x) gives you a sequence of numbers from 0,...,(x-1).

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("Colors:")
for color in ["Blue", "Red", "Yellow", "Magenta"]:
  print(color)
print()
print("Done!")

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.
  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:

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 * (n − 1)*(n − 2)*...*2 * 1 e.g., 5!=5 * 4 * 3 * 2 * 1. Begin by answer the questions above and then start to write your program in factorial.py.