while auction: print(logo) print("Welcome to the private bidding auction") # str.title():字符串方法,无参数。把每个单词首字母大写、其余小写,返回新字符串。 # 用在姓名上,输入 "tom smith" 会存成 "Tom Smith"。 name = input("What is your name?: ").title() # float():把输入的字符串转成小数,金额可能有 99.5 这种。 bid = float(input("How much would you like to bid?: $")) # 用“关键字实参”调用上面的函数,可读性好:一眼看出哪个值给哪个参数。 add_new_bidder(bidder_name = name, bidder_amount = bid)
others = input("Are there any other bidders for this auction? Type 'yes' or 'no'.n") if others == 'no': # 结束拍卖,开始算最高价。 auction = False highest_bidder = 0 count = -1 # 遍历列表里的每个字典,e 依次是 {"bid":…, "name":…} for e in auction_info: # e['bid'] 用键取金额,和 0 比较找出更大的。 if e['bid'] > highest_bidder: highest_bidder = e['bid'] # 作者想用 count 记录“最高价那位的下标”,但这个写法有 bug: # count 只在“出现新的最高价”时 +1,它数的是“刷新纪录的次数”, # 不是被刷新者的位置。只要最高价不是第一条,count 就会指错人。 # 安全写法:用 enumerate 同时拿下标,或直接记住 e 本身。 count += 1 # 用(可能错的)下标去取名字。 # 举例:三条记录 300 / 100 / 500 → 刷新纪录两次,count 从 -1 变到 1, # auction_info[1] 是 100 那位,于是“最高价那行金额”配了别人的名字。 winner = auction_info[count]['name'] print(f"The highest bidder is {winner} with a ${highest_bidder}") print("Thank you for your participation.") else: # 还有人要出价 → 清屏,别让后面的人看到前面的价格(盲拍)。 clear()
What is your name?: tom How much would you like to bid?: $100 Are there any other bidders for this auction? Type 'yes' or 'no'. yes ... The highest bidder is Bob with a $200.0
while auction: print(logo) print("Welcome to the private bidding auction") name = input("What is your name?: ").title() bid = float(input("How much would you like to bid?: $")) add_new_bidder(bidder_name = name, bidder_amount = bid)
others = input("Are there any other bidders for this auction? Type 'yes' or 'no'.n")
# 写法一:记录下标 highest_bidder, winner = 0, None for i, e in enumerate(auction_info): if e['bid'] > highest_bidder: highest_bidder, winner = e['bid'], e['name']
# 写法二:直接用 max winner_entry = max(auction_info, key=lambda x: x['bid'])