我试图猜测python中的数字游戏,但每当我猜它重复4次'你的猜测太低了'
import random
number = random.randint(1, 20)
guessestaken = 0
print('I am thinking of a number between 1 and 20 ')
guess = raw_input('Take a guess and hit enter')
while guessestaken < 4:
guessestaken = guessestaken + 1
if guess > number:
print('your number is too low')
if guess < number:
print('your number is too high ')
if guess == number:
break
print('well done the number was ' + number + ' and you got it in ' + guessestaken + '')
答案 0 :(得分:1)
您在while循环之前要求输入用户。
guess = int(raw_input('Take a guess and hit enter'))
此声明应位于while块内。
函数raw_input返回一个字符串,您应该将其转换为整数。您可以在Documentation。
中详细了解相关信息答案 1 :(得分:0)
在您进入循环之前,您只要求用户输入一次。在循环的每次迭代之后,您将需要询问用户新的输入,否则猜测将永远不会改变!
此外,当您使用raw_input读取用户的某些输入时,它将是一个字符串。您需要将其强制转换为int。 接下来,如果循环中断,则不会调用它后面的语句。这意味着当用户得到正确的答案时,您需要将break语句移动到输出之后,否则将不会打印任何内容。 最后,if语句中的逻辑是向后的,如果猜测小于你生成的数字,那么猜测太低,不会太高!总而言之:
import random
number = random.randint(1, 20)
guessestaken = 0
print('I am thinking of a number between 1 and 20 ')
while guessestaken < 4:
guess = int(raw_input('Take a guess and hit enter'))
guessestaken = guessestaken + 1
if guess < number:
print('your number is too low')
if guess > number:
print('your number is too high ')
if guess == number:
print('well done the number was ' + number + ' and you got it in ' + guessestaken + '')
break
答案 2 :(得分:0)
你需要让用户在你的循环中输入,否则你只是多次比较他的第一个猜测。此外,您应该将输入值转换为整数,因为raw_input返回一个字符串。
>>> guess = raw_input('guess the number> ')
>>> type(guess)
<type 'str'>
>>> type(int(guess))
<type 'int'>
答案 3 :(得分:0)
来自随机进口randint
print("you wanna guess a number between A to B and time of guess:")
A = int(input("A:"))
B = int(input("B:"))
time = int(input("time:"))
x = randint(1, 10)
print(x)
while time != 0:
num = int(input("Enter: "))
time -= 1
if num == x:
print("BLA BLA BLA")
break
print("NOPE !")
if time == 0:
print("game over")
break