2016-06-10 37 views
-2

在這段代碼中,我想創建10個隨機問題,但是如果操作符號(+, - 或*)是 - 那麼我想要第一個數字要大於第二個(所以答案會是積極的。但是,這似乎並沒有工作,因爲我得到的是「 - 」問題,其中y小於x。這個代碼的目的是針對y,r和Z都可以隨機生成的。使用while循環和random.randint(python 3.4.3)製作y> x

import random 
    name=input("What is you name: ") 
    x=0 
    d=0 
    op=['+','-','*'] 

    def easy(): 
     global x 
     global d 
     y=random.randint(1,12) 
     z=random.randint(1,12) 
     r=op[random.randint(0,2)] 
     if (r==1): 
      while (y<z): 
       y=random.randint(1,12) 

     answer=eval('{}{}{}'.format(y,r,z)) 
     question=int(input("What is {}{}{}?".format(y,r,z))) 
     if question==answer: 
      print("Correct") 
      x+=1 
     else: 
      print("Incorrect") 
     d+=1 
     while d<10: 
      easy() 
    easy() 

回答

0

你跟1比較r,但你的運營商已經分配了。與'-'而不是進行比較。

+0

非常感謝你 – Woli123

-1

試試這個:

import random 
name=input("What is you name: ") 
x=0 
d=0 
op=['+','-','*'] 

def easy(): 
    global x 
    global d 
    y=random.randint(1,12) 
    z=random.randint(1,12) 
    r=op[random.randint(0,2)] 
    if (r=='-'): # << change from if (r==1) 
     while (y<=z): # << what if z is 12? 
      print(y, z) 
      y=random.randint(1,12) 

    answer=eval('{}{}{}'.format(y,r,z)) 
    question=int(input("What is {}{}{}?".format(y,r,z))) 
    if question==answer: 
     print("Correct") 
     x+=1 
    else: 
     print("Incorrect") 
    d+=1 
    while d<10: 
     easy() 
easy() 
+0

謝謝,我會把你的建議納入考慮 – Woli123

+0

無論如何,好的工作和你的項目的好運。 –

0

而不是循環找到一對值,爲什麼不生成它們與所需的屬性?

import random as rnd 

smaller, larger = sorted([rnd.randint(1,11), rnd.randint(1,12)]) 
if larger == smaller: 
    larger += 1 

由於在範圍(1,11)中產生的第一個值,如果兩個值相等總有空間來增加其中的一個。