Python is telling me 66 <= 17

Viewed 162

I'm new to python and trying to build a program that evaluates whether a potential partner is too young for someone using the / 2 + 7 rule.

despite using test variables that are well above 18 the program executes line 7 no matter what I do. I used 88/77, 77/66, 19/19, it always executes line 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")

EDIT:

I made the fix that many suggested, but now the program is still not working as intended and I found another flaw.

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")

when num1 = 19 and num2 = 16, the program outputs line 5 when I want it to output line 7. It's also still outputting line 7 when num1 and num2 are both set to a value higher than 17.

3 Answers

The expression :

if num1 and num2 <= 17:

is like :

if num1 == True and num2 <= 17:

With num1=66, num1 is similar to True and num2 <= 17 is evaluated

To fix your program, You need write :

if num1 <= 17 and num2 <= 17:

From python documention : Truth Value Testing

The issue is for this line of code:

if num1 and num2 <= 17:

Python reads this as follows:

if num1 is TRUE (which it is) and num2 is less or equal to 17, then execute ...

You were looking for

if num1 <= 17 and num2 <= 17

Or even:

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

in case you want to check more than two partners eventually (i.e. you hold a list of num1, num2, num3 ...)

To write num1 and num2 <= 17 in Python, you need to be explicit:

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

Otherwise, provided num1 != 0, the condition will always be True.

Or just use the max of the two values for the equivalent logic:

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