Python 5e – More Libraries

Clear the console with os and supercharge calculations with math.

Overview

In this section, we explore a couple of helpful Python libraries: os for interacting with the operating system and math for common mathematical operations.

Clear the Screen with os.system()

To clear the console, call the system command for your platform. Many online editors support clear, while Windows terminals use cls. Here’s a simple cross-platform approach:

import os

print("Hello")
# Try Windows first, then Unix-like:
os.system("cls" if os.name == "nt" else "clear")
print("Bye")

Note: Some offline editors (e.g. IDLE) may not clear the embedded shell even though the command runs.

Clear Screen Task – Trivia Questions

Create a three-question quiz. Clear the screen between questions and show the total score at the end.

import os

correct = 0

# Question 1
answer1 = input("What is the capital of France? ")
if answer1.lower() == "paris":
    correct += 1
os.system("cls" if os.name == "nt" else "clear")

# Question 2
answer2 = input("What is 5 + 7? ")
if answer2 == "12":
    correct += 1
os.system("cls" if os.name == "nt" else "clear")

# Question 3
answer3 = input("What is the color of the sky on a clear day? ")
if answer3.lower() == "blue":
    correct += 1
os.system("cls" if os.name == "nt" else "clear")

print("You got", correct, "correct!")

The math Library

The math module provides functions and constants for numeric work:

  • sqrt(x) – square root of x.
  • ceil(x) – smallest integer ≥ x (round up).
  • floor(x) – largest integer ≤ x (round down).
  • pi – the constant π.

Example: Square Root

from math import sqrt
answer = sqrt(64)
print(answer)  # 8.0

Example: Rounding with ceil and floor

from math import ceil, floor
answer = 65 / 8
print("True answer:", answer)
print("Rounded up:", ceil(answer))
print("Rounded down:", floor(answer))

Example: Area of a Circle

from math import pi
radius = 5.6
area = pi * (radius ** 2)
print("The area of the circle is", area)

Math Task – Area of a Sphere

Ask for the radius, compute the area using 4 × π × r², round down with floor(), and print the result.

from math import pi, floor
radius = float(input("Enter the radius: "))
area = 4 * pi * (radius ** 2)
print("The area of the sphere is", floor(area))