猜测游戏:将用户输入与随机生成的数字相匹配

时间:2017-04-26 18:26:08

标签: python python-3.x

 def var (guess):
    return guess


guess = int(input("Guess a number 1 through 10: "))
import random
num = (random.randint(1,10))

while True:
    try:
        guess = num
        print("you guessed the right number!")
        break
    except:
        print("try again")
        break

因此,对于这个程序,我试图找出如何让用户输入一个数字并猜出程序生成的数字(1到10)。似乎每次我输入一个值,它总是给我“你猜对了!”即使我输入的值高于10,也要输入字符串。

编辑:为什么有人会向我提出问题o_o

2 个答案:

答案 0 :(得分:0)

你需要在循环中获取用户的输入,以便每次迭代都能更新用户的输入。

import random
num = (random.randint(1,10))

while True:
    try:
        guess = int(input("Guess a number 1 through 10: "))
        if guess == num:
            print("you guessed the right number!")
            break
        else:
            print("try again")
    except:
        print('Invalid Input')

答案 1 :(得分:0)

try/except用于异常处理,不匹配值。你要找的是if个陈述,例如:

guess = int(input("Guess a number 1 through 10: "))
import random
num = (random.randint(1,10))
if guess == num:
    print("You guessed the right number!")
else:
    print("Try again")

我认为您可能打算继续循环,直到猜到正确的数字为止,在这种情况下,这将有效:

import random
num = (random.randint(1,10))
while True:
    guess = int(input("Guess a number 1 through 10: "))
    if guess == num:
        print("You guessed the right number!")
        break
    else:
        print("Try again")