Cou*_*ney 0 python if-statement while-loop
我正在为计费程序项目编写条件语句。我知道这对于初学者来说有点高级,但我欢迎挑战。无论如何,我计划在启动程序时询问用户名和密码。这是我对该程序的第一次编码。
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.")
Run Code Online (Sandbox Code Playgroud)
现在,一开始当我运行这段代码时,如果我输入了用户名的三个选项以外的任何内容,Python 就会打印出“无效用户名”行。由于某种原因,它现在打印出“有效用户名”,然后继续显示密码提示。此外,如果我输入密码选择以外的任何内容,它总是会读出“有效密码”提示。
另外,当用户输入三个选项以外的内容时,如何循环用户名提示?我应该使用 while 语句而不是 if-else 还是可以在 if-else 语句末尾放置 while 语句以再次触发提示?
哦,我知道你看不出来,因为我在问题中的格式很糟糕,但我确实在脚本本身上使用了正确的缩进。
布尔表达式本身的问题在于它们始终为 True。
\n\nif a == \'b\' or \'c\'
类似于if (True|False) or \'c\'
,并且由于\'c\'
是true,因此无论第一个表达式 ( ) 为何,它都是 True a == \'b\'
。
您要么想要a == \'b\' and a == \'c\'\xe2\x80\xa6
或更简洁的a in {\'b\', \'c\'\xe2\x80\xa6}
,它检查是否a
是集合的成员。
如果你想循环,就使用循环:)
\n\nwhile username not in {"cking", "doneal", "mcook"}:\n print ("Invalid username. Please try again.")\n username = input ("Enter username:")\nprint ("Valid username.")\n
Run Code Online (Sandbox Code Playgroud)\n
您需要将您的名字与所有名字进行比较。问题就出在这里:
if username == "cking" or "doneal" or "mcook":
Run Code Online (Sandbox Code Playgroud)
Python 将第一个评估为 true 或 false,然后执行or
某些操作,在这种情况下评估为True
,最后您的比较如下所示:
if username == "cking" or True or True:
Run Code Online (Sandbox Code Playgroud)
最终结果为真。根据建议,您应该使用:
if username == "cking" or username == "doneal":
Run Code Online (Sandbox Code Playgroud)
或者简单地做:
if username in ("cking", "doneal"):
Run Code Online (Sandbox Code Playgroud)
这同样适用于密码。
归档时间: |
|
查看次数: |
3472 次 |
最近记录: |