A6 - Subprograms
A common strategy in programming is to break our program up into small subtasks. We do this by creating small subprograms, which can be called upon to run at any time. Below is an example that creates five subprograms:
import random
def print_menu():
print("What do you want me to do?")
print("1. Count to 10")
print("2. Make you guess a secret word")
print("3. Calculate the area of a rectangle")
print("4. Exit")
def count_to_10():
for i in range(10):
print(i+1)
def guess_secret_word():
word = random.choice(["rock", "paper", "scissors"])
guess = input("Guess the secret word: ")
if guess == word:
print("Correct!")
else:
print(f"Wrong - the secret word was {word}")
def area_of_rectangle():
length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
area = length*width
print(f"The area is {area}")
def print_spacer():
print()
print("==================================")
print()
We define a subprogram like this:
Defining a subprogram, however, does nothing on its own. The code will only run when we trigger the subprogram by calling it. This is done by writing the name of the subprogram, followed by a set of open/close parentheses, like this:
Once we have subprograms defined, we can call them as many times as we'd like. Here's a completed version of the program started above, with the five subprograms followed by the main part of the program that will call each subprogram as needed:
import random
def print_menu():
print("What do you want me to do?")
print("1. Count to 10")
print("2. Make you guess a secret word")
print("3. Calculate the area of a rectangle")
print("4. Exit")
def count_to_10():
for i in range(10):
print(i+1)
def guess_secret_word():
word = random.choice(["rock", "paper", "scissors"])
guess = input("Guess the secret word: ")
if guess == word:
print("Correct!")
else:
print(f"Wrong - the secret word was {word}")
def area_of_rectangle():
length = int(input("Enter the length: "))
width = int(input("Enter the width: "))
area = length*width
print(f"The area is {area}")
def print_spacer():
print()
print("==================================")
print()
# Start of main program
choice = 0
while choice != 4:
print_spacer()
print_menu()
choice = int(input("Enter a choice [1-4]: "))
print_spacer()
if choice == 1:
count_to_10()
if choice == 2:
guess_secret_word()
if choice == 3:
area_of_rectangle()
Your Task
Create a file called a6.py for this assignment.
Start by pasting in this program, then customize it.
Change some of the menu options, and then based on that change the subprogram names and their implementations (ie, what they do).
For example, you could change area_of_rectangle() to area_of_cirlce() and get it to calculate the area of a circle.
Do this with at least two of the menu options.
Feel free to make any further tweaks you desire.
Alternatively, if you'd like, you can create your own program from scratch that makes use of subprograms.