The code at line 7 works when 'Add' is typed. But the code at line 7 keeps repeating when 'View' prompt is entered. This is my password storing programe
import string
master_pass = input('Lost in Soul Sand be everything, but the KEY! \n')
while master_pass == 'Soul':
action = input('Add/View Soul?').lower()
if action == 'add':
U = input('Soulname: ')
P = input('Soul Sand: ')
with open('sandvalley.txt','a') as f:
f.write( U + '|' + P + '\n')
print('Souls saw the light')
if action == 'view':
with open('sandvalley.txt','r') as narrate:
narrate.readlines()
for row in narrate:
print(row)
if action != 'add' or 'view':
print('Soul has left the storm')
break
print ('End')
I don't know what you mean by
The code at line 7 works when 'Add' is typed. But the code at line 7 keeps repeating when 'View' prompt is entered.
since all options (add
, view
, and other strings) will not keep the program stay in the loop in my test and line 7 is a blank line.
But I do know if you want to use the variable action
to control the program, then if action != 'add' or 'view:
is certainly not the guy you looking for.
What if action != 'add' or 'view':
acutally does is if (action != 'add') or ('view'):
, which means if the variable action is NOT 'add'
OR 'view'
, and the so-called Truth Value Testing is coming around. According to doc, any string whose length is not zero is considered True
, hence the conditional expression will always be True
and the ending process will always be done.
If you want to fix it, if action not in ['add', 'view']
will be good, but I will use
if action == 'add':
# do something
elif action == 'view':
# do something
else:
# end the program
instead, which is better IMO.
BTW, in Python 3.10+, match-case is introduced (link to doc), and this kind of cases is definitely the best time to use it.
match action:
case 'add':
# do something
case 'view':
# do something
case _:
# end the program
Give it a try.