Functions · 7 / 27 Theory

Common mistakes with functions

These are the most frequent mistakes when starting with functions.

1. Defining but not calling

def greet():
    print("Hello")

# nothing is shown: greet() is missing

2. Forgetting the parentheses when calling

greet        # does nothing: it is just the name of the function
greet()      # this does run it

3. print instead of return

def double(n):
    print(n * 2)

x = double(4) + 1   # TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

If you are going to use the result elsewhere, use return.

4. Code after return

def f():
    return 1
    print("never shown")

5. return inside a loop too early

def all_letters(text):
    for c in text:
        if c.isalpha():
            return True   # returns True with the first letter!
    return False

print(all_letters("a1"))   # True, but it should be False

To check that all of them meet a condition, return False as soon as one does not, and True only when the loop ends.

6. Wrong number of arguments

def add(a, b):
    return a + b

add(1)         # TypeError: missing 1 required positional argument: 'b'
add(1, 2, 3)   # TypeError: takes 2 positional arguments but 3 were given

7. Using a variable from another function

Local variables cannot be seen from outside. If you need that value, return it with return or pass it as a parameter.

8. Modifying a received list by accident

def remove_first(l):
    l.pop(0)          # modifies the original list

numbers = [1, 2, 3]
remove_first(numbers)
print(numbers)        # [2, 3]

Lists are passed by reference: the function works with the same list, not a copy. If you do not want to change it, work with l.copy().

9. Mixing texts and numbers

def double(n):
    return n * 2

print(double(input()))        # with "5" it returns "55": input() is text
print(double(int(input())))   # 10

Quick check

  • Do I call the function, and with parentheses?
  • Does it return with return what it should return?
  • Do I pass as many arguments as it has parameters?
  • Do I convert what comes from input() or sys.argv?