如何确保第一个随机值总是大于第二个?

时间:2012-04-22 00:20:50

标签: python

代码:

def Division():

    print "************************\n""********DIVISION********\n""************************"
    counter = 0
    import random
    x = random.randint(1,10)
    y = random.randint(1,10)
    answer = x/y
    print "What will be the result of " + str(x) + '/' + str(y) + " ?"
    print "\n"
    userAnswer = input ("Enter result: ")
    if userAnswer == answer:
        print ("Well done!")
        print "\n"
        userInput = raw_input ("Do you want to continue? \n Enter 'y' for yes or 'n' for no.")
        if userInput == "y":
            print "\n"
            Division()
        else:
            print "\n"
            Menu()
    else:
        while userAnswer != answer:
            counter += 1
            print "Try again"
            userAnswer = input ("Enter result: ")
            if counter == 3: break
        userInput = raw_input ("Do you want to continue? \n Enter 'y' for yes or 'n' for no.")
        if userInput == "y":
            print "\n"
            Division()
        else:
            print "\n"
            Menu()

在这种情况下,我希望x值始终大于y值。我该怎么办? 减法代码类似,问题保持不变,目标是避免 否定结果。

3 个答案:

答案 0 :(得分:5)

您可以检查是否x < y并交换它们,例如

if x < y:
    x, y = y, x

请注意,在python中,您可以交换两个变量而无需临时变量。

您甚至可以通过使用bultin minmax进行更多快捷方式,并在一行中执行此操作,例如。

x, y = max(x,y), min(x,y)

答案 1 :(得分:2)

除了Anrag Uniyal的回答,你也可以试试这个:

y,x = sorted([x,y])

答案 2 :(得分:1)

您可以在x和10之间执行randint以获得大于x的数字:

x = random.randint(1,10)
y = random.randint(x,10)