Coding Fundamentals Python Exam 3 | Lab
Add Coffee Record
# This program adds coffee inventory records to # the coffee.txt file. def main(): # Create a variable to control the loop. another = 'y' # Open the coffee.txt file in append mode. coffee_file = open('coffee.txt', 'a') # Add records to the file. while another == 'y' or another == 'Y': # Get the coffee record data. print('Enter the following coffee data:') descr = input('Description: ') qty = int(input('Quantity (in pounds): ')) # Append the data to the file. coffee_file.write(f'{descr}\n') coffee_file.write(f'{qty}\n') # Determine whether the user wants to add # another record to the file. print('Do you want to add another record?') another = input('Y = yes, anything else = no: ') # Close the file. coffee_file.close() print('Data appended to coffee.txt.') # Call the main function. if __name__ == '__main__': main()
# This program saves a list of numbers to a file.
def main(): # Create a list of numbers. numbers = [1, 2, 3, 4, 5, 6, 7] # Open a file for writing. outfile = open('numberlist.txt', 'w') # Write the list to the file. for item in numbers: outfile.write(str(item) + '\n') # Close the file. outfile.close() # Call the main function. if __name__ == '__main__': main()
# This program calculates the average of the values # in a list.
def main(): # Create a list. scores = [2.5, 7.3, 6.5, 4.0, 5.2] # Create a variable to use as an accumulator. total = 0.0 # Calculate the total of the list elements. for value in scores: total += value # Calculate the average of the elements. average = total / len(scores) # Display the total of the list elements. print(f'The average of the elements is {average}.') # Call the main function. if __name__ == '__main__': main()
# This program demonstrates how the append # method can be used to add items to a list.
def main(): # First, create an empty list. name_list = [] # Create a variable to control the loop. again = 'Y' # Add some names to the list. while again.upper() == 'Y': # Get a name from the user. name = input('Enter a name: ') # Append the name to the list. name_list.append(name) # Add another one? print('Do you want to add another name?') again = input('y = yes, anything else = no: ') print() # Display the names that were entered. print('Here are the names you entered.') for name in name_list: print(name) # Call the main function. if __name__ == '__main__': main()
# This program demonstrates several string testing methods.
def main(): # Get a string from the user. user_string = input('Enter a string: ') print('This is what I found about that string:') # Test the string. if user_string.isalnum(): print('The string is alphanumeric.') if user_string.isdigit(): print('The string contains only digits.') if user_string.isalpha(): print('The string contains only alphabetic characters.') if user_string.isspace(): print('The string contains only whitespace characters.') if user_string.islower(): print('The letters in the string are all lowercase.') if user_string.isupper(): print('The letters in the string are all uppercase.') # Call the main function. if __name__ == '__main__': main()
# This program reads test scores from a CSV file # and calculates each student's test average.
def main(): # Open the file. csv_file = open('test_scores.csv', 'r') # Read the file's lines into a list. lines = csv_file.readlines() # Close the file. csv_file.close() # Process the lines. for line in lines: # Get the test scores as tokens. tokens = line.split(',') # Calculate the total of the test scores. total = 0.0 for score in tokens: total += float(score) # Calculate the average of the test scores. average = total / len(tokens) print(f'Average: {average}') # Execute the main function. if __name__ == '__main__': main()
# This program concatenates strings.
def main(): name = 'Carmen' print(f'The name is: {name}') name = name + ' Brown' print(f'Now the name is: {name}') # Call the main function. if __name__ == '__main__': main()
Reading a file
def read_grades_file(): while True: file_name = input("Please enter the file name to open: ") try: with open(file_name) as file: print(file.read()) break except FileNotFoundError: print("File not found. Please enter the correct file name: ")
# This program gets the user's first name, last name, and # student ID number. Using this data it generates a # system login name.
import login def main(): # Get the user's first name, last name, and ID number. first = input('Enter your first name: ') last = input('Enter your last name: ') idnumber = input('Enter your student ID number: ') # Get the login name. print('Your system login name is:') print(login.get_login_name(first, last, idnumber)) # Call the main function. if __name__ == '__main__': main()
# This program displays a simple pie chart.
import matplotlib.pyplot as plt def main(): # Create a list of sales amounts. sales = [100, 400, 300, 600] # Create a list of labels for the slices. slice_labels = ['1st Qtr', '2nd Qtr', '3rd Qtr', '4th Qtr'] # Create a pie chart from the values. plt.pie(sales, labels=slice_labels) # Add a title. plt.title('Sales by Quarter') # Display the pie chart. plt.show() # Call the main function. if __name__ == '__main__': main()
# This program displays a simple line graph.
import matplotlib.pyplot as plt def main(): # Create lists with the X and Y coordinates of each data point. x_coords = [0, 1, 2, 3, 4] y_coords = [0, 3, 1, 5, 2] # Build the line graph. plt.plot(x_coords, y_coords, marker='o') # Add a title. plt.title('Sales by Year') # Add labels to the axes. plt.xlabel('Year') plt.ylabel('Sales') # Customize the tick marks. plt.xticks([0, 1, 2, 3, 4], ['2016', '2017', '2018', '2019', '2020']) plt.yticks([0, 1, 2, 3, 4, 5], ['$0m', '$1m', '$2m', '$3m', '$4m', '$5m']) # Add a grid. plt.grid(True) # Display the line graph. plt.show() # Call the main function. if __name__ == '__main__': main()
Try Except Clause
try: choice = input("Enter your choice (a/b/c/d/e): ").lower() if choice not in ['a', 'b', 'c', 'd', 'e']: raise ValueError("Invalid choice. Please select a valid option from the menu.") if choice == 'a': miles_to_kilometers() elif choice == 'b': FahToCel() elif choice == 'c': GalToLit() elif choice == 'd': PoundsToKg() elif choice == 'e': InchesToCm() except ValueError as e: print(e) except Exception as e: print("An unexpected error occurred. Please try again.")
Writing name, grade into a file.
with open ("grades.txt", "w") as file: for name, grade in students.items(): file.write(f"{name}:{grade}\n")