# Announcements

• Lab 01 is posted and due Saturday night
• Quiz 01 will be in class at the start of Friday February 8th's class

# Today's Topics

• More on program design
• Math Operators
• +, -, *, /
• integer division //
• exponential **, mod %
• String concatenate +
• Precedence rules
• math library

# Designing a full program

Suppose we are given the following problem: Have the user enter the current year as a number and the year he or she plans to graduate and print how many more college years he/she has left. We want to design an algorithm that can solve this problem (this one is a bit easy) and then implement and test our solution in python.

Here are some steps a computer scientist might use to solve the problem:

1. First think about how you would solve the problem. no keyboards, mice, or even writing utensils. Just think.
2. Write or sketch a solution on paper. Discuss you solution with a friend or neighbor. This solution does not have to be in python. pseudocode is fine.
3. Write your solution in python using your editor (atom).
4. save, run, and test your solution. Go back and make changes if needed
cd
cd cs21/inclass/w01-intro
atom ./
Enter the current year: 2019
You have 3 year(s) until graduation

When you do write python code, it's good practice to comment. You've seen large Python comment blocks enclosed in triple-quotes. You can also provide a single-line of comment by using the # symbol.

# Programming Style

You will soon see in Python and other programming languages how to combine simple statements to create complex powerful code. This takes practice and experience. For example, consider the following snippet of code from last week:

# store user input in yearText as a string
yearText = input("Enter the current year: ")
# convert user input to int, save in year
year = int(yearText)

The first line calls input to ask the user of your program (i.e., the person who is running the python program you wrote) for a number. This gets returned by the input function as a string and stored in yearText. input always returns a string, even if it is supposed to represent a number. The second line converts the string value contained in yearText, converts it to an int, and saves the value in a variable called year.

It's possible to combine the code into a single line of python code

"""
get int from user, store in num
don't forget to convert from str to int
"""
year = int(input("Enter the current year: "))

Both snippets of code are legal Python. Which is better or preferable is a matter of taste. Our general advice to use the former 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. 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 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 algebra 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. >>> hw = "hello" + "world!" >>> print(hw) helloworld! 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. 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. # import math library 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 = πr2 (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