Return statement

Why I’m getting ‘None’ as output for the below mentioned code. Could anyone please provide clarification on this?

Input:

 #If print function will not return anything to the function modular then what is the use of mentioning return before print function.

def modular (input_number):
    return print(input_number % 4)   
result1 = modular (15)
print(result1)

Output:

3
None

Hello! Welcome to the forum.
I mocked up some code to explain.

def modular (something):
    return print(something % 2)

modular (3)
x = print("hello")
print(x)

So the problem is you’re returning a ‘print’ function. Although the spaces are also non conventional. Here’s a new written version of what I think you want. I haven’t googled why a print function has no return value, but I suspect this might help understand.

def modular (something):
    x = something % 2
    print(x)
    return x

new = modular (3)
x = print(new) # but our new function will print it anyways so this is not necessary
print(x)  #

def Nothing():
    pass

x = Nothing()
print(x)

Also I get the code format by typing three back-ticks before my code, copy-paste my code in, and three back-ticks to end the code block. This is a great question, I didn’t realize a print() had no return value.

1 Like

Welcome @Raj_Chiranjeevi to the forum.

This took me a while to get my head around too, but as @nellietobey says, it’s because the print function doesn’t return a value, it just prints to terminal, hence the ‘None’ value.

A lot of the book gets you to print to screen in each example so you get into the habit of that behaviour. In reality, you are more likely to be returning a value than printing it.

One way to practice this is to set the print statement to a variable, and then call that with the print function. That way you are separating the function return from the print to screen action.

Using Nellie’s example tweeked a bit…

# define the function and return the potential output
def modular (something):
    x = something % 2
    return x

#print the output separately with actual input value
print(modular(6))
2 Likes

I think everyone’s reply here has good info, but the short answer is:

Because the print() function doesn’t return anything, so then your return in modular is returning None. Just remove the print() inside modular:

def modular(input_number):
    return input_number % 4
1 Like