我的if-else声明发生了什么? (Python 3.3) [英] What's going on with my if-else statement? (Python 3.3)

查看:190
本文介绍了我的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语句放在if-else语句的末尾以再次触发提示?

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.

推荐答案

布尔表达式本身存在的问题是它们总是为真。

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

如果a =='b'或'c'就像 if(True | False)或'c',以及'c' truthy ,无论第一个表达式是什么都是真的( 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'和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天全站免登陆