Почему функция возвращает None?
Доброго времени суток. Решил начать самообучаться азам Python. Сейчас играюсь с функциями и return. Написал вот такой калькулятор, но он возвращает None, хотя весь код исполняется.
Подскажите, пожалуйста, в чем я ошибаюсь. Самостоятельный поиск в гугле не помог.
- Вопрос задан более трёх лет назад
- 6199 просмотров
- Вконтакте
В вашей функции deistvie происходит просто вызов функций сложение, вычитания, умножения и т.д. И вы с ними ничего не делатете, т.е. как вариант, это выводить результат, например так:
либо надо возвращать значения в deistvie и в inputs, т.е. таким образом
Null in Python: Understanding Python's NoneType Object
If you have experience with other programming languages, like C or Java, then you’ve probably heard of the concept of null . Many languages use this to represent a pointer that doesn’t point to anything, to denote when a variable is empty, or to mark default parameters that you haven’t yet supplied. null is often defined to be 0 in those languages, but null in Python is different.
Python uses the keyword None to define null objects and variables. While None does serve some of the same purposes as null in other languages, it’s another beast entirely. As the null in Python, None is not defined to be 0 or any other value. In Python, None is an object and a first-class citizen!
In this tutorial, you’ll learn:
- What None is and how to test for it
- When and why to use None as a default parameter
- What None and NoneType mean in your traceback
- How to use None in type checking
- How null in Python works under the hood
Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.
Understanding Null in Python
None is the value a function returns when there is no return statement in the function:
When you call has_no_return() , there’s no output for you to see. When you print a call to it, however, you’ll see the hidden None it returns.
In fact, None so frequently appears as a return value that the Python REPL won’t print None unless you explicitly tell it to:
None by itself has no output, but printing it displays None to the console.
Interestingly, print() itself has no return value. If you try to print a call to print() , then you’ll get None :
It may look strange, but print(print(«. «)) shows you the None that the inner print() returns.
None also often used as a signal for missing or default parameters. For instance, None appears twice in the docs for list.sort :
Here, None is the default value for the key parameter as well as the type hint for the return value. The exact output of help can vary from platform to platform. You may get different output when you run this command in your interpreter, but it will be similar.
Using Python’s Null Object None
Often, you’ll use None as part of a comparison. One example is when you need to check and see if some result or parameter is None . Take the result you get from re.match . Did your regular expression match a given string? You’ll see one of two results:
- Return a Match object: Your regular expression found a match.
- Return a None object: Your regular expression did not find a match.
In the code block below, you’re testing if the pattern «Goodbye» matches a string:
Here, you use is None to test if the pattern matches the string «Hello, World!» . This code block demonstrates an important rule to keep in mind when you’re checking for None :
- Do use the identity operators is and is not .
- Do not use the equality operators == and != .
The equality operators can be fooled when you’re comparing user-defined objects that override them:
Here, the equality operator == returns the wrong answer. The identity operator is , on the other hand, can’t be fooled because you can’t override it.
Note: For more info on how to compare with None , check out Do’s and Dont’s: Python Programming Recommendations.
None is falsy, which means not None is True . If all you want to know is whether a result is falsy, then a test like the following is sufficient:
The output doesn’t show you that some_result is exactly None , only that it’s falsy. If you must know whether or not you have a None object, then use is and is not .
The following objects are all falsy as well:
- Empty lists
- Empty dictionaries
- Empty sets
- Empty strings
- 0
- False
For more on comparisons, truthy values, and falsy values, you can read about how to use the Python or operator, how to use the Python and operator, and how to use the Python not operator.
Declaring Null Variables in Python
In some languages, variables come to life from a declaration. They don’t have to have an initial value assigned to them. In those languages, the initial default value for some types of variables might be null . In Python, however, variables come to life from assignment statements. Take a look at the following code block:
Here, you can see that a variable with the value None is different from an undefined variable. All variables in Python come into existence by assignment. A variable will only start life as null in Python if you assign None to it.
Using None as a Default Parameter
Very often, you’ll use None as the default value for an optional parameter. There’s a very good reason for using None here rather than a mutable type such as a list. Imagine a function like this:
bad_function() contains a nasty surprise. It works fine when you call it with an existing list:
Here, you add ‘d’ to the end of the list with no problems.
But if you call this function a couple times with no starter_list parameter, then you start to see incorrect behavior:
The default value for starter_list evaluates only once at the time the function is defined, so the code reuses it every time you don’t pass an existing list.
The right way to build this function is to use None as the default value, then test for it and instantiate a new list as needed:
good_function() behaves as you want by making a new list with each call where you don’t pass an existing list. It works because your code will execute lines 2 and 3 every time it calls the function with the default parameter.
Using None as a Null Value in Python
What do you do when None is a valid input object? For instance, what if good_function() could either add an element to the list or not, and None was a valid element to add? In this case, you can define a class specifically for use as a default, while being distinct from None :
Here, the class DontAppend serves as the signal not to append, so you don’t need None for that. That frees you to add None when you want.
You can use this technique when None is a possibility for return values, too. For instance, dict.get returns None by default if a key is not found in the dictionary. If None was a valid value in your dictionary, then you could call dict.get like this:
Here you’ve defined a custom class KeyNotFound . Now, instead of returning None when a key isn’t in the dictionary, you can return KeyNotFound . That frees you to return None when that’s the actual value in the dictionary.
Deciphering None in Tracebacks
When NoneType appears in your traceback, it means that something you didn’t expect to be None actually was None , and you tried to use it in a way that you can’t use None . Almost always, it’s because you’re trying to call a method on it.
For instance, you called append() on my_list many times above, but if my_list somehow became anything other than a list, then append() would fail:
Here, your code raises the very common AttributeError because the underlying object, my_list , is not a list anymore. You’ve set it to None , which doesn’t know how to append() , and so the code throws an exception.
When you see a traceback like this in your code, look for the attribute that raised the error first. Here, it’s append() . From there, you’ll see the object you tried to call it on. In this case, it’s my_list , as you can tell from the code just above the traceback. Finally, figure out how that object got to be None and take the necessary steps to fix your code.
Checking for Null in Python
There are two type checking cases where you’ll care about null in Python. The first case is when you’re returning None :
This case is similar to when you have no return statement at all, which returns None by default.
The second case is a bit more challenging. It’s where you’re taking or returning a value that might be None , but also might be some other (single) type. This case is like what you did with re.match above, which returned either a Match object or None .
The process is similar for parameters:
You modify good_function() from above and import Optional from typing to return an Optional[Match] .
Taking a Look Under the Hood
In many other languages, null is just a synonym for 0 , but null in Python is a full-blown object:
This line shows that None is an object, and its type is NoneType .
None itself is built into the language as the null in Python:
Here, you can see None in the list of __builtins__ which is the dictionary the interpreter keeps for the builtins module.
None is a keyword, just like True and False . But because of this, you can’t reach None directly from __builtins__ as you could, for instance, ArithmeticError . However, you can get it with a getattr() trick:
When you use getattr() , you can fetch the actual None from __builtins__ , which you can’t do by simply asking for it with __builtins__.None .
Even though Python prints the word NoneType in many error messages, NoneType is not an identifier in Python. It’s not in builtins . You can only reach it with type(None) .
None is a singleton. That is, the NoneType class only ever gives you the same single instance of None . There’s only one None in your Python program:
Even though you try to create a new instance, you still get the existing None .
You can prove that None and my_None are the same object by using id() :
Here, the fact that id outputs the same integer value for both None and my_None means they are, in fact, the same object.
Note: The actual value produced by id will vary across systems, and even between program executions. Under CPython, the most popular Python runtime, id() does its job by reporting the memory address of an object. Two objects that live at the same memory address are the same object.
If you try to assign to None , then you’ll get a SyntaxError :
All the examples above show that you can’t modify None or NoneType . They are true constants.
You can’t subclass NoneType , either:
This traceback shows that the interpreter won’t let you make a new class that inherits from type(None) .
Conclusion
None is a powerful tool in the Python toolbox. Like True and False , None is an immutable keyword. As the null in Python, you use it to mark missing values and results, and even default parameters where it’s a much better choice than mutable types.
Now you can:
- Test for None with is and is not
- Choose when None is a valid value in your code
- Use None and its alternatives as default parameters
- Decipher None and NoneType in your tracebacks
- Use None and Optional in type hints
How do you use the null in Python? Leave a comment down in the comments section below!
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python's None: Null in Python
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

