Program Function and Purpose
To “make” a program with function and purpose, you need to “plan” a program with function and purpose. Our Jupyter Notebook will show examples of the following.
Program with Output: Print Function
from emoji import emojize
print(emojize(":thumbs_up: Jayden and Will are awesome! :grinning_face:"))
👍 Jayden and Will are awesome! 😀
Program with Input and Output: Python Quiz
import getpass, sys
def question_with_response(prompt):
print("Question: " + prompt)
msg = input()
return msg
questions = 3
correct = 0
print('Hello, ' + getpass.getuser() + " running " + sys.executable)
print("You will be asked " + str(questions) + " questions.")
question_with_response("Are you ready to take a test?")
rsp = question_with_response("What is the best baby name?")
if rsp == "jayden":
print(rsp + " is correct!")
correct += 1
else:
print(rsp + " is incorrect!")
rsp = question_with_response("Does Will smell?")
if rsp == "yes":
print(rsp + " is correct!")
correct += 1
else:
print(rsp + " is incorrect!")
rsp = question_with_response("Who is the next president of the USA")
if rsp == "jayden chen":
print(rsp + " is correct!")
correct += 1
else:
print(rsp + " is incorrect!")
print(getpass.getuser() + " you scored " + str(correct) +"/" + str(questions))
Program with a List: Cool Kid List
# Define an empty List called InfoDb
InfoDb = []
InfoDB is a data structure with expected Keys and Values
Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
"FirstName": "Jayden",
"LastName": "Chen",
"DOB": "May 31, 2007",
"Residence": "San Diego",
"Email": "jaydenchen16@gmail.com",
"Cool?": ["Yes"]
})
Append to List a 2nd Dictionary of key/values
InfoDb.append({
"FirstName": "Will",
"LastName": "Bartelt",
"DOB": "September 25, 2006",
"Residence": "San Diego",
"Email": "willbartelt@gmail.com",
"Cool": ["Yes"]
})
Append to List a 2nd Dictionary of key/values
InfoDb.append({
"FirstName": "Howie",
"LastName": "Nguyen",
"DOB": "January 21, 2007",
"Residence": "San Diego",
"Email": "howien07@gmail.com",
"Cool?": ["Yes"]
})
Append to List a 3rd Dictionary of key/values
InfoDb.append({
"FirstName": "Nihar",
"LastName": "Gupta",
"DOB": "September 10, 2008",
"Residence": "San Diego",
"Email": "niharg@gmail.com",
"Cool?": ["Yes"]
})
Print the data structure
print(InfoDb)
Program with a Dictionary : Word Search
from PyDictionary import PyDictionary
#Initialize the PyDictionary
dictionary = PyDictionary()
#Function to fetch the meaning of a word
def fetch_meaning(word):
try:
meanings = dictionary.meaning(word)
if meanings:
for part_of_speech, definition_list in meanings.items():
print(f"{part_of_speech}:")
for definition in definition_list:
print(f" - {definition}")
else:
print(f"Meaning not found for '{word}'")
except Exception as e:
print(f"An error occurred: {e}")
#Simple CLI interface for word lookup
while True:
user_input = input("Enter a word to lookup (or 'exit' to quit): ").strip()
if user_input.lower() == 'exit':
break
fetch_meaning(user_input)
Program with Iteration: Cool Kid Convert Table
Define an empty List called InfoDb
InfoDb = []
InfoDB is a data structure with expected Keys and Values
Append to List a Dictionary of key/values related to a person and coolness
InfoDb.append({
"FirstName": "Jayden",
"LastName": "Chen",
"DOB": "May 31, 2007",
"Residence": "San Diego",
"Email": "jaydenchen16@gmail.com",
"Cool?": ["Yes"]
})
Append to List a 2nd Dictionary of key/values
InfoDb.append({
"FirstName": "Will",
"LastName": "Bartelt",
"DOB": "September 25, 2006",
"Residence": "San Diego",
"Email": "willbartelt@gmail.com",
"Cool?": ["Yes"]
})
Append to List a 2nd Dictionary of key/values
InfoDb.append({
"FirstName": "Howie",
"LastName": "Nguyen",
"DOB": "January 21, 2007",
"Residence": "San Diego",
"Email": "howien07@gmail.com",
"Cool?": ["Yes"]
})
Append to List a 3rd Dictionary of key/values
InfoDb.append({
"FirstName": "Nihar",
"LastName": "Gupta",
"DOB": "September 10, 2008",
"Residence": "San Diego",
"Email": "niharg@gmail.com",
"Cool?": ["Yes"]
})
Print the data structure
print(InfoDb)
This jupyter cell has dependencies on one or more cells above
print function: given a dictionary of InfoDb content
def print_data(d_rec):
print(d_rec["FirstName"], d_rec["LastName"]) # using comma puts space between values
print("\t", "Residence:", d_rec["Residence"]) # \t is a tab indent
print("\t", "Birth Day:", d_rec["DOB"])
print("\t", "Cool kid???: ", end="") # end="" make sure no return occurs
print(", ".join(d_rec["Cool?"])) # join allows printing a string list with separator
print()
for loop algorithm iterates on length of InfoDb
def for_loop():
print("For loop output\n")
for record in InfoDb:
print_data(record) # call to function
for_loop() # call to function
Program with a Function to perform mathematical and/or a statistical calculations: Average Calculator
Program with a Selection/Condition: x-value test
x = 100
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Finish with a Program with Purpose: Pacman
Program Design and Development
The following program calculates the average of numbers in a list using iteration:
# Define a list of numbers
numbers = [10, 20, 30, 40, 50]
# Initialize a variable to store the sum of numbers
total = 0
# Iterate through the list of numbers
for num in numbers:
# Add each number to the total
total += num
# Calculate the average by dividing the total by the number of elements in the list
average = total / len(numbers)
# Print the list of numbers
print("List of Numbers:", numbers)
# Print the sum of numbers
print("Sum of Numbers:", total)
# Print the average
print("Average:", average)
We start by defining a list of numbers called numbers.
We initialize a variable total to store the sum of the numbers, setting it to 0.
We use a for loop to iterate through each element in the numbers list. The variable num represents each number in the list during each iteration.
Inside the loop, we add each number to the total using the += operator.
After the loop has finished iterating through all the numbers, we calculate the average by dividing the total by the number of elements in the list, which is obtained using the len() function.
We print the list of numbers, the sum of numbers, and the calculated average to the console.
Identifying and Correct Errors
Bugged Program
menu = {"burger": 3.99,
"fries": 1.99,
"drink": 0.99}
total = 0
#shows the user the menu and prompts them to select an item
print("Menu")
for k,v in menu.items():
print(k + " $" + str(v)) #why does v have "str" in front of it?
#ideally the code should prompt the user multiple times
item = input("Please select an item from the menu")
#code should add the price of the menu items selected by the user
print(total)
Our New Program
menu = {
"burger": 3.99,
"fries": 1.99,
"drink": 0.99
}
bill = []
# Display the menu
print("Menu")
for item, price in menu.items():
print(f"{item}: ${price:.2f}")
while True:
item = input("Please select an item from the menu (or enter 'done' to finish): ").lower()
if item == 'done':
break
if item in menu:
bill.append(menu[item])
print(f"{item.capitalize()} added to the bill.")
else:
print("Invalid item. Please select an item from the menu or enter 'done' to finish.")
if bill:
total_cost = sum(bill)
print(f"Your total bill amount is: ${total_cost:.2f}")
else:
print("No items selected. Have a nice day!")
We start by defining a list of numbers called numbers.
We initialize a variable total to store the sum of the numbers, setting it to 0.
We use a for loop to iterate through each element in the numbers list. The variable num represents each number in the list during each iteration.
Inside the loop, we add each number to the total using the += operator.
After the loop has finished iterating through all the numbers, we calculate the average by dividing the total by the number of elements in the list, which is obtained using the len() function.
We print the list of numbers, the sum of numbers, and the calculated average to the console.