-1

I have the following piece of code in Python which tries to put a function that prints something in a print statement.

def my_print(num: int) -> None:
    for i in range(num):
        print(i, end=' ')

if __name__ == '__main__':
    print('When num is 5 :', my_print(5))

I expect to get something like

When num is 5 : 0 1 2 3 4

But I actually get

0 1 2 3 4 When num is 5 : None

Could someone please explain the logic behind the print function in this case and where that None comes from at the end? Thanks.

Kai Li
  • 55
  • 1
  • 7

2 Answers2

1

Try this:

def my_print(num: int) -> None:
    for i in range(num):
        print(i, end=' ')

if __name__ == '__main__':
    print('When num is 5 :', end=" ")
    my_print(5)

The None was printing because your my_print() function would return a None to the calling position.

edusanketdk
  • 602
  • 1
  • 6
  • 11
1

You can try list comprehension as an alternative

def my_print(num: int) -> str:
    return ' '.join(map(str, [i for i in range(num)]))

if __name__ == '__main__':
    print(f'When num is 5 : {my_print(5)}')

output

When num is 5 : 0 1 2 3 4
edusanketdk
  • 602
  • 1
  • 6
  • 11
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44