gpt4 book ai didi

python - 一个简单的python循环问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:01:57 24 4
gpt4 key购买 nike

这段代码:

import random
print("\tWelcome to the guess my number program\n")

print("im thinking of a number between 1 and 100")
print("try to guess it in 5 attempts\n")

randomNum = random.randint(1,101)

tries = 0

userNumber = int(input("please pick a number"))

while userNumber != randomNum:
if userNumber > randomNum:
print ("lower")
else:
print("higher")
tries += 1

print ("you guessed it! the number was" , randomNum)

出于某种原因,这会产生无限循环。任何帮助,我还在习惯 python。

最佳答案

您从未在 while 循环内更新您的 userNumberrandomNum。所以一旦满足循环条件,就会无限执行。

您需要将 while 循环更新为:

while userNumber != randomNum:
if userNumber > randomNum:
print ("lower")
else:
print("higher")

tries += 1
userNumber = int(input("please pick a number"))

关于python - 一个简单的python循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17432543/

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