此代码:
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。
答案 0 :(得分:5)
您从未在while循环中更新userNumber
或randomNum
。因此,一旦满足循环条件,它将无限执行。
您需要将while循环更新为:
while userNumber != randomNum:
if userNumber > randomNum:
print ("lower")
else:
print("higher")
tries += 1
userNumber = int(input("please pick a number"))
答案 1 :(得分:3)
您忘记要求用户再次猜测。试试这个!
while userNumber != randomNum:
if userNumber > randomNum:
print("lower")
else:
print("higher")
tries += 1
userNumber = int(input("please pick a number")
答案 2 :(得分:0)
试试这个:
import random
print("Welcome to the guess my number program!")
randomnum = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100.")
print("Try to guess it in 5 attempts.")
tries = 0
usernumber = 0
while not usernumber == randomnum:
usernumber = int(raw_input("please pick a number.")
if usernumber > randomnum:
print("Too High")
if usernumber < randomnum:
print("Too Low")
tries = tries + 1
if usernumber == randomnum:
print("You got the number!")
print("It took you " + str(tries) + " attempts.")