4

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

提前致谢

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
4

3 回答 3

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
于 2013-05-25T16:00:09.300 回答
6

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

你需要做的是

user = int(user)

顺便说一句,这适用于您使用 int(user) 的所有地方

于 2013-05-25T15:48:23.313 回答
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
于 2013-05-25T15:59:36.597 回答