Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Formatting Code
#1
Can someone please explain to me the difference between the following two examples and why the shorter one compiles correctly and the longer one doesn't? Don't they both say the same thing? Forgive me, I'm new to coding!

The number 6 is a truly great number. Given two int values, a and b, return True if either one is 6. Or if their sum or difference is 6. Note: the function abs(num) computes the absolute value of a number.

def love6(a, b):
  return a == 6 or b == 6 or (a + b) == 6 or abs(a - b) == 6
#passes all tests
def love6(a, b):
  if a == 6 or b == 6:
    return True
  if (a + b) == 6 or abs(a - b) == 6:
    return True
#Doesn't pass
Reply
#2
What test do you perform/fail?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
The shorter one returns False if the expression is not correct. The longer version does not return False but returns None automatically, if none of the expressions are True. That is the main difference. so just change the longer one to:
def love6(a, b):
  if a == 6 or b == 6:
    return True
  if (a + b) == 6 or abs(a - b) == 6:
    return True
  return False
That should do the trick :)
Reply
#4
first one broken into steps:
>>> def love6(a, b):
...     x1 = a == 6
...     x2 = b == 6
...     x3 = (a + b) == 6
...     x4 = abs(a - b) == 6
...     x5 = x1 or x2 or x3 or x4
...     print(f'x1: {x1}, x2: {x2}, x3: {x3}, x4: {x4}, x5: {x5}')
...
>>> love6(6, 6)
x1: True, x2: True, x3: False, x4: False, x5: True
>>> love6(2, 6)
x1: False, x2: True, x3: False, x4: False, x5: True
>>>
step 2 broken into steps:
>>> def love6(a, b):
...     x1 = a == 6
...     x2 = b == 6
...     x3 = x1 or x2
...     x4 = (a + b) == 6
...     x5 = (abs(a - b)) == 6
...     x6 = x4 or x5
...     print(f'x1: {x1}, x2: {x2}, x3: {x3}, x4: {x4}, x5: {x5}, x6: {x6}')
...
>>> love6(6, 6)
x1: True, x2: True, x3: True, x4: False, x5: False, x6: False
>>> love6(2, 6)
x1: False, x2: True, x3: True, x4: False, x5: False, x6: False
>>>
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020