2015-02-24 53 views
0

我希望我的問題始終處於隨機狀態,但他們不斷重複。除此之外,如果答案不正確,更正用戶的if語句仍然會糾正用戶的錯誤。Python - 隨機問題繼續重複

FirstNo=random.randint(1,12) 
SecondNo=random.randint(1,12) 
ops=[['+', operator.add], ['-', operator.sub], ['*', operator.mul]] 
op=random.choice(ops) 

for i in range(1,11): 
    print('Question '+str(i)) 
    pupilAns=input('What is '+str(FirstNo)+str(op[0])+str(SecondNo)+'? ') 
    realAns=op[1](FirstNo, SecondNo) 
    if pupilAns==realAns: 
     score=score+1 
     print('Well Done '+FN+'!') 
    else: 
     print("Wrong Answer "+FN+'. It was '+str(realAns)) 

下面是完整的代碼

import random 
import operator 
score=0 #Score for Quiz 

FN=input(str('What is your First Name:')) 
while FN=='': 
    FN=input(str('Please enter your First Name:')) 
    DigitFound=True 
    while DigitFound==True: 
     FN=input(str('Please enter your First Name:')) 
     for digit in FN: 
      if digit.isdigit(): 
       DigitFound=True 
       break 
      else: 
       DigitFound=False 

LN=input(str('What is your Last Name:')) 
while LN=='': 
    LN=input(str('Please enter your Last Name:')) 
    DigitFound=True 
    while DigitFound==True: 
     LN=input(str('Please enter your Last Name:')) 
     for digit in LN: 
      if digit.isdigit(): 
       DigitFound=True 
       break 
      else: 
       DigitFound=False 

Status=False 
CN=input('What is your Class Name? Class 1, Class 2, or Class 3:') 
while Status==False: 
    if CN=='Class 1' or CN=='Class 2' or CN=='Class 3': 
     Status=True #Break out of the loop and continue to the quiz 
    else: 
     CN=input('What is your Class Name? Class 1, Class 2, Class 3:') 

FirstNo=random.randint(1,12) 
SecondNo=random.randint(1,12) 
ops=[['+', operator.add], ['-', operator.sub], ['*', operator.mul]] 
op=random.choice(ops) 

for i in range(1,11): 
    print('Question '+str(i)) 
    pupilAns=input('What is '+str(FirstNo)+str(op[0])+str(SecondNo)+'? ') 
    realAns=op[1](FirstNo, SecondNo) 
    if pupilAns==realAns: 
     score=score+1 
     print('Well Done '+FN+'!') 
    else: 
     print("Wrong Answer "+FN+'. It was '+str(realAns)) 
+0

您種子()? – zubergu 2015-02-24 11:28:11

回答

0

爲避免重複提出您的問題,您應該在for - 循環中將random.randintrandom.choice調用放入。 Python中的函數(以及其他語言afaik)在調用時進行評估,因此變量FirstNo,SecondNoop都填充了它們各自函數返回的值。

然後,在for -loop的每次迭代中,值都不會改變。所以他們保持不變。

+1

謝謝你的幫助。 – UserIsMe 2015-02-24 11:45:16

2

您需要選擇您的循環內的隨機數。你所做的只是選擇一次隨機數,然後問這個問題10次。

1

其他人已經回答了爲什麼這個問題不是隨機的,所以我不會解決你的問題的那部分。

你得到"Wrong Answer "...打印,即使用戶提供了正確的答案,因爲你是一個比較字符串以數字:pupilAns是一個字符串,但realAns是一個整數。因此,在執行if pupilAns==realAns:測試之前,您需要將pupilAns轉換爲int,或將realAns轉換爲str。如果pupilAns不能轉換爲int,我可能會做前者,並打印出錯信息。

+0

唉!它的工作原理,感謝您的幫助。 – UserIsMe 2015-02-24 11:44:58