+
, -
, *
, /
//
**
, mod %
+
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:
atom
).cd
cd cs21/inclass/w01-intro
atom ./
python3 grad.py
Enter the current year: 2019
Enter your graduation year: 2022
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.
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.
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.
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()
Some math operators can be used with strings:
+
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!
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.
When more than one operator appears in an expression, which gets executed first depends on the rules of precedence. Python follows the following rules
2*(3-1)
is 4
, and (5-2)**(2+2)
is 81
.2**1+1
is 3
and not 4
, and 3*1**3
is 3
and not 27
.2*3-1
yields 5
rather than 4
, and 2//3-1
is -1
, not 1
(remember that in integer division, 2//3=0
).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.
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.
from math import pi, sin, cos, sqrt
once at the top of your program, even before the def main():
blocksqrt(64)
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