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

Geo*_*ata 0 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()
Run Code Online (Sandbox Code Playgroud)

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

Anu*_*yal 5

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

if x < y:
    x, y = y, x
Run Code Online (Sandbox Code Playgroud)

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

您甚至可以通过使用bultin进一步获得快捷方式min,max并且可以在一行中完成,例如

x, y = max(x,y), min(x,y)
Run Code Online (Sandbox Code Playgroud)