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()
Run Code Online (Sandbox Code Playgroud)
我想更改打开的文件路径变量,正如我试图演示的那样,但我未能这样做,我需要在需要时更改文件路径,但事实并非如此。它只是不注册和更改这两个变量并分别打印出 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
Run Code Online (Sandbox Code Playgroud)
您正在设置opened = True,但您将在下一个循环迭代中使用 覆盖它opened = False。
您需要在while循环之前初始化变量。
另外,这里也没有必要使用global。