-1

I am a noob, just when I thought I was getting a hang of loops, it had to throw me a curve ball. And I cannot find an answer anywhere.

I have a very simple for loop inside a function. All it does is counts i in a range and prints i. Then I call the function, and instead of printing, eg., 0, 1, 2, 3, 4 it prints 0, 1, 2, 3, 4, None.

I wrote the following code:

`

def generate():
    for i in range(5):
        print(i)


print(generate())

`

If I do this code without the function, just with the for loop, it works fine.

  • You print the result of a function that returns `None`. Hence, you print `None`. If you don't want to print the result of the function, then don't print the result of the function. – Silvio Mayolo Dec 17 '22 at 01:48

1 Answers1

1

You are not returning anything from generate(). So printing generate is causing that None to appear.

Change print(generate())

to generate()

Rajib
  • 36
  • 4
  • Thank you so much. I also saw the other question that SO forwarded me to. So basically every function needs a return statement or it'll return a none. – nosni khoritz Dec 18 '22 at 00:26
  • Yes. You can store all those numbers in a list with 'numberList.append(i)' inside the for loop and return the list itself. But if you are trying to print it in the main function then you will need the for loop again. So it's better not to return anything in this case. – Rajib Dec 19 '22 at 18:35