- math
- pi
- **
Solution: Calculations
In order to have the math operation work properly we had to put the addition in parentheses. Just as you would in math class.
examples/basics/rectangle_solution.py
width = 23 height = 17 area = width * height print("The area is ", area) # 391 circumference = 2 * (width + height) print("The circumference is ", circumference) # 80
In order to calculate the area and the circumference of a circle we need to have PI so we created a variable called
pi and put in 3.14 which is a very rough estimation. You might want to have a more exact value of PI.
examples/basics/circle_solution.py
r = 7 pi = 3.14 print("The area is ", r * r * pi) # 153.86 print("The circumference is ", 2 * r * pi) # 43.96
Python has lots of modules (aka. libraries, aka. extensions), extra code that you can import and start using.
For example it has a module called math that provides all kinds of math-related functions and attributes.
A function does something, an attribute just hold some value. More about this later.
Specifically it has an attribute you can call math.pi with the value 3.141592653589793. A much better proximation of PI.
In the following solution we used that.
- The documentation of the math module.
examples/basics/circle_math_solution.py
import math r = 7 print("The area is ", r * r * math.pi) # 153.9380400258998 print("The circumference is ", 2 * r * math.pi) # 43.982297150257104
The expression r * r might also bothered your eyes. Well don't worry in Python there is an operator to express exponential values
It is the double star: . This is how we can use it to say r-square: r 2.
examples/basics/circle_power_solution.py
r = 7 pi = 3.14 print("The area is ", r ** 2 * pi) # 153.86 print("The circumference is ", 2 * r * pi) # 43.96
I don't have much to say about the calculator. I think it is quite straight forward.
examples/basics/calc_solution.py
a = 3 b = 2 print(a+b) # 5 print(a-b) # 1 print(a*b) # 6 print(a/b) # 1.5