简体   繁体   English

变量没有定义,但是

[英]variable isn't defined but it is

I have seen this question multiple times but none of them can apply to my code and none of it makes sense to my code. 我已经多次看到这个问题,但是没有一个问题适用于我的代码,也没有一个问题对我的代码有意义。 So I am sorry for asking this question. 因此,很抱歉提出这个问题。

I have written up a code where the data from previous inputs are written into a csv file. 我编写了一个代码,其中先前输入的数据被写入到csv文件中。 The name of the variable is called file and i have numerous of these for different inputs. 变量的名称称为文件,我有许多用于不同输入的变量。 But when I try to close the csv it comes up with the error: NameError: name 'file' is not defined 但是,当我尝试关闭csv时,出现错误:NameError:未定义名称'file'

Here is the code: 这是代码:

if classCode=="1":
  file=open("class1.csv","w")
  file.write("name, correct\n" + name + "," + str(correct) + "\n")

elif classCode=="2":
  file=open("class2.csv","w")
  file.write("name, correct\n" + name + "," + str(correct) + "\n")

elif classCode=="3":
  file=open("class3.csv","w")
  file.write("name, correct\n" + name + "," + str(correct) + "\n")

file.close()

I don't know why it says that 'file' isn't defined when I clearly have for all three. 我不知道为什么当我清楚地为所有三个文件都定义了“文件”时,为什么没有定义。 Am i just being stupid? 我只是愚蠢吗?

What happens if the class code is not 1,2 or 3. If all class code do the same thing you can make the filename dynamic, instead of repeating the code several times. 如果类代码不是1,2或3,会发生什么。如果所有类代码都执行相同的操作,则可以使文件名动态化,而不必重复执行几次。

class_file=open("class{}.csv".format(classCode),"w")
class_file.write("name, correct\n" + name + "," + str(correct) + "\n")
class_file.close()

file variable will only declare when classCode is either "1", "2" or "3" otherwise it will not declare and error will come. 仅当classCode为“ 1”,“ 2”或“ 3”时,文件变量才会声明,否则将不会声明,并且会出现错误。

you should make sure either control goes to any of the if statement or you should declare this variable outside If statement. 您应确保将控制权转到任何if语句,或者应在If语句之外声明此变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM