Python Forum

Full Version: Formatting Code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
What test do you perform/fail?
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 :)
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
>>>