簡體   English   中英

我的if-else語句是怎么回事? (Python 3.3)

[英]What's going on with my if-else statement? (Python 3.3)

我正在為計費程序項目編寫條件語句。 對於我認識的初學者來說有點先進,但是我歡迎挑戰。 無論如何,我計划通過詢問用戶名和密碼來啟動程序。 因此,這是我對該程序的第一個編碼。

print ("Hello and welcome to Billing Pro, please enter your username and password to access the database.")

username = input ("Enter username:")

if username == "cking" or "doneal" or "mcook":
  print ("Valid username.")
else:
  print ("Invalid username. Please try again.") 


password = input ("Enter password:")

if password == "rammstein1" or "theory1" or "tupac1":
  print ("Valid password. User has been verified.")
else:
  print ("Invalid password. Access denied.")

現在,當我運行此代碼時,如果我鍵入了用戶名的三個選項以外的其他選項,Python會打印出“無效的用戶名”行。 現在由於某種原因,它會打印出“有效的用戶名”,然后顯示密碼提示。 另外,如果我輸入除密碼選項以外的任何內容,它將始終讀出“有效密碼”提示。

另外,當用戶輸入三個選項之外的其他內容時,如何循環用戶名提示? 我應該使用while語句而不是if-else還是可以在if-else語句的末尾放置while語句以再次觸發提示?

哦,我知道您不能說出來,因為我的格式很糟糕,但是我確實在腳本本身上使用了適當的縮進。

布爾表達式本身的問題在於它們始終為True。

if a == 'b' or 'c'就像if (True|False) or 'c' ,並且由於'c'true ,則不管第一個表達式( a == 'b'均為 True。

您可能需要a == 'b' and a == 'c'…a in {'b', 'c'…}更簡潔的a in {'b', 'c'…} ,它檢查a是否是集合的成員。

如果要循環,請使用循環:)

while username not in {"cking", "doneal", "mcook"}:
    print ("Invalid username. Please try again.")
    username = input ("Enter username:")
print ("Valid username.")

您需要將您的姓名與所有姓名進行比較。 問題就在這里:

if username == "cking" or "doneal" or "mcook":

Python首先評估一個結果為true或false,然后執行操作or進行某種操作,在這種情況下評估為True ,最后,您的比較如下所示:

if username == "cking" or True or True:

最終是真實的。 根據建議,您應該使用:

if username == "cking" or username == "doneal":

或干脆做:

if username in ("cking", "doneal"):

密碼也一樣。

我認為這段代碼可以幫助您

from sys import argv

    username=raw_input("Enter user name")
    password=raw_input("Enter password")

    if(username=="VARUN" or "Varun" or "varun"):
        print "\n\tvalid Username "
    else:
        print "\n\tUsername already existes"

    if (password=="@ppu1131986"):
        print "\n\tPasssowrd matched"
    else:
        print "\n\tWeak Password"
~                              
print ("Hello, welcome to Facebook, please enter your username and password to access.")

username = input ("Enter username:")

if username == "cking":
  print ("Valid username.")
else:
  print ("Invalid username. Please try again.") 

  username = input ("Enter username:")

if username == "cking":
  print ("Valid username.")
else:
  print ("Invalid username. Please try again.") 


password = input ("Enter password:")

if password ==  "tupac1":
  print ("Valid password. User has been verified.")
else:
  print ("Invalid password. Access denied.")

  password = input ("Enter password:")

if password ==  "tupac1":
  print ("Valid password. User has been verified.")
else:
  print ("Invalid password. Access denied.")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM