【问题标题】:Elif and if not working or me not understanding [duplicate]Elif 如果不工作或者我不理解 [重复]
【发布时间】:2013-01-16 04:24:42
【问题描述】:

好吧,我的代码可以正常工作,但是当我想重新输入密码时键入 No 时,它不起作用;它只是进入输入密码行(第 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)

【问题讨论】:

  • 有人需要列出常见的 Python 误解。 if a == x or y 的主题将位于列表顶部。
  • @MarkRansom:已经有一些这样的列表(即使是常见问题解答也有一个),但出于某种原因,这似乎并没有出现在他们身上……
  • @MarkRansom - 这种误解很常见的不仅仅是 python

标签: python if-statement


【解决方案1】:
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'):

【讨论】:

  • 感谢大家的帮助。
  • @haws1290.. 不客气 :)
  • @RohitJain - 感谢您展示pythonic方式:)
【解决方案2】:

这个条件:

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

表示“如果passretry == 'yes' 为真,或'Yes' 为真”。 'Yes' 始终为真,因为非空字符串被视为真。这就是为什么您总是采用第一个代码路径。

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

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

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

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

这将允许人们大喊YES。)

【讨论】:

    【解决方案3】:

    你需要另一个完整的陈述:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      相关资源
      最近更新 更多