Maths with Python
Maths with Python
Challenges 27 - 34
Maths
Explanation
Python can perform several mathematical functions, but these are only available when the
data is treated as either an integer (a whole number) or a floating-point (a
number with a decimal place). If data is stored as a string, even if it only contains numeric
characters, Python is unable to perform calculations with it (see page 24 for a fuller
explanation).
Example Code
Please note: In order to use some of the mathematical functions (math.sqrt(num)
and math.pi) you will need to import the maths
library at the start of your program. You do this by print(round(num,2))
typing import math as the first line of your Displays a number rounded to
program. two decimal places.
** math.sqrt(num)
To the power of The square root of a number, but you must have the line import
(e.g. 102 is 10**2). math at the top of your program for this to work.
math.pi
Gives you pi (π) to 15 decimal places,
but you must have the line import
math at the top of your program for
this to work.
x // y
Whole number division (e.g.15//2 gives
the answer 7).
x % y
Finds the remainder (e.g. 15%2 gives
the answer 1).
32 Challenges 27 - 34: Maths
Challenges
027 028
Ask the user to enter a Update program 027 so that it will display the answer to
number with lots of two decimal places.
decimal places. Multiply
this number by two and
029
display the answer.
Ask the user to enter an integer that is over 500. Work
out the square root of that number and display it to two
030 decimal places.
Display pi (π) to five
decimal places. 031
Ask the user to enter the radius of a circle
(measurement from the centre point to the edge). Work
out the area of the circle (π*radius2).
032 033
Ask for the radius and the depth of a cylinder Ask the user to enter two numbers.
and work out the total volume (circle Use whole number division to divide
area*depth) rounded to three decimal the first number by the second and
also work out the remainder and
places.
display the answer in a user-friendly
way (e.g. if they enter 7 and 2 display
“7 divided by 2 is 3 with 1
remaining”).
034
You are
Display the following message:
starting to
think like a
programmer.