2015-04-03 78 views
-2

我需要幫助打開文本文件。出於某種原因,它似乎沒有正常工作,我想知道是否有人能指出任何錯誤並告訴我如何解決它們。謝謝。需要幫助打開/創建文本文件

import time 
import operator 
import random 

username=input("What is your name?") 

usersClass = input("Which class are you in, 1, 2 or 3?") 
print ("Welcome {} to the Math quiz, hope you have fun lets begin".format(username)) 

start = time.time() 

def askquestion(): 
    score = 0 
    opslist = {operator.add: "+", operator.sub: "-", operator.mul: "x"} 
    num1,num2 = random.randint(1,10), random.randint(1,10)  
    ops = random.choice(list(opslist.keys()))      
    ActualAnswer = (ops(num1,num2))        
    score = 0 
    print(num1,opslist[ops],num2)    
    userAns = (int(input("Answer the above"))) 
    if userAns == ActualAnswer: 
    print("Awesome, that's correct") 
    return 1 
    else: 
    print("Incorrect sorry") 
    score = score - 0 
    return 0 

totalScore = 0 
for i in range (10): 
    totalScore += askquestion() 

print ("Well done, you have completed the quiz") 

print("your final score was " + str(totalScore)) 
if totalScore > 9: 
    print("Great work! You got top marks!") 
elif totalScore > 7: 
    print("Good, try harder next time and you might get full marks!") 
elif totalScore > 5: 
    print("You did alright") 
elif totalScore > 4: 
    print("Are you not motivated.. c'mon") 
else: 
    print("Hmmm..dissapointing, however know you know what you need to work on") 

end = time.time() 
etime = end - start 
timeTaken = round(etime) 

if usersClass == 1: 
    with open("class1.txt","a+") as f: 
     f.write("{}:Scored {} in {} seconds".format(username,totalScore,timeTaken)) 

elif usersClass == 2: 
    with open("class2.txt","a+") as f: 
     f.write("{}:Scored {} in {} seconds".format(username,totalScore,timeTaken)) 

elif usersClass == 3: 
    with open("class3.txt","a+") as f: 
     f.write("{}:Scored {} in {} seconds".format(username,totalScore,timeTaken)) 
+3

「無法正常工作」沒有幫助。 *發生了什麼,你會得到什麼錯誤? – Andy 2015-04-03 14:07:56

+0

我的代碼的最後部分從usersclass == 1開始:etc;我需要它來打開一個文件,顯示用戶的分數和花費的時間。關於這一點的代碼的開始,我想知道如果我輸入了任何錯誤,因爲在Python上最後一節似乎沒有顯示/打開文件 – GreenLad 2015-04-03 14:29:00

回答

0

所以看起來你可能需要改變幾件事情。您應該使用raw_input來捕獲來自用戶的輸入。

對於usersClass,您的if語句可能不會觸發,因爲它們正在查找int而不是在輸入中傳遞的數字的字符串。

您可以將這些投入整數:usersClass = INT(usersClass),或在你的if語句,你可以只添加圍繞整數報價:如果usersClass ==「1」:

而且,貌似有是第一條if語句中的無意縮進。

編輯:您可能使用Python3.x,無需改變輸入的raw_input來,因爲它不存在Python3 ......我的錯誤就實現了。

+0

Bingo .. spot on cheers – GreenLad 2015-04-03 14:43:50

0

您必須確保usersClass的值不小於1或大於3.您從未這麼做過,因此如果輸入的數字不符合這些條件,則該文件將無法打開或創建。

我不明白的score = score - 0askquestion最後一行上面的意思。這是什麼意思?如果你不想改變一個變量的值,不要這樣做。