我对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行。
发布于 2019-01-09 10:20:59
这句话:
if num1 and num2 <= 17:就像:
if num1 == True and num2 <= 17:使用num1=66,num1类似于True,num2 <= 17被评估。
要修复您的程序,需要编写:
if num1 <= 17 and num2 <= 17:来自python文档:真值检验
发布于 2019-01-09 10:23:14
问题在于这一行代码:
if num1 and num2 <= 17:Python如下所示:
如果num1是真(它是这样的)并且num2小于或等于17,那么执行.
你在找
if num1 <= 17 and num2 <= 17甚至:
if all(i <= 17 for i in [num1,num2]) 如果您最终想要检查两个以上的合作伙伴(即,您持有一个num1、num2、num3 .的列表)
发布于 2019-01-09 10:24:46
要用Python编写num1 and num2 <= 17,您需要显式地:
if num1 <= 17 and num2 <= 17:
# do something否则,如果是num1 != 0,条件将始终是True。
或者,只需将两个值的max用于等效逻辑:
if max(num1, num2) <= 17:
# do somethinghttps://stackoverflow.com/questions/54107801
复制相似问题