0
import random # imports the random module
user_class = "" # Global variable
question_counter = int(0) # sets counter
amount_correct = int(0) # sets score
possible_operators = ("+","-","x") # creates a list of operators
while user_class == "": # Indefinite iteration - Runs until a valid class is given
user_class = str(input("Please enter your class"))
if user_class == "Rainbow": # Testing variable class - Will not crash the program
class_file = open("RainbowClass.txt","a")
elif user_class == "Sun":
class_file = open("SunClass.text","a")
elif user_class == "Moon":
class_file = open("MoonClass.text","a")
else:
print("Not quite. Try again:")
user_class = ""
name = str(input("Please enter your name"))
while question_counter < 10: # Indeffinate iteration – number of questions
num1 = random.randint(1,10) # random number generation
num2 = random.randint(1,10)
operator = random.choice(possible_operators) # Chooses one of the operators from the list
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "x":
answer = num1 * num2
print("What is the answer to ", num1," "+operator+"" ,num2,"?")
user_answer = int(input())
if user_answer == answer:
question_counter = question_counter + 1
amount_correct = amount_correct + 1
print("Correct!")
else:
print("Incorrect")
question_counter = question_counter + 1
final_score = amount_correct
print("Well Done! You scored",amount_correct,"out of",question_counter,".")
amount_correct = str(amount_correct)
class_file.write(user_class)
class_file.write(name)
class_file.write(amount_correct + "\n")
class_file.close
數據這是我的代碼。當我運行它時,它不會收到任何錯誤,但我正在嘗試獲取用戶的類並根據輸入打開文本文件。文件處於打開狀態,但當涉及到底部時,它不會寫入我想要的變量內部的測驗數據。寫入文件中使用從變量
如何解決這個?在此
嘿pstatix,謝謝您的回答。一切運行良好,直到74行,這條語句:f.write(final_score +「\ n」) 。它返回一個回溯錯誤。這是貝說什麼:回溯(最近通話最後一個): 文件 「//文件服務器/學生/ 11197/GCSE CS評估夏/任務2 /堆棧溢出answer.py」,行73,在 f.write (final_score + 「\ n」 個) 類型錯誤:不支持的操作數類型(一個或多個)爲+: 'INT' 和 'STR' >>> –
FIXED: 'f.write(STR(final_score)+ 「\ n」)' ...謝謝@pstatix –
@BenColmer對不起,所有那些簡單的失敗!我已更新它以包括該修復。再次,我無法測試我寫作的時間。但問題仍然存在,你明白做了什麼?如果你這樣做,請選擇作爲答案,它適用於你! – pstatix