Python猜数字游戏问题:猜对数字后while循环未终止,求解决
解决猜数字游戏猜对后循环不终止的问题
你的问题出在猜对数字后没有终止while循环,所以即使猜对了,程序还会继续执行循环体内容,直到尝试次数用完。这里有两种简单的解决方法:
方法一:使用break语句直接终止循环
在猜对的分支里添加break,一旦猜对就跳出整个while循环:
secret_number = 9 attempts = 0 while attempts <= 2: guess = int(input("Guess: ")) if guess == secret_number: print("Yes you succeeded!") break # 猜对后立刻终止循环 else: print("You failed!") attempts = attempts + 1
方法二:用标志变量控制循环条件
定义一个布尔变量标记是否猜对,通过修改这个变量让循环条件不成立,从而终止循环:
secret_number = 9 attempts = 0 is_success = False while attempts <= 2 and not is_success: guess = int(input("Guess: ")) if guess == secret_number: print("Yes you succeeded!") is_success = True # 设置成功标记,循环条件不再满足 else: print("You failed!") attempts = attempts + 1
两种方法都能实现你要的“猜对后立即结束游戏”的效果,选哪种都可以。
内容的提问来源于stack exchange,提问作者Jahan Zaib
相关产品推荐
相关产品推荐

