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()
I want to change the opened and the filepath variable as i've tried to demonstrate but am failing to do so, i need the filepath to change when i want it to, but it doesn't. It just dosen't regester and change both of the variables and prints out Empty and Fasle respectively. btw this is my output:
save or open: open
opened /home/pi/Desktop/testing True
save or open: save
no you didn't open a file Empty False
CodePudding user response:
You are setting opened = True
, but you will overwrite it in the next loop iteration with opened = False
.
You will need to initialize variables before the while
loop.
Also, there is no need to use global
here.
CodePudding user response:
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()
result:
save or open: open
opened /home/pi/Desktop/testing True
save or open: save
yes you opened a file /home/pi/Desktop/testing