"""Mini movie calculator.""" import pandas import random from datetime import date # functions go here def show_instructions(): """Print instructions when function called.""" print('''\n *** Instructions *** For each ticket, enter: - The person's name (cannot be blank) - The age (must be between 12 and 120) - Payment method (cash or credit) When you have entered all users, type 'xxx' to quit. The program will then display the ticket details, including the cost of each ticket, the total cost, and the total profit. This info will also be automatically written to a text file. ''') def num_check(question): """Check that something is a number.""" while True: try: response = int(input(question)) return response except ValueError: print("Please enter an integer.") def calc_ticket_price(var_age): """Calculate ticket price based on age.""" # ticket is $7.50 for users under 16 if var_age < 16: price = 7.5 # ticket is $10.50 for users inbetween 16 and 64 elif var_age < 65: price = 10.5 # ticket is $6.50 for seniors 65+ else: price = 6.5 return price def string_checker(question, num_letters, valid_responses): """Check that users enter a valid response. (eg yes / no / cash / credit based on a list of options. """ error = "Please choose {} or {}".format(valid_responses[0], valid_responses[1]) if num_letters == 1: short_version = 1 else: short_version = 2 while True: response = input(question).lower() for item in valid_responses: if response == item[:short_version] or response == item: return item print(error) def currency(x): """Currency formatting function.""" return "${:.2f}".format(x) # main routine starts here # set maximum number of tickets below MAX_TICKETS = 5 tickets_sold = 0 yes_no_list = ["yes", "no"] payment_list = ["cash", "credit"] # dictionaries to hold ticket details all_names = [] all_ticket_costs = [] all_surcharge = [] mini_movie_dict = { "Name": all_names, "Ticket Price": all_ticket_costs, "Surcharge": all_surcharge } # instructions want_instructions = string_checker( "Do you want to read the instructions (y/n): ", 1, yes_no_list) print("You chose", want_instructions) if want_instructions == "yes": show_instructions() # loop to sell tickets tickets_sold = 0 while tickets_sold < MAX_TICKETS: name = input("Please enter your name or 'xxx' to quit: ") if name == 'xxx' and len(all_names) > 0: break elif name == 'xxx': print("You must sell at least ONE ticket before quitting") continue age = num_check("Age: ") if 12 <= age <= 120: pass elif age < 12: print("Sorry you are too young for this movie") continue else: print("?? That looks like a typo, please try again.") continue # calculate ticket cost ticket_cost = calc_ticket_price(age) print("Age: {}, Ticket price: ${:.2f}".format(age, ticket_cost)) # get payment method pay_method = string_checker( "Choose a payment method (cash / credit): ", 2, payment_list) print("You chose", pay_method) if pay_method == "cash": surcharge = 0 else: # calculate 5% surcharge if they are paying by card surcharge = ticket_cost * 0.05 tickets_sold += 1 all_names.append(name) all_ticket_costs.append(ticket_cost) all_surcharge.append(surcharge) mini_movie_frame = pandas.DataFrame(mini_movie_dict) # mini_movie_frame = mini_movie_frame.set_index('Name') # Calculate the total ticket cost (ticket + surcharge) mini_movie_frame['Total'] = mini_movie_frame['Surcharge'] \ + mini_movie_frame['Ticket Price'] # Calculate profit per ticket mini_movie_frame['Profit'] = mini_movie_frame['Ticket Price'] - 5 # Calculate totals total = mini_movie_frame['Total'].sum() profit = mini_movie_frame['Profit'].sum() # choose winner and check total won winner_name = random.choice(all_names) win_index = all_names.index(winner_name) total_won = mini_movie_frame.at[win_index, 'Total'] # currency formatting add_dollars = ['Ticket Price', 'Surcharge', 'Total', 'Profit'] for var_item in add_dollars: mini_movie_frame[var_item] = mini_movie_frame[var_item].apply(currency) # set index at end mini_movie_frame = mini_movie_frame.set_index('Name') today = date.today() day = today.strftime("%d") month = today.strftime("%m") year = today.strftime("%Y") heading = "---- Mini Movie Fundraiser Ticket Data ({}/{}/{}) ----\n"\ .format(day, month, year) filename = "MMF_{}_{}_{}".format(year, month, day) # change frame to string (so we can export it to file) mini_movie_string = pandas.DataFrame.to_string(mini_movie_frame) # create strings for printing ticket_cost_heading = "\n----- Ticket Cost / Profit -----" total_ticket_sales = "Total Ticket Sales: ${:.2f}".format(total) total_profit = "Total Profit: ${:.2f}".format(profit) if tickets_sold == MAX_TICKETS: sales_status = "\n*** All the tickets have been sold ***" else: sales_status = "\n*** You have sold {} out of {} tickets. ***"\ .format(tickets_sold, MAX_TICKETS) winner_heading = "\n---- Raffle Winner ----" winner_text = "The winner of the raffle is {}. " \ "They have won ${:.2f}. ie : Their ticket is " \ "free!".format(winner_name, total_won) to_write = [heading, mini_movie_string, ticket_cost_heading, total_ticket_sales, total_profit, sales_status, winner_heading, winner_text] for item in to_write: print(item) write_to = "{}.txt".format(filename) text_file = open(write_to, "w+") for item in to_write: text_file.write(item) text_file.write("\n") text_file.close()