猿问

Python中的数字猜谜游戏

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


提前致谢


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


Qyouu
浏览 221回答 3
3回答

眼眸繁星

当您转换为int(user)时,并没有将新的int保存为user。因此用户仍然是一个字符串。您需要做的是user&nbsp;=&nbsp;int(user)顺便说一句,这适用于您使用int(user)的所有地方

慕桂英4014372

这可以通过更简单的实现来完成:import randomnumber = random.randrange(10)for i in xrange(4):&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; user = int(raw_input('guess: '))&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; print 'must be int'&nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; if user == number:&nbsp; &nbsp; &nbsp; &nbsp; print 'bravo'&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; elif user < number:&nbsp; &nbsp; &nbsp; &nbsp; print 'greater'&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print 'lesser'print 'it was: %d' % number
随时随地看视频慕课网APP

相关分类

Python
我要回答