Python follows the same precedence of operations as in your high school math class (i.e., order of operations). Mainly, we process operators in the following order:
Python symbol | Meaning |
---|---|
func() | functions e.g., abs(-3) |
() | parentheses |
** | exponentiation |
- | negation (unary) |
*, /, % | multiplication, division, modulo |
+,- | addition, subtraction |
Symbols on the same tier are processed left to right. Test your understanding of types and mathematical expressions. Evaluate these expressions and see if the result and type are as expected:
num1 = 2.5
num2 = 4
print(type(num1))
print(type(num2))
print(num1+num2)
print(type(num1+num2))
print(int(num1+num2))
print(3/4)
print(3%4)
print(5%4)
print(float(3/4))
print(float(3)/4)
print(3 + 2 * 6**2 + 8 / 2)
print(3 + (2 * 6)**2 + 8 / 2)
print(3-7*10**2/6+3)
#Add parens to make that expression easier to read
Let us write a program from sratch that calculates the tax on a price (you can ignore the version from last week that we did not get to).
First, we need to put a block comment at the top of the program. It is good practice (and required for assignments) to include include a top-level comment that explains the purpose of the program at the top of all of your Python programs.
Next, remind yourself of the purpose of def main():
and main()
. The first defines what steps our program takes; the later tells Python to run our program. Type def main():
and indent all code inside of here. It is a good idea to add main()
at the bottom so you don’t forget later.
Our algorithm will be as follows:
Note the 3 major components of a program - input, computation, and output. They can be interleaved, as we will see as programs get more complex. You should stop and test your program after each completed step.
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:
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:
which outputs:
0
1
2
3
4
What is the output of this loop?
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:
Open loop.py
to get some practice writing loops. I have given you one loop that doesn’t quite do what we want. Can you fix the error?
Next, complete the two remaining tasks:
i
by adding 1 and squaring the value.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. Be careful to avoid errors due to integer division.
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 * (x − 1) * (x − 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
.
We will practice using various string operations today including indexing, concatenation, repetition, and length.
Open str_practice.py
to complete 4 tasks and a couple of extension if you desire. Be sure to incrementally develop; that is, complete one task, run your program to see if that task works, and then move on to the next. Tasks 4 and the bonus will require for loops and accumulators. Here is an example output with user input in yellow bold:
$ python3 str_practice_soln.py
Task 1:
Enter first name: David
Enter last name: Mauskop
Welcome David Mauskop
Task 2:
There are 12 characters in your name
Task 3:
Initials: D.M.
BONUS:
Last initials: d.p.
Task 4:
D
a
v
i
d
BONUS:
D
Da
Dav
Davi
David