【问题标题】:I need python understand True when 1, yea, y is typed当输入 1,是的,y 时,我需要 python 理解 True
【发布时间】:2017-01-02 19:23:59
【问题描述】:

我想了解如何以正确的方式在 Python 代码下运行。我猜 cmets 会做下面的工作。 现在,这仅在我用大写首字母键入“True”或“False”的情况下才有效。但我也需要在输入 1 或 true 等时得到相同的结果。

# Here we ask the user place an input and assign it to name parameter.
name = raw_input ("What is your name human?: ")

# Here we will display the value of name parameter placed by user
print "Got it! Your name is %r" % name

# Here we ask the user if he is owning the device.  
# We will assign the answer to computers_owner parameter
computers_owner = input ("Are you the owner of this machine?: ")

# In this question's answer we have an if condition.

# If the answer is True machine will say "Good! I need you" % name
if computers_owner is True:
    print "Good! I need you %s" % name  

# If the answer is False machine will say "Call me your master!" % name 
else:
    print "Call me your master! %s" % name 

【问题讨论】:

  • 在第二个输入中也使用 raw_input() 并像这样比较:computers_owner.lower() == "true"
  • 并添加更多您提到的条件computers_owner.lower() == 'true' or computers_owner.lower() == 'y' or computers_owner == 1。你明白了。
  • 为什么用户希望能够输入1作为是/否问题的答案?只需检查以yn 开头的字符串(忽略大小写)并完成。

标签: python boolean boolean-logic boolean-expression


【解决方案1】:

您可以将列表用于真实条件,如下所示:

name = raw_input ("What is your name human?: ")
print "Got it! Your name is %r" % name
computers_owner = raw_input("Are you the owner of this machine?: ")
if computers_owner in ['1','yea','y','yo','hell yeah','true','True', 'true dat']:
    print "Good! I need you %s" % name  
else:
    print "Call me your master! %s" % name 

【讨论】:

  • 这正是我试图做的。谢谢你的帮助。
  • @phantomxxx 如果回答了您的问题,您可能会接受答案:Accepting Answer
  • 抱歉,这里是新来的,并试图弄清楚什么是什么。我刚刚接受了。感谢您的耐心等待。
猜你喜欢
  • 1970-01-01
  • 2020-04-30
  • 2015-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
  • 1970-01-01
  • 2019-07-26
相关资源
最近更新 更多