Python循环无法退出问题:选择'no'后如何终止程序循环?
秘密拍卖程序循环无法终止的问题修复
问题原因
你在函数blind_auction里直接赋值auction_stop = True时,Python会把它当成一个局部变量,而非修改全局作用域里的auction_stop变量。这就导致外层while循环的判断条件始终未被改变,循环会一直运行。
另外你原代码里把contin == "no"的判断放在了for循环内部,会导致遍历参与者时重复打印结果,这个逻辑也需要调整。
修复方案
方案1:用global声明修改全局变量
在函数内部明确告诉Python要使用全局的auction_stop变量:
print("Welcome to the secret auction program") auction_participants = {} auction_stop = False def blind_auction(name1, bid1, contin): global auction_stop # 声明使用全局变量 auction_participants[name1] = bid1 higher_participant = "" higher_price = 0 for price in auction_participants: if auction_participants[price] > higher_price: higher_price = auction_participants[price] higher_participant = price if contin == "no": auction_stop = True print(f"The winner is {higher_participant} with a bid of ${higher_price}") while not auction_stop: blind_auction(input("What is your name?: "), int(input("What's your bid?: $")), input("Are there any other bidders? Type 'yes' or 'no'."))
方案2:让函数返回终止状态(更推荐)
避免使用全局变量,让函数返回是否需要终止循环的布尔值,外层循环根据返回值更新状态:
print("Welcome to the secret auction program") auction_participants = {} auction_stop = False def blind_auction(name1, bid1, contin): auction_participants[name1] = bid1 higher_participant = "" higher_price = 0 for price in auction_participants: if auction_participants[price] > higher_price: higher_price = auction_participants[price] higher_participant = price if contin == "no": print(f"The winner is {higher_participant} with a bid of ${higher_price}") return True # 返回True表示终止循环 return False # 返回False继续循环 while not auction_stop: auction_stop = blind_auction(input("What is your name?: "), int(input("What's your bid?: $")), input("Are there any other bidders? Type 'yes' or 'no'."))
内容的提问来源于stack exchange,提问作者qazxsw301015
相关产品推荐
相关产品推荐

