代码无效,导致语法错误

时间:2016-01-28 19:05:17

标签: python syntax-error

import random

correct= 0
print ("Hello, Welcome to the Quiz!")
name = input("What is your name?")
class_no = ""
while class_no not in ["1", "2", "3"]:
    class_no =  input("Please enter your class - 1,2 or 3:")
print ("Welcome to this maths quiz, while answering the questions please take in mind:")
print ("That + is addition, - subtraction and * is multiplication")
print ("Also please only enter numbers and make sure you do not leave an answer blank, Thank you!")
for count in range(10):
    num1 = random.randint(1,20)
    num2 = random.randint(1,10)
    symbol = random.choice(["+","-","*"])
    print("Please solve :\n",num1,symbol,num2)
    user = int(input(""))

    if symbol == "+":
        answer = num1 + num2
    elif symbol == "-":
        answer = num1 - num2
    elif symbol == "*":
        answer = num1 * num2


    if user == answer:
        print("Correct!")
        correct = correct + 1
    else:
        print("Incorrect")

print(name ,"You Got ",correct, "Out of 10")

with open("class%s.txt" % class_no, "a") as my_class:
    my_class.write("{0}\n".format([name,correct]))

viewscores= input("Please select a class from 1,2 or 3 and press space and choose one from alphabetically, average or highest?")
if viewscores=='1 alphabetically':    
     with open('class1.txt', 'r') as r:
           print(line, end=' ')

我要做的是让代码按字母顺序对保存到单独文本文件中的结果进行排序。 我仍然得到关于未定义的行的错误,所以我的整个代码有什么问题,谢谢你的任何帮助。 这是错误消息: 回溯(最近一次调用最后一次):

  

文件“E:\ GCSE COMPUTING \ task 3 trial.py”,第41行,

print(line, end=' ')

NameError:名称'line'未定义

1 个答案:

答案 0 :(得分:0)

这是你的错误:

 withopen('class1.txt', 'r') as r:
     print(line, end=' ')

您应该使用with open(file, mode) as r:,如下面的代码所示:

viewscores= input("Please select a class from 1,2 or 3 and press space and choose one from alphabetically, average or highest?")
if viewscores=='1 alphabetically':    
    with open('class1.txt', 'r') as r:
        print(line, end=' ')

阅读docs