Python告诉我66 <= 17

时间:2019-01-09 10:18:32

标签: python python-3.x

我是python的新手,正在尝试构建一个程序来评估潜在伴侣是否对使用/ 2 + 7规则的人来说太年轻。

尽管使用的测试变量远高于18,但无论我做什么,程序都会执行第7行。我使用88 / 77、77 / 66、19 / 19,它总是执行第7行。

num1 = float(input("What is the higher age number? "))
num2 = float(input("What is the lower age number? "))
output = num1 / 2 + 7
if num1 and num2 <= 17:
    print("You're both underage")
elif num2 <= 17:
    print("You're going to jail bud")
elif output <= num2:
    print("That's OK")
else:
    print("They are slightly too young for you")

编辑:

我做了许多人建议的修复程序,但是现在程序仍然无法按预期运行,我发现了另一个缺陷。

num1 = float(input("What is the higher age number? "))
num2 = float(input("What is the lower age number? "))
output = num1 / 2 + 7
if num1 <= 17 and num2 <= 17:
    print("You're both underage")
elif num2 <= 17:
    print("You're going to jail bud")
elif output <= num2:
    print("That's OK")
else:
    print("They are slightly too young for you")

当num1 = 19和num2 = 16时,程序在我希望输出第7行时输出第5行。当num1和num2都设置为高于17的值时,程序仍然输出第7行。

3 个答案:

答案 0 :(得分:9)

表达式:

if num1 and num2 <= 17:

就像:

if num1 == True and num2 <= 17:

对于num1=66num1True类似,并且num2 <= 17被求值

要修复您的程序,您需要编写:

if num1 <= 17 and num2 <= 17:
  

来自python文档:Truth Value Testing

答案 1 :(得分:4)

问题在于以下代码行:

if num1 and num2 <= 17:

Python的用法如下:

  

如果num1是TRUE(是)并且num2小于或等于17,则   执行...

您正在寻找

if num1 <= 17 and num2 <= 17

甚至:

if all(i <= 17 for i in [num1,num2]) 

如果您最终想要检查两个以上的伙伴(即,您拥有num1,num2,num3 ...的列表)

答案 2 :(得分:4)

要在Python中编写num1 and num2 <= 17,您需要明确:

if num1 <= 17 and num2 <= 17:
    # do something

否则,提供num1 != 0,条件将始终为True

或仅将两个值中的max用于等效逻辑:

if max(num1, num2) <= 17:
    # do something