Python 5e - More Libraries
Clear Screen
Importing the os library and using the .system() command with the "clear" parameter will clear the screen.
The console won't clear on offline editors like IDLE but will work with many online editors like Replit.
import os
print("Hello")
os.system("clear")
print("Bye")
Bye
Practice Task 1
Ask three trivia questions to the user and clear the screen between each one. You should display the total they got correct atfter the third question.
Example solution:
Question One
What is the smallest planet? Mercury
Correct! Moving on to question two...
Question Two
How many moons does Neptune have? 7
Incorrect! Moving on to question three...
The Math Library
The math libraries contains several commands used for numbers:
-
sqrt to find the square root of a number.
-
ceil to round a decimal up to the nearest whole number and floor to round down to the nearest whole number.
-
pi to generate the value of pi (π).
The sqrt command will find the square root of a number or variable placed in the brackets and return it as a decimal number.
from math import sqrt
answer = sqrt(64)
print(answer)
8.0
The ceil command rounds a decimal up to the nearest integer and the floor command rounds a decimal down to the nearest integer.
from math import ceil, floor
answer = 65 / 8
print("True answer:" , answer)
print("Rounded up:" , ceil(answer))
print("Rounded down:" , floor(answer))
True answer: 8.125
Rounded up: 9
Rounded down: 8
The pi command generates a pi value accurate to 15 decimal places. Pi is used for many mathematical calculations involving circles.
The area of a circle is pi x radius².
The first example below uses 5.6 as the radius.
from math import pi
radius = 5.6
area = pi * (radius * radius)
print("The area of the circle is" , area)
The area of the circle is 98.5203456165759
The example below uses an input to allow the user to enter a decimal (float) number for the radius. It also uses the ceil command to round the area up.
from math import pi, ceil
radius = float(input("Enter the radius: "))
area = pi * (radius * radius)
print("The area of the circle is" , ceil(area))
Enter the radius: 2.3
The area is 17
Practice Task 2
The formula of a sphere is 4 x π x r² where π represents pi and r is the radius. Use an input line to enter the radius and then calculate the area of the sphere. Round the answer down to the nearest integer and print it.
Example solution:
Enter the radius: 7.1
The area of the sphere is 633