3

这段代码:

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。

4

3 回答 3

5

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

您需要将 while 循环更新为:

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

    tries += 1    
    userNumber = int(input("please pick a number"))
于 2013-07-02T17:58:05.550 回答
3

您忘记让用户再次猜测。尝试这个!

while userNumber != randomNum:
    if userNumber > randomNum:
        print("lower")
    else:
        print("higher")
    tries += 1
    userNumber = int(input("please pick a number")
于 2013-07-02T17:59:20.060 回答
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.")
于 2014-04-27T14:03:27.713 回答