About Wolf
Wolf is an avid Pythonista and writes for Real Python.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:




Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Master Real-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!
Откуда в выводе появляется None в python при вызове print?
Есть вот такой код. Пытаюсь выполнить код и по идее на выходе должно быть слово «test», но тут почему-то ниже появляется «None». Что не так? Как фиксить?
Заранее спасибо. 
![]()
![]()
Когда вы вызываете строку print( test() ) происходит следующая последовательность действий:
- print вызывает ваша процедура test() .
- Процедура test печатает вашу надпись ‘test’
- Процедура test() не возвращает результата( нет инструкции return ). По этому результатом работы этой процедуры будет None . Это значение и печатает команда print .
Для того, чтобы получить ожидаемый результат ваш код следует изменить например так:
![]()
none («ничего») выдаёт вторая команда print — она печатает резулат выполнния функции test . функция у вас ничего не возвращает — вот и none .
если не хотите, чтобы печаталось none , не печатайте результат выполнения фунции test , а просто её вызывайте. т.е. вместо:
![]()
![]()
Что бы понять, почему » ниже появляется «None»» набери
A=test () и посмотри, чему равно A.
Null in Python
In Python, there is no such value as null.
Instead, Python has None that represents null.
You can use an if-statement to check if a value is None in Python:
Today, you are going to learn everything about the None object in Python.
History of Null Values in Programming
In programming, a null value means a parameter does not have a value (at least yet).
It is like a placeholder for empty variables.

