我的随机数生成器出了什么问题。 (蟒蛇)

时间:2015-11-15 00:53:33

标签: python random numbers generator

我是python的新手。我试图制作一个随机的#generator,但除了else语句之外什么都没有用。我不知道问题是什么。请帮助!

import random
randomNum = random.randint(1, 10)
answer = int(raw_input("Try to guess a random number between 1 and 10. "))

if (answer > randomNum) and (answer < randomNum):
    if (answer == randomNum + 1):
        print "Super Close"
        print randomNum
    elif (answer == randomNum + 2):
        print "Pretty Close"
        print randomNum
    elif (answer == randomNum + 3):
        print "Fairly Close"
        print randomNum
    elif (answer == randomNum + 4):
        print "Not Really Close"
        print randomNum
    elif (answer == randomNum + 5):
        print "Far"
        print randomNum
    elif (answer == randomNum - 5):
        print "Far"
        print randomNum
    elif (answer == randomNum - 4):
        print "Not Really Close"
        print randomNum
    elif (answer == randomNum - 3):
        print "Fairly Close"
        print randomNum
    elif (answer == randomNum - 2):
        print "Pretty Close"
        print randomNum
    elif (answer == randomNum - 1):
        print "Super Close"
        print randomNum
else:
    print "Good Job!"
    print randomNum

2 个答案:

答案 0 :(得分:2)

您的第一个if语句逻辑不正确。 answer 同时小于和大于randomNum,但这是您的测试所要求的。

如果or值大于小于and,则您希望使用answer代替randomNum

if (answer > randomNum) or (answer < randomNum):

或只是使用!=来测试不平等:

if answer != randomNum:

答案 1 :(得分:0)

我将此代码用于我的随机数生成器并且它有效,我希望它有帮助 您可以更改要生成的最高和最低随机数(0,20)

import random

maths_operator_list=['+','-','*']
maths_operator = random.choice(maths_operator_list)
number_one = random.randint(0,20)
number_two = random.randint(0,20)
correct_answer = 0

print(str(number_one), str(maths_operator), number_two)

if maths_operator == '+':
    correct_answer = number_one + number_two
elif maths_operator == '-':
    correct_answer = number_one - number_two
elif maths_operator == '*':
    correct_answer = number_one * number_two

print(correct_answer)