Omitting a return Statement: None

If you don’t have a return statement in a function, nothing is produced:

 >>>​​ ​​def​​ ​​f(x):
 ...​​ ​​x​​ ​​=​​ ​​2​​ ​​*​​ ​​x
 ...
 >>>​​ ​​res​​ ​​=​​ ​​f(3)
 >>>​​ ​​res
 >>>

Wait, that can’t be right—if res doesn’t have a value, shouldn’t we get a NameError? Let’s investigate:

 >>>​​ ​​print(res)
 None
 >>>​​ ​​id(res)
 1756120

Variable res has a value: it’s None! And None has a memory address. If you don’t have a return statement in your function, your function will return None. You can return None yourself if you like:

 >>>​​ ​​def​​ ​​f(x):
 ...​​ ​​x​​ ​​=​​ ​​2​​ ​​*​​ ​​x
 ...​​ ​​return​​ ​​None
 ...
 >>>​​ ​​print(f(3))
 None

The value None is used to signal the absence of a value. We’ll see some uses for it later in the book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.142.194