Search code examples
pythonfunctionloopsreturnlogic

Can anyone please give me the correct justification , because i expected the anser to be 9 while the result was "0"?


def print_nums(x):
    for i in range(x):
        print(i)
        return 

print_nums(10)

With this code I was expecting the answer to be 9, but I was really surprised to see 0 as the answer. Please could anyone provide the proper justification ?


Solution

  • your return is in the wrong spot

    def print_nums(x):
    for i in range(x):
        print(i)
    return 
    
    print_nums(10)
    

    will print 0-9 on a new line every time, if you want to just print 9 you should do

    def print_nums(x):
        for i in range(x):
        return i
    
    print_nums(10)