我的 if-else 语句是怎么回事?(Python 3.3) [英] What's going on with my if-else statement? (Python 3.3)

查看:18
本文介绍了我的 if-else 语句是怎么回事?(Python 3.3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing conditional statements for a billing program project. It's a bit advanced for a beginner I know but I welcome the challenge. Anyways, I plan on starting the program with asking for username and password. So this is my first coding for the program.

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 会打印出无效用户名"行.现在出于某种原因,它正在打印有效用户名",然后继续输入密码提示.此外,如果我输入的不是密码选项,它总是会读出有效密码"提示.

Now at first when I ran this code if I had typed in anything other than the three choices for username Python printed out the 'invalid username' line. For some reason now, it's printing out 'valid username' and then going ahead with the password prompt. Also if I input anything other than the choices for passwords it will always read out the 'valid password' prompt.

另外,当用户输入三个选项以外的内容时,我如何循环显示用户名提示?我应该使用 while 语句而不是 if-else 还是可以在 if-else 语句的末尾放置一个 while 语句以再次触发提示?

Also how do I loop the username prompt when the user inputs something other than the three choices? Should I be using a while statement instead of if-else or can a while statement be placed at the end of the if-else statement to trigger the prompting again?

哦,我知道你看不出来,因为我在问题中的格式很糟糕,但我确实在脚本本身上使用了适当的缩进.

Oh and I know you can't tell because my crappy formatting in the question, but I did use proper indentation on the script itself.

推荐答案

布尔表达式本身的问题在于它们始终为 True.

The problem with your boolean expressions themselves is that they're always True.

if a == 'b' or 'c' 类似于 if (True|False) or 'c',并且因为 'c'真实,无论第一个表达式 (a == 'b').

if a == 'b' or 'c' is like if (True|False) or 'c', and since 'c' is truthy, it's True regardless of the first expression (a == 'b').

你要么想要 a == 'b' and a == 'c'... 或者更简洁的 a in {'b', 'c'...},它检查 a 是否是集合的成员.

You either want a == 'b' and a == 'c'… or the more succinct a in {'b', 'c'…}, which checks if a is a member of the set.

如果你想循环,使用循环:)

If you want to loop, use a loop :)

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

这篇关于我的 if-else 语句是怎么回事?(Python 3.3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