0

我正在为计费程序项目编写条件语句。对于我认识的初学者来说,这有点先进,但我欢迎挑战。无论如何,我计划通过询问用户名和密码来启动程序。所以这是我的第一个程序编码。

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 还是可以将 while 语句放在 if-else 语句的末尾以再次触发提示?

哦,我知道您无法分辨,因为我在问题中的格式很糟糕,但我确实在脚本本身上使用了适当的缩进。

4

4 回答 4

5
于 2013-08-20T17:05:41.033 回答
5

You need to compare your name with all names. Problem lies here:

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

Python evaluates first one to either true or false and then doing or with something, that evaluates to True in this context and at the end your comparison looks like this:

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

which ends up being True. As suggested, you should use:

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

or simply do:

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

The same applies to password.

于 2013-08-20T17:08:53.230 回答
0

我认为这段代码可以帮助你

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"
~                              
于 2014-04-20T03:51:05.217 回答
0
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.")
于 2016-12-17T10:45:05.290 回答