Книга: Practical Programming, Fourth Edition
Назад: Writing and Running a Program
Дальше: Dealing with Situations Tha t Your Code Doesn’t Handle

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 you get a NameError? Let’s investigate:

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

Variable res has a value: it’s None! And None has an identity. 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. You’ll see some uses for it later in the book.

Назад: Writing and Running a Program
Дальше: Dealing with Situations Tha t Your Code Doesn’t Handle