0

I'm learning Python and I was writting this snippet:

def some_function(a):
  if a <= 5:
   return b = a + 5
  elif a > 5:
   return b = a + 20

When i run it, it appears :

return b = a + 5
             ^
SyntaxError: invalid syntax

However, if i write it in this way, it works:

def some_function(a):
  if a <= 5:
    b = a + 5
  elif a > 5:
    b = a + 20
  return b

Why does it works this way?

SMath
  • 137
  • 6
  • 1
    Why would you need to define a variable there? All local variables will perish after the `return`. – Klaus D. Jun 04 '20 at 02:44

1 Answers1

1

You are not allowed to assign and return a thing in the same line. You can return without assigning a variable like this.

def some_function(a):
    if a <= 5:
        return a + 5
    elif a > 5:
        return a + 20

Also, you can do this and save a line since you only have 2 conditions. If a is not less than or equal to 5, it goes to the next line.

def some_function(a):
    if a <= 5:
        return a + 5
    return a + 20

This is also equivalent, else you can't specify a condition, it's a catch all for anything that isn't satisfied earlier.

def some_function(a):
    if a <= 5:
        return a + 5
    else:
        return a + 20

Both of these are probably preferable stylistically to using elif. Elif is usually for if you have 3 or more conditions like:

def some_function(a):
    if a <= 5:
        return a + 5
    elif 5 < a < 30:
        return a + 7
    else:
        return a * 100 
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
user2415706
  • 932
  • 1
  • 7
  • 19