繁体   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