【问题标题】:Code not working, getting syntax error代码不起作用,出现语法错误
【发布时间】:2016-05-06 07:45:24
【问题描述】:
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=' ')

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

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

print(line, end=' ')

NameError: name 'line' 未定义

【问题讨论】:

  • withoopen 应该是 with open。你错过了两者之间的空间。
  • 您应该始终分享您的错误。我们可以非常快速地调试阅读这些语法错误。您还应该仔细阅读错误,它们通常会告诉您问题所在。

标签: python syntax-error


【解决方案1】:

这是你的错误:

 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

【讨论】:

    猜你喜欢
    • 2015-03-28
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 2018-04-06
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多