0

好吧,我的代码可以正常工作,但是当我输入“否”时,如果我想重试输入密码,它就不起作用了;它只是进入输入密码行(第 20 行)。我已经尝试了多种方法来解决这个问题,但我根本做不到。

import time
import os

print ("Hello world.")
time.sleep(1)
print ("Waiting 5 seconds.")
time.sleep(5)
print ("You have waited 10 seconds.")
print ("Executing Chrome.")
time.sleep(1)
print ("Execution failed!")
password = input("Enter the execution password: ")
if password == 'password1234':
    os.system ('C:\\Users\\Harry\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')
else:
    print ("Wrong password!")
    time.sleep(1)
    passretry = input("Do you want to try again? ")
    if passretry == 'yes' or 'Yes':
        passretry1 = input("Enter password: ") 
        if passretry1 == 'password1234':
            os.system ('C:\\Users\\Harry\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe')
    elif passretry == 'no' or 'No':
        print ("Closing...")
        time.sleep(1)
    else:
        print ("Wrong password.")
        time.sleep(.5)
        print ("Retry limit exceeded, closing.")
        time.sleep(1)
4

3 回答 3

9
if passretry == 'yes' or 'Yes':

上面的 if 语句被评估为: -

if (passretry == 'yes') or 'Yes':

现在,因为'Yes'被评估为True,所以,你的if语句总是True,因此你总是必须输入新密码。


您需要将条件更改为: -

if passretry in ('yes', 'Yes'):

同样,elif应将以下内容更改为:-

elif passretry in ('no', 'No'):
于 2013-01-31T22:39:45.183 回答
3

这个条件:

if passretry == 'yes' or 'Yes':

意思是“如果passretry == 'yes'是真的,或者'Yes'是真的”。 'Yes'始终为真,因为非空字符串算作真。这就是为什么您总是采用第一个代码路径。

你需要把事情说得更清楚一点:

if passretry == 'yes' or passretry == 'Yes':

(或者让你的代码更通用一点:

if passretry.lower() == 'yes':

这将允许人们大喊大叫YES。)

于 2013-01-31T22:39:59.587 回答
2

您需要另一个完整的声明:

passretry == 'yes' or passretry == 'Yes':

字符串 'Yes' 的计算结果始终为 True。

于 2013-01-31T22:40:23.023 回答