簡體   English   中英

如何預定義python變量

[英]How to predefine a python variable

以下代碼可以工作,但是有點混亂,即使代碼可以工作,大多數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理解問題。

求助,

S.

您可以這樣做。

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.')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM