如何在Python中从用户输入的游戏列表获取对应单价并计算总价
解决方法
你需要通过选中的游戏名称找到它在game_titles列表中的索引,再用该索引获取game_prices中对应的单价。另外要注意,当前你存入game_prices的是字符串类型,必须先转换成数值类型(比如float)才能进行乘法运算。
关键修改步骤
修正价格输入的类型转换
在输入价格时,直接将输入内容转为float类型,避免后续计算出错:print('Enter the price of each game (followed by ENTER on the keyboard):') for i in range(0, n): input_prices = float(input('$')) # 转换为浮点型 game_prices.append(input_prices)获取对应游戏单价并计算总价
在倒数第二行的位置,先通过index()方法找到游戏的索引,再取出对应单价计算总价:# 获取选中游戏的索引 game_index = game_titles.index(game_to_purchase) # 计算总价 total_price = num_copies * game_prices[game_index]修复库存打印逻辑
你原来的库存打印循环存在索引越界问题,改成以下方式可正确垂直展示每个游戏和价格:print('\nGAMES IN STOCK') for title, price in zip(game_titles, game_prices): print(f"{title} ${price:.2f}")优化总价输出格式
将总价格式化为两位小数,符合货币展示习惯:print(f'The total for {num_copies} of {game_to_purchase} is ${total_price:.2f}')
完整修正代码
# creating an empty list game_titles = [] game_prices = [] # number of elements as input n = int(input("Enter number of game titles (followed by ENTER on the keyboard): ")) # iterating till the range print('Enter the name of each game (followed by ENTER on the keyboard):') for i in range(0, n): input_names = input() # adding the element game_titles.append(input_names) print('Enter the price of each game (followed by ENTER on the keyboard):') for i in range(0, n): input_prices = float(input('$')) # 转换为浮点型 game_prices.append(input_prices) print('\nGAMES IN STOCK') # 正确打印每个游戏和对应价格 for title, price in zip(game_titles, game_prices): print(f"{title} ${price:.2f}") while True: try: game_to_purchase = str(input("Please enter the name of the game you would like to purchase: ")) except ValueError: print("Sorry, that game is not in stock. Please enter a game that is in stock:") continue if game_to_purchase not in game_titles: print("Sorry, that game is not in stock.\n") continue else: break while True: try: num_copies = int(input("Please enter the number of copies you would like to purchase (1-10): ")) except ValueError: print("Sorry, that was an invalid input. Please try again.") continue if num_copies > 10 or num_copies < 1: # 补充判断小于1的情况 print("Sorry, please enter a number between 1 and 10.\n") continue else: break # 获取对应游戏的单价并计算总价 game_index = game_titles.index(game_to_purchase) total_price = num_copies * game_prices[game_index] # 格式化输出总价 print(f'The total for {num_copies} of {game_to_purchase} is ${total_price:.2f}')
额外补充:在购买数量的判断中,新增了对小于1的输入限制,避免用户输入0或负数。
内容的提问来源于stack exchange,提问作者Spencer
相关产品推荐
相关产品推荐

