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