在Python

时间:2017-08-28 23:09:20

标签: python-2.7

我已经创建了一个生成安全密码短语的python程序,我已做过这样,以便用户可以决定是否将其密码打印到具有raw_input功能的文本文件中。我还做了这样,如果用户决定输入程序无法识别的输入,程序就会重复。我虽然对这个问题感到难过。下面是代码,下面是我对问题的解释。

if writeyn == 'Y' or writeyn == 'y' or writeyn == 'yes' or writeyn == 'Yes':
    print('Written to passwords.txt')
    f = open("passwords.txt", "a+") # "append"
    f.write(passtype + " - " + mypw)

if writeyn == 'n' or writeyn == 'N' or writeyn == 'no' or writeyn == 'No':
    print('Writting Stopped.')

while writeyn != 'n' or writeyn != 'N' or writeyn != 'no' or writeyn != 'No' or writeyn != 'Y' or writeyn != 'y' or writeyn != 'yes' or writeyn != 'Yes':
     writeyn = raw_input("Invalid Input; " + "\nWould you like to write your password to a text file? Y or n")
     writeyn = writeyn.strip()
     if writeyn == 'n' or writeyn == 'N' or writeyn == 'no' or writeyn == 'No':
         print 'Writing Stopped.'
         break
     elif writeyn == 'Y' or writeyn == 'y' or writeyn == 'yes' or writeyn == 'Yes':
         print('Written to passwords.txt')
         f = open("passwords.txt", "a+")
         f.write(passtype + " - " + mypw)
         break

当我在终端I中运行程序时,得到以下输出,如下面的链接所示。

print statement repeats twice

当用户指定他们不想将密码写入passwords.txt文件时,而不是print 'Writing Stopped.打印一次,而是重复两次。这也适用于print('Written to passwords.txt')。 我看过空白,看看是不是问题,但似乎不是。有谁知道导致程序执行此操作的原因是什么?

1 个答案:

答案 0 :(得分:0)

问题在于如何连接

中的逻辑比较
while writeyn != 'n' or writeyn != 'N' or writeyn != 'no' or writeyn != 'No' or writeyn != 'Y' or writeyn != 'y' or writeyn != 'yes' or writeyn != 'Yes':

根据您输入的截图" n"。所以比较

writeyn != 'n'

是假的,但是

writeyn != 'N'

是真的。由于您使用OR将它们全部连接起来,因此最终结果为true并且您输入while循环(导致对话框重新出现)。

为了解决这个问题,我建议使用

while not (writeyn == 'n' or writeyn == 'N' or writeyn == 'no' or writeyn == 'No' or writeyn == 'Y' or writeyn == 'y' or writeyn == 'yes' or writeyn == 'Yes'):