2014-10-10 196 views
-2

我的代碼存在一個奇怪的問題。當我只想要10個問題時,它提出了14次問題。那麼它也不是正確計算得分。任何幫助表示讚賞解決這兩個問題!在此先感謝隨機函數選擇

import random 
StudentName = input("Please enter you name: ") 


def question_a(): 
    score=0 
    num1=random.randint(1,10) 
    num2=random.randint(1,10) 
    num3=num1-num2 
    answer=int(input("What is "+str(num1)+"-"+str(num2)+"? ")) 
    if answer==num3: 
     print ("Well done, you are correct") 
     score=score+1 
    else: 
     print ("That is the wrong answer") 

    return score 

def question_b(): 
    score=0 
    num1=random.randint(1,10) 
    num2=random.randint(1,10) 
    num3=num1+num2 
    answer=int(input("What is "+str(num1)+"+"+str(num2)+"? ")) 
    if answer==num3: 
     score = score + 1 
     print ("Well done, you are correct") 
    else: 
     print ("That is the wrong answer") 

    return score 

def question_c(): 
    score=0 
    num1=random.randint(1,10) 
    num2=random.randint(1,10) 
    num3=num1*num2 
    answer=int(input("What is "+str(num1)+"*"+str(num2)+"? ")) 
    if answer==num3: 
     score = score + 1 
     print ("Well done, you are correct") 
    else: 
     print ("That is the wrong answer") 

    return score 


def question_d(): 
    score=0 
    num1=random.randint(1,10) 
    num2=random.randint(1,10) 
    num3=num1/num2 
    num4=round(num3,1) 
    answer=float(input("What is "+str(num1)+"/"+str(num2)+"? ")) 
    if answer==num4: 
     score = score + 1 
     print ("Well done, you are correct") 
    else: 
     print ("That is the wrong answer") 

    return score 

my_list=[question_a,question_b,question_c,question_d] 

for i in range (0,10): 
    random.choice(my_list)() 

final_score = (question_a() + question_b() + question_c() + question_d()) 

print(StudentName+", you scored "+str(final_score)+"/10.") 

回答

2

這條線:

random.choice(my_list)() 

調用10隨機函數:對。但忽略輸出:錯誤。

然後這一行:

final_score = (question_a() + question_b() + question_c() + question_d()) 

調用這些函數非隨機地,並增加了的結果。 10 + 4等於14次調用你的函數。

解決方案:

final_score = 0 
for i in range (0,10): 
    final_score += random.choice(my_list)() 

或者類似的東西。

+0

非常感謝羅德里戈,作品! – 2014-10-10 11:12:16