gpt4 book ai didi

Python 3.4 :While loop not looping

转载 作者:行者123 更新时间:2023-11-30 22:59:29 24 4
gpt4 key购买 nike

如果用户的猜测大于或小于随机生成的值,Python 循环不想循环。它要么退出循环,要么创建无限循环。我哪里出错了?

import random

correct = random.randint(1, 100)
tries = 1
inputcheck = True
print("Hey there! I am thinking of a numer between 1 and 100!")
while inputcheck:
guess = input("Try to guess the number! " )
#here is where we need to make the try statement
try:
guess = int(guess)
except ValueError:
print("That isn't a number!")
continue
if 0 <= guess <= 100:
inputcheck = False
else:
print("Choose a number in the range!")
continue
if guess == correct:
print("You got it!")
print("It took you {} tries!".format(tries))
inputcheck = False
if guess > correct:
print("You guessed too high!")
tries = tries + 1
if guess < correct:
print("You guessed too low!")
tries = tries + 1

if tries >= 7:
print("Sorry, you only have 7 guesses...")
keepGoing = False

最佳答案

问题出在这一行:

if 0 <= guess <= 100:
inputcheck = False

每当用户输入 0 到 100 之间的数字时,这都会终止循环。您可以将这部分重写为:

if not 0 <= guess <= 100:
print("Choose a number in the range!")
continue

关于Python 3.4 :While loop not looping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35738947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com