def hello():
while True:
global opened, filepath
command = input("save or open: ")
opened = False
filepath = "Empty"
if command == "save":
if opened:
print(f"yes you opened a file {filepath}")
else:
print(f"no you didn't open a file {filepath} {opened}")
elif command == "open":
filepath = "/home/pi/Desktop/testing.txt"
opened = True
print(f"opened {filepath} {opened}")
else:
print("typo")
hello()
我想更改打開的和檔案路徑變數,因為我試圖演示但沒有這樣做,我需要檔案路徑在我想要的時候更改,但它沒有。它只是不注冊和更改這兩個變數并分別列印出 Empty 和 Fasle。順便說一句,這是我的輸出:
save or open: open
opened /home/pi/Desktop/testing True
save or open: save
no you didn't open a file Empty False
uj5u.com熱心網友回復:
您正在設定opened = True,但您將在下一次回圈迭代中使用opened = False.
您需要在while回圈之前初始化變數。
另外,這里不需要使用global。
uj5u.com熱心網友回復:
def hello():
opened = False #moved these
filepath = "Empty"
while True:
command = input("save or open: ")
if command == "save":
if opened:
print(f"yes you opened a file {filepath}")
else:
print(f"no you didn't open a file {filepath} {opened}")
elif command == "open":
filepath = "/home/pi/Desktop/testing"
opened = True
print(f"opened {filepath} {opened}")
else:
print("typo")
hello()
結果:
save or open: open
opened /home/pi/Desktop/testing True
save or open: save
yes you opened a file /home/pi/Desktop/testing
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/409828.html
標籤:
