當我嘗試使用此代碼寫入文本文件時,遇到「回溯(最近調用最後一次):」錯誤。所有這三個文件都已經存在了(儘管我相信他們不應該 - 代碼應該創建它們,如果它找不到它們,不應該?),並且它們都與.py文件在同一個目錄中。我看不到我的錯誤 - 我做錯了什麼?Python中文本文件的意外回溯
import random
forename=""
surname=""
classno=0
numberone=0
numbertwo=0
correct=False
score=0
ops = ["+", "x", "-"]
while forename == "" or forename.isnumeric():
forename=input("What is your first name? ")
if forename == "":
print("You have to enter your first name.")
if forename.isnumeric() == True:
print("Your name must contain letters.")
while surname == "" or surname.isnumeric():
surname=input("What is your surname? ")
if surname == "":
print("You have to enter your name.")
if surname.isnumeric() == True:
print("Your name must contain letters.")
while classno not in [1,2,3]:
while True:
try:
classno=int(input("What class are you in? "))
break
except ValueError:
print("That wasn't right. Please try again.")
for x in range(10):
operation=random.choice(ops)
if operation == "-":
numberone=random.randint(0,10)
numbertwo=random.randint(0,numberone)
elif operation == "x":
numberone=random.randint(0,12)
numbertwo=random.randint(0,12)
else:
numberone=random.randint(0,100)
numbertwo=random.randint(0,(100-numberone))
while True:
try:
answer=int(input("What is " + str(numberone) + str(operation) + str(numbertwo) + "? "))
break
except ValueError:
print("Incorrect input. Please try again.")
if operation=="+":
if answer==numberone+numbertwo:
correct=True
elif operation=="-":
if answer==numberone-numbertwo:
correct=True
else:
if answer==numberone*numbertwo:
correct=True
if correct==True:
print("Correct!")
score=score+1
else:
print("Wrong!")
correct = False
if classno == 1:
file1=open("class1.txt", "a")
file1.write(forename,surname,score,"\n")
file1.close()
elif classno == 2:
file2=open("class2.txt", "a")
file2.write(forename,surname,score,"\n")
file2.close()
else:
file3=open("class.text", "a")
file3.write(forename,surname,score,"\n")
file3.close()
print("You scored",score,"out of 10.")
編輯:這是我的問題後看到:
燦你發佈完整的追蹤? –
將其添加到帖子:) @BhargavRao – gulliver
追溯之後的消息是什麼?提示:錯誤:行* –