-1

I have written a function in python that prints multiples of 7 between 0 and 100. The output is okay but am getting None at the end of the output. How do I get rid of it and what triggers it?

def multiples(x):
    for n in range(100):
        n = n*x
        if n <= 100:
            print(n)
print(multiples(7))
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69

3 Answers3

4

Change print(multiples(7)) to multiples(7).

You were printing the return value of the function as well.

Here's a tutorial that explains it a bit more: https://www.w3schools.com/python/gloss_python_function_return_value.asp

Since your function did not contain a return statement, the function returns None.

codewelldev
  • 246
  • 1
  • 6
1

You need to explicitly return something to the function as so:

def multiples(x):
    result = []
    for n in range(100):
        n = n*x
        if n <= 100:
            print(n)
            result.append(n)

        else:
            pass
    return n
print(multiples(10))

Functions always return something, when the return is omit, Python implicitly returns None in the background.

I suggest you to have a look at The Python return Statement: Usage and Best Practices

Federico Baù
  • 6,013
  • 5
  • 30
  • 38
  • Technically though, you do not **need** to explicitly `return` anything. When you don't `return` anything, the function returns `None`, as was the case in the original question. – codewelldev Dec 19 '20 at 08:18
  • Sure you don't have to. Keep i mind that my first sentence is a direct answer to the question. Question: how to get rid of the None ... Answer: you need explicity... also i actually stated that if you dont add the return python will implicity return None – Federico Baù Dec 19 '20 at 08:47
0

In this case, in the last line, print is an outer function and the "multiples" is the inner function that the print wraps around.

First your function "multiples" is getting called. There is a print instruction in the function. So it is printing everything. At the end, however, you are not returning anything explicitly at the end of the function. Implicit return is None. So when your function is finished it returns, the implicit "None" to the outer print function. That's why the additional None in the end.

You can fix this by using suggestion of @codewelldev (by removing the print that wraps the multiples function).

Amit
  • 2,018
  • 1
  • 8
  • 12