Python中的数字猜测游戏

时间:2013-05-25 15:39:13

标签: python random

我试图创建一个简单的随机数猜谜游戏。问题是即使我输入正确的数字,它回答“数字小于”。有人可以为我提供解决方案吗?

提前致谢

import random
import sys

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
user = raw_input('Guess The Number\n Pick between 1 - 10\n >>> ')
try:
    int(user)
except:
    print "Numbers Only !"
    sys.exit(0)
number = random.choice(numbers)
int(number)
for i in range(0, 4):
    if number == user:
        print 'You Won!'
    if user > number:
        print 'The number is less than', user
        user = raw_input('>>> ')
        try:
            int(user)
        except:
            print "Numbers Only !"
    if user < number:
        print 'The number is bigger than', user
        user = raw_input('>>> ')
        int(user)

print "The Number was", number

3 个答案:

答案 0 :(得分:12)

最大的问题是您没有将转化保存到int,因此您将猜测用作用户输入的字符串。您需要通过执行user = int(raw_input('>>>'))

来保存它

但是,还有其他方法可以改进此代码。你重复了一下,并且你不需要random.choice,你可以使用random.randrange(1, 10)

你不应该只说except:。你想要抓住你想要的例外。您正在寻找的特殊例外是ValueError

此外,我建议您让用户在输入不是数字的内容时再试一次。你可以将整个事物包含在它自己的功能中。

import random

def get_user_num(msg='>>> '): 
    """Print the msg parameter as a prompt for the user to enter a number.  If
    they enter an invalid string, reprompt them until they enter a number.

    """
    while True: 
        try: 
            return int(raw_input(msg)) # save the conversion to int
        except ValueError: # only except the error you're actually looking for
            print 'Numbers Only!' 

# 'from 1-9' is probably better than 'between 1-10'
user = get_user_num('Guess The Number\n Pick from 1-9\n>>> ') 
number = random.randrange(1, 10) # <- numbers list is unnecessary
#int(number) # this conversion was never needed, it was already a number

for _ in range(4):  # you don't need (0, 4), 0 is assumed 
    if number == user:
        print 'You Won!' # the correct number has been guessed
        break # exit the loop once the number has been correctly guessed
    elif user > number:
        print 'The number is less than', user
    elif user < number:
        print 'The number is bigger than', user

    # Don't repeat yourself, put this outside the `if`s
    user = get_user_num()
else:
    #only print the answer when it wasn't guessed correctly
    print "The Number was", number

答案 1 :(得分:6)

转换为int(用户)时,不会将新int保存到用户。所以用户仍然是一个字符串。

您需要做的是

user = int(user)

顺便说一句,这适用于使用int(user)

的所有地方

答案 2 :(得分:3)

这可以通过更简单的实现来完成:

import random

number = random.randrange(10)
for i in xrange(4):
    try:
        user = int(raw_input('guess: '))
    except ValueError:
        print 'must be int'
        continue
    if user == number:
        print 'bravo'
        break
    elif user < number:
        print 'greater'
    else:
        print 'lesser'
print 'it was: %d' % number