Geometry
A menu of shapes: perimeter and area of a rectangle, square, circle and right triangle. Teaches functions that return a value.
Open in Tokbit Level: Intermediate. Free in the browser, nothing to install, no account needed.
Run the example in Tokbit and step through it: before each step say what will happen and check it in the Variables panel. Then change it your way.
Flowchart
Python program
The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.
"""A menu of shapes: works out the perimeter and area of a rectangle, square, circle and right triangle. Teaches functions that return a value."""
from math import pi, sqrt
def read_size(label: str) -> float:
"""Prints the name of the size and reads until it is positive; returns it."""
x: float
while True:
print(label + ":", end="")
x = float(input())
if x <= 0:
print("The size must be greater than 0.")
if not (x <= 0):
break
return x
def rect_perimeter(a: float, b: float) -> float:
"""P = 2 · (a + b)"""
return 2 * (a + b)
def rect_area(a: float, b: float) -> float:
"""A = a · b"""
return a * b
def circle_perimeter(r: float) -> float:
"""C = 2 · π · r"""
return 2 * pi * r
def circle_area(r: float) -> float:
"""A = π · r²"""
return pi * r ** 2
def hypotenuse(a: float, b: float) -> float:
"""c = √(a² + b²)"""
return sqrt(a ** 2 + b ** 2)
option: str = ""
a: float
b: float
c: float
# The menu repeats until you choose 5.
while option != "5":
print("")
print("1 Rectangle")
print("2 Square")
print("3 Circle")
print("4 Right triangle")
print("5 Quit")
option = input("Choice:")
if option == "1":
a = read_size("Side a")
b = read_size("Side b")
print("Perimeter:", round(rect_perimeter(a, b), 2))
print("Area:", round(rect_area(a, b), 2))
else:
if option == "2":
# A square is a rectangle with equal sides: P = 4a, A = a².
a = read_size("Side")
print("Perimeter:", round(rect_perimeter(a, a), 2))
print("Area:", round(rect_area(a, a), 2))
else:
if option == "3":
a = read_size("Radius r")
print("Perimeter:", round(circle_perimeter(a), 2))
print("Area:", round(circle_area(a), 2))
else:
if option == "4":
a = read_size("Leg a")
b = read_size("Leg b")
# Triangle: P = a + b + c, A = a · b / 2.
c = hypotenuse(a, b)
print("Hypotenuse:", round(c, 2))
print("Perimeter:", round(a + b + c, 2))
print("Area:", round(a * b / 2, 2))
else:
if option != "5":
print("Unknown choice.")
Follow-up tasks
Tasks in which you change the example (with a model solution):