秘密拍卖程序For循环Bug求助:误判最后出价者为赢家
问题排查与修复
核心问题1:bids字典被重复初始化
你在ongoing_game的while循环里每次都执行bids={},这会导致每输入一个出价者,之前的出价记录就被清空,最后bids里永远只有最后一个人的数据,自然永远判定最后一个是赢家。要把bids={}移到ongoing_game循环外面,每次新拍卖开始时初始化一次即可。
核心问题2:多处缩进错误
if continuity=="no":的缩进不对,它属于ongoing_game循环内的代码,要和上面的continuity=input(...)保持同一缩进级别else: clear()的缩进要和对应的if对齐stuff函数里的print语句现在在for循环内部,每次遍历一个候选人就打印一次,应该移到for循环外面,等所有候选人遍历完再输出结果- 最后的
else: clear; print("Goodbye!")缩进错误,而且clear要加括号变成clear(),同时这个else要和外层的while newgame对齐
其他细节问题
winningbid=bid这里的bid是最后一次输入的出价变量,不是当前候选人的出价,应该改成winningbid=runner(runner已经转成整数)或者winningbid=bids[candidate]stuff函数定义放在while newgame循环里完全没必要,每次循环都会重新定义,移到循环外面更合理- 变量
winner和winningbid最好在函数里提前初始化,避免出现未定义的异常
修复后的完整代码
from replit import clear from art import logo def determine_winner(bids): nominee = 0 winner = "" winningbid = 0 for candidate in bids: runner = int(bids[candidate]) if runner > nominee: nominee = runner winner = candidate winningbid = runner print(f"The winner is {winner} with a bid of ${winningbid}.") newgame = True while newgame: clear() print(logo) print("Welcome to the secret auction program.") ongoing_game = True bids = {} # 移至此处,每次新拍卖初始化一次 while ongoing_game: name = input("What is your name?: ") bid = input("What is your bid?: ") bids[name] = bid continuity = input("Are there any other bidders? Type 'yes' or 'no'. ") if continuity == "no": ongoing_game = False else: clear() clear() determine_winner(bids) another = input("Do you want to hold another auction? Type 'yes' or 'no'. ") if another == "no": newgame = False else: clear() print("Goodbye!")
内容的提问来源于stack exchange,提问作者Spicy Pineapple
相关产品推荐
相关产品推荐

