# ========================================================= # File: text_menu_example.py # 2015-04-16 by A. Ortiz, ITESM CEM. # # This program demonstrates how to write a text-based # application with a menu that contains several options # for the user. Requires Python 3. # ========================================================= #---------------------------------------------------------- def average(a): """Calculate the arithmetic mean of the list of numbers contained in a. """ return sum(a) / len(a) #---------------------------------------------------------- def compute_average(): """User interface for computing the average of some numbers typed by the user. Prints the average using two decimals of precision after the point. """ print("\nCOMPUTE AVERAGE") print("---------------") n = int(input("How many numbers? ")) a = [] for i in range(n): x = float(input("Give me number: ")) a.append(x) print("Average is:", round(average(a), 2)) #---------------------------------------------------------- def fact(n): """Calculate the factorial of n. n! = (1)(2)(3)...(n - 1)(n) """ a = 1 for i in range(1, n + 1): a *= i return a #---------------------------------------------------------- def compute_factorial(): """User interface for computing the factorial of a number typed by the user. """ print("\nCOMPUTE FACTORIAL") print("-----------------") x = int(input("Give me number: ")) print("Factorial of", x, "is", fact(x)) #---------------------------------------------------------- def main(): """Main program menu to select the user options. """ while True: print("\nMENU") print("====") print("1. Compute the average of numbers") print("2. Compute a factorial") print("3. Quit") option = int(input("Choose an option: ")) if option == 1: compute_average() elif option == 2: compute_factorial() elif option == 3: break main() # Start program.