如何预定义python变量

时间:2014-06-03 09:45:19

标签: python variables interpreter

以下代码有效,但它有点乱,大多数IDE显示未定义变量的错误=>即使代码有效,也可以使用“myFile”。

i = 0
block = False
while i < 10:
   if block == True:
      myFile.write("End of a Turn.")
   block = True
   myFile = open("path/of/my/file/"+str(i)+".txt", "w")
   myFile.write("The turn begin.")
   i += 1

我想要做的是在第一次分配之前“预先定义”变量:

#myFile = SOMETHING_THAT_DOES_NOT_RUIN_THE_FOLLOWING_CODE
myFile = None #RESOLVE
i = 0
block = False
while i < 10:
   if block == True:
      myFile.write("End of a Turn.")
   block = True
   myFile = open("path/of/my/file/"+str(i)+".txt", "w")
   myFile.write("The turn begin.")
   i += 1

避免一些IDE理解问题。

Ty求助,

S上。

1 个答案:

答案 0 :(得分:1)

你可以这样做。

myFile = None
i = 0
block = False
while i < 10:
   if block and myFile:
       # ...

或者,可能更清洁:

for i in range(9):
    with open(str(i) + '.txt', 'w') as myFile:
        myFile.write('The turn begin. End of a turn')
with open(str(i + 1) + '.txt', 'w') as myFile:
        myFile.write('The turn begin.')