2016-06-28 27 views
-2

最好的數學測驗我目前是:如何在python 2中使用隨機數字編寫數學測驗?

answer = '' 
while not (answer == '75'): 
answer = raw_input('What is 5 x 15? ') 
if answer == '75': 
    print ' ' 
    print 'You are correct' 

    answer1 = '' 
    while not (answer1 == '72'): 
     answer1 = raw_input('What is 8 x 9? ') 
     if answer1 == '72': 
      print ' ' 
      print 'You are correct' 

      answer2 = ' ' 
      while not (answer2 == '0'): 
       answer2 = raw_input('What is 5 x 0? ') 
       if answer2 == '0': 
        print' ' 
        print'You are correct' 

        answer3 = '' 
        while not (answer3 == '18'): 
         answer3 = raw_input('what is 6 x 3? ') 
         if answer3 == '18': 
          print '' 
          print 'You are correct' 
         else: 
          print 'You are incorrect' 
       else: 
        print'You are incorrect' 
     else: 
      print 'You are incorrect' 
      continue 
else: 
    print 'You are incorrect' 
    continue 

對我來說,至少,它認爲這個代碼是太長只有4回答的問題。我想知道是否有一種更簡單的方法來用隨機數字進行數學測驗,因此您不必創建每個問題。

+1

如果這是您認爲可以改進的**工作代碼**,請參閱[codereview.se]。你絕對可以簡化它,並且絕對會產生隨機問題。 – jonrsharpe

+2

你顯然是在學習,所以可能給你的解決方案會比傷害更多。所以只是指出一個方向:爲什麼沒有問題和答案的列表呢? –

+0

提示@ tomasz-plaskota給你的答案是清理這一噸的關鍵。 – Jeff

回答

1

可以動態生成類似這樣的問題:

from random import randint 
q = '' 
while not q.capitalize() == 'N': 
    num1 = randint(0, 100) 
    num2 = randint(0, 100) 
    answer = input("What is " + str(num1) + " x " + str(num2) + " ? ") 
    if answer == (num1 * num2): 
     print "Correct" 
    else: 
     print "Incorrect" 

    q = raw_input("Do you want to continue: Y/N? ") 

在您的測驗只有三件事情被改變,他們是num1num2其結果改變answer。這意味着您可以重新使用其他所有內容並隨機生成num1num2

相關問題