To get a better idea about null values, let’s use a real-life example.
Let’s say you have a variable n that represents how much money you have.
- If n == $100, you have 100 dollars
- If n == $0, you have no money
- If n == null, you haven’t checked if you have money or not. Thus in this example, null represents the case where you don’t know how much money you have.
Many programming languages represent this absence of value as null.
However, in Python, None is used instead.
None in Python
In Python, a function automatically returns None when there is no return statement in a function.
For example, let’s create a function that does not return anything.
The simplest way to do this is by using the pass statement:
Let’s call this function and print the returning value:
As you can see, the function returns None.
Let’s see another example.
Python’s built-in print() function does not return anything. This is a fact that you have probably not thought about before.
Because the print() function does not return a value, it returns None.
To see this, you can print the result of a print() call:
Instead of printing “Example”, None is printed is because print(“Example”) itself returns None.
Facts About None Object in Python
Here are some facts about the None object:
- None is not the same as False.
- An empty string is not the same as None.
- None is also not a zero.
- Any comparison with None returns False, except for comparing None with itself.
Here I am using Python REPL to verify these:
How to Use and Deal with None in Python
In Python, None represents the absence of a value.
You commonly use None to:
- Make comparisons to see if a value is None or not.
- Provide an empty default argument value for a function.
You also commonly see NoneType in the traceback error messages.
This is because you have an unexpected None value somewhere in the code and you try to use it.
None in Comparisons
None is commonly seen when making comparisons in Python.
To compare an object with None, use the identity operator is (and is not).
Generally, to check if a value is None in Python, you can use the if…else statement.
For instance, let’s check if a name variable is None:
None as a Default Parameter
A None can be given as a default parameter to a function.
This means if you call the function without specifying the parameter None is used as a fallback.
For example, let’s create a function that greets a person only if a name is given as an argument:
This function works such that:
- If a name is not specified, it defaults to None. As a result, the function does nothing.
- If a name is specified, the function greets the person with that name.
None as a default parameter is a common way to use None in Python.
If you take a look at the official documentation of Python, you see None used this way in the list.sort() method for example.

The key parameter is None by default.
Debugging a NoneType in a Traceback
When writing Python code, you commonly stumble across an error like this one:
If you see this or any other error with the word NoneType it means you are using None in a way it cannot be used.
In other words, something that is not supposed to be None is accidentally None.
For instance, let’s create a function that returns a list of names and call it:
Instead of printing the names, an error occurs:
This happens because we forgot to return the names in the give_names() function.
As you learned earlier, when a function does not use the return keyword, None is returned automatically.
As a result of this little mistake, we try to iterate over the None object.
In this case, the fix is simple—return the names from the function:
Now the function works as we expected:
This serves as one example of how to track down an error with NoneType.
Whenever you see this error, something similar is happening.
None Object Under the Hood in Python
In many popular programming languages, null is just a 0 under the hood.
In Python, this is not true.
Just like everything else in Python, None is an object.
This is easy to verify by checking the type of None in Python REPL:
The type of None is NoneType. This is because NoneType is the base class that implements the None object.
In Python, None is a singleton object.
This means there is only one None in Python at your disposal.
No matter where you see None, it is always the same None none object.
Let’s verify this by creating multiple variables with None as their value and checking their id:
All the variables return the same id.
This verifies that there is only one None.

In other words, the variables n1, n2, and n3 are also the same object because they point to the same memory address.
None Is a True Constant in Python
Let’s go further into the details of None.
None is an object in Python. But it is a special object that you cannot modify.
Let’s see what happens if you try to modify the None object in Python:
Also, you cannot add properties to the None object:
Modifying the None object is not possible, because it is a true constant in Python.
As discussed earlier, this can cause errors and bugs in your code. Luckily, the error message is clear enough to tell you what is going on.
Subclassing the underlying type NoneType of None is not possible.
Conclusion
Python null is called None.
None is a special object that represents the absence of a value.
A function that does not return a value automatically returns None.
Comparisons with None evaluate True only when comparing None with itself.