Last answered:

07 Mar 2022

Posted on:

04 Mar 2022

0

I've put three conditions:

I did the following:

n1 = input("We need you to input two numbers. Input the first number: \n > ")
n2 = input("Now the second number: \n > ")
n1 = float(n1)
n2 = float(n2)
if n1 and n2 > 15:
    print(n1*n2)
elif n1 > 15 and n2 <= 15:
    print(n1+n2)
elif n1 <= 15 and n2 > 15:
    print(n1+n2)
else:
    print(0)

It works fine when n1 and n2 > 15, when n1 > 15 and n2 <= 15, and when n1 and n2 <15. However, if n1 <= 15 and n2 > 15, it returns the product. Any ideas as to why?

1 answers ( 0 marked as helpful)
Instructor
Posted on:

07 Mar 2022

0

Hey João,

Thank you for your question!

First, let me address this line in the code here:

if n1 and n2 > 15:
    *something happens*

Notice that this is not equivalent to checking whether both n1 and n2 are larger than 15. Rather, it is equivalent to

if n1:
    if n2 > 15:
        *something happens*

The first condition will always be True for n1 different than 0. You can check that for yourself :)

Let me share one way to think about this problem. You have the following 4 cases that I have represented with the table below

n1 greater than 15? n2 greater than 15?
Case 1 Yes Yes
Case 2 Yes No
Case 3 No Yes
Case 4 No No

Let's cover the first case, where both numbers are greater than 15:

if n1 > 15 and n2 > 15:
    print(f'Product: {n1*n2}')
elif ...
    ...

The elif command that follows implies that either of the three remaining cases is satisfied. Let's cover Cases 2 and 3 as follows:

if n1 > 15 and n2 > 15:
    print(f'Product: {n1*n2}')
elif n1 > 15 or n2 > 15:
    print(f'Sum: {n1+n2}')

Finally, the only remaining option is that both numbers are smaller than or equal to 15. We cover it by introducing the else statement:

if n1 > 15 and n2 > 15:
    print(f'Product: {n1*n2}')
elif n1 > 15 or n2 > 15:
    print(f'Sum: {n1+n2}')
else:
    print(0)

Hope this helps!

Kind regards,
365 Hristina

Submit an answer