2012-04-22 28 views
0

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

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价值更大。我该怎么做? 减法的代码是相似的,问题保持不变,目标是避免 的负面结果。

+1

没有你的问题不对,但对于将来的问题,考虑在遇到小问题时,不要让代码阅读。这很容易可能是“给定两个数字,你如何让x =小一个,y =大一个?” – 2012-04-22 00:53:27

回答

5

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

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

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

您甚至可以通过使用bultin minmax采取进一步的快捷方式,并在一行中执行操作,例如,

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

非常感谢Anurag Uniyal,我仍然在那里学习,因为我很高兴有像你这样的人准备好帮助那些寻求答案的人。 – Geostigmata 2012-04-22 00:43:39

+1

@Geostigmata欢迎您,如果您喜欢,您可以选择它作为答案。 – 2012-04-22 00:51:07

2

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

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

这也工作得很好!谢谢inspectorG4dget – Geostigmata 2012-04-22 00:48:57

+0

+1永远不会通过最小/最大的方式:) – 2012-04-22 00:51:38

+0

得到我的程序完成!谢谢你们 - 从来没有想过回应会如此迅速! :D – Geostigmata 2012-04-22 00:58:12

1

你可以x和10之间做randint获得大于x一个数字:

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

它可能并不重要,但请注意,这会微妙地改变值的分布。以x = 2,y = 3为例。在原始中,这种组合将以概率2(0.1 * 0.1)= 0.02(交换后x = 2且y = 3或x = 3且y = 2)发生。使用这种方法,它将以0.1 *(0.125)= 0.0125(x = 2,然后y = 3从3..10) – chepner 2012-04-22 01:31:07

相关问题