None ошибка python

Достаточно часто возникают вопросы: «почему моя функция ничего не возвращает?!», «почему из функции возвращается None?», «не могу понять откуда появляется None…».

Для начала необходимо понимать и помнить, что любая функция в Python всегда что-то возвращает и если не используется оператор return для возврата значения (такие случаи бывают, но об этом позднее), то функция возвращает объект None. В случае если return используется, но после него ничего не указывается явно, то по умолчанию считается, что там стоит объект None.

# Не используем оператор return, поэтому результат не возвращается.
def func(x):
    x * x  

print(func(10))
#=> None

# Используем оператор return, но не задаем явное значение/используем некорректно
def func(x):
    x * x
    return

print(func(10))
#=> None

# Корректно возвращаем результат с использованием оператора return
def func(x):
    return x * x

print(func(10))
#=> 100

Порой бывает, что по ошибке указывается возврат вместе с функцией print(). Для информации функция print() в Python выводит переданные аргументы на стандартное устройство вывода (экран), но при этом не возвращает значений, т.е. можно считать, что возвращает None.

def func(x):
    return print(x * x)

a = 5
b = func(a)  # Присваиваем результат функции переменной b
# Результат работы функции выводится на экран, благодаря print() в теле функции.
#=> 25
# Но при этом данный результат не присваивается переменной b.
print(b)
#=> None

Если дальше по коду проводятся манипуляции с переменной b, например сложение, то возникнет ошибка TypeError:

c = b + 1  # Пытаемся сложить None и 1
print(c)
# => TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Возможен вариант, когда функция и не должна ничего возвращать, она производит какие-либо действия с объектами в глобальной зоне видимости и на этом ее функционал заканчивается. В таком случае return может и не использоваться, но необходимо помнить, что в этом случае функция возвращает None.

# Бесполезная функция необходимая только в качестве примера.
def extend_list(list1, list2):
    list1.extend(list2)


list1 = [1, 2]
list2 = [3, 4]
print(extend_list(list1, list2))
# => None
#  При этом поставленную задачу функция выполнила - изменила list1
print(list1)
# => [1, 2, 3, 4]

В примере выше использовался метод работы со списками extend() и необходимо понимать, что метод изменяет объект, к которому применен, а не возвращает результат изменения объекта.

list3 = extend_list(list1, list2)
print(list3)
# =>  None

In Python you have the None singleton, which acts pretty oddly in certain circumstances:

>>> a = None
>>> type(a)
<type 'NoneType'>
>>> isinstance(a,None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

So first off, <type 'NoneType'> displays that None is not a type, but that NoneType is. Yet when you run isinstance(a,NoneType), it responds with an error: NameError: name 'NoneType' is not defined

Now, given this, if you have a function with an input default set to None, and need to check, you would do the following:

if variable is None:
    #do something
else:
    #do something

what is the reason that I cannot do the following instead:

if isinstance(variable,None): #or NoneType
    #do something
else:
    #do something

I am just looking for a detailed explanation so I can better understand this

Edit: good application

Lets say I wanted to use isinstance so that I can do something if variable is a variety of types, including None:

if isinstance(variable,(None,str,float)):
    #do something

В вашей функции deistvie происходит просто вызов функций сложение, вычитания, умножения и т.д. И вы с ними ничего не делатете, т.е. как вариант, это выводить результат, например так:

#Определяем что делать
def deistvie(znak, num1, num2):
  if znak == '!':
    print(factorial(num1))
  elif znak == '+':
    print(summa(num1, num2))
  elif znak == '-':
    print(raznost(num1, num2))
  elif znak == '*':
    print(proisvedenie(num1, num2))
  elif znak == '/':
    print(delenie(num1, num2))
  else:
    return ('Нет такого действия')

либо надо возвращать значения в deistvie и в inputs, т.е. таким образом

#Определяем что делать
def deistvie(znak, num1, num2):
  if znak == '!':
    return factorial(num1)
  elif znak == '+':
    return summa(num1, num2)
  elif znak == '-':
    return raznost(num1, num2)
  elif znak == '*':
    return proisvedenie(num1, num2)
  elif znak == '/':
    return delenie(num1, num2)
  else:
    return ('Нет такого действия')
#Получаем данные
def inputs():
  num1 = float(input('Введите число: '))
  znak = input('Введите знак (+, -, *, /, !): ')
  if znak == '!':
    num2 = ''
  else:
    num2 = float(input('Введите второе число: '))
  return deistvie (znak, num1, num2)

def print_name(name):
    print(name)

print(print_name('Annabel Lee'))

Why do I get the following output:

Annabel Lee
None

More precisely, from where does the word None come from?

asked Feb 10, 2019 at 19:30

Nacka's user avatar

2

You have two calls to print: one inside print_name and another outside the function’s scope.

The one inside print_name() prints the name passed in. The one on the outside prints what the function print_name returns — which is None as you have no return statement. Presuming you want only one printed output, you’d return it instead of printing it in the function:

def print_name(name):
    return name

print(print_name('Annabel Lee'))

Or just call print_name without wrapping it in a print function.

answered Feb 10, 2019 at 19:33

Because you are print the method print, the return should be name, not print(name).

answered Feb 10, 2019 at 19:31

Fernandoms's user avatar

FernandomsFernandoms

4443 silver badges13 bronze badges

Your function prints the name and you don’t need to use print() again.

def print_name(name):
    print(name)

print_name('Annabel Lee')

If don’t use return in a function, it returns None by default. Your code was correct if your function was like this:

def print_name(name):
    return name

print(print_name('Annabel Lee'))

answered Feb 10, 2019 at 19:41

Heyran.rs's user avatar

Heyran.rsHeyran.rs

5011 gold badge10 silver badges20 bronze badges

Your function is not returning anything that’s why it is giving None.
An non-returning function is returned with None.

answered Feb 10, 2019 at 19:33

bhalu007's user avatar

bhalu007bhalu007

1311 silver badge10 bronze badges

The print() function evaluates the arguments in the parentheses and print the result.
print(1+1) will print «2», since the result of 1+1 is 2. Just like that, print("abcd".upper()) will print «ABCD».

When you call print(print_name('Annabel Lee')), the print function tries to evaluate the argument, in this case, print_name('Annabel Lee'). Since the print_name() function does not return any value (it just prints ‘Annabel Lee’), the returned value is None. This is why the print() function print «None».

answered Feb 10, 2019 at 19:57

Michael T's user avatar

Michael TMichael T

3704 silver badges16 bronze badges

One of the data types provided by Python is the NoneType which you might have found when coding in Python if you have seen the keyword None.

NoneType is a Python data type that shows that an object has no value. None is the only object of type NoneType and you can use it to show that a variable has no value. None can also be used when a function doesn’t return a value or for defining an optional parameter in a function.

Are you ready to learn how to use None in this tutorial?

What Is NoneType in Python?

The NoneType in Python is a data type that represents the absence of a value or a null value. The None object is the only Python object of type NoneType.

Using the type() function in the Python shell we can see that None is of type NoneType.

>>> type(None)
<class 'NoneType'>

Now try to assign the value None to a variable. You will see that the type of that variable is also NoneType.

>>> x = None
>>> type(x)
<class 'NoneType'>

How to Check For NoneType in Python?

How can you check if a Python object is of type NoneType or, in other words, if the value of the object is equal to None?

To verify if a Python object is equal to None you can use Python’s “is operator”. You can also apply its negation using the “is not operator”.

For example, let’s take a variable called number and assign the value None to it.

Then use an if / else statement and the is operator to check if the value of this variable is None or not.

>>> number = None
>>> 
>>> if number is None:
...     print("The variable number is equal to None")
... else:
...     print("The variable number is not equal to None")
... 
The variable number is equal to None

Using the is operator we have correctly detected that the value of the variable number is None.

But, how does this work exactly?

To understand that we will simply check the value returned by the expression that uses the is operator.

>>> number is None
True

The expression using the is operator returns a boolean with the value True meaning that the variable number is equal to None.

Now, assign a value to the variable number and execute the expression again.

>>> number = 10
>>> number is None
False

This time we get back False because the variable is not equal to None.

We can also reverse the logic of the expression using the “is not” Python operator.

>>> number is not None
True

As expected, in this case, the result is a boolean with the value True.

Is None the Same as Undefined in Python?

If it is the first time you learn about None in Python, you might think that None and undefined are the same thing in Python.

This is not the case…

By default a variable is undefined and its value becomes None only if you assign this value to it or if the variable is returned by a function that returns None.

Let’s see this in practice:

>>> print(result)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'result' is not defined

We have printed the value of the variable result without assigning a value to it. That’s why we get back an error message that says that this variable is not defined.

If you try to access a Python variable before assigning a value to it the Python interpreter throws a NameError exception because the variable you are trying to access is undefined.

Now let’s assign the value None to the variable result.

>>> result = None
>>> print(result)
None

This time we don’t get an error back when we print the value of the variable result. We get back the value None.

This shows that None and undefined are not the same thing in Python.

Can a Python Function Return None?

A Python function can return None and this usually happens if the function doesn’t have a return statement or a return value. An example of a function that returns None is the print() function.

>>> print(print("Hello"))
Hello
None

The first “Hello” message is the output of the inner print() function. The None value is the output of the outer print() function that prints the value returned by the inner print() function.

To make sure this concept is clear, let’s define a custom Python function that doesn’t return any value.

First of all, we define a function called custom that returns the integer 1.

>>> def custom():
...     x = 1
...     return x
... 
>>> print(custom())
1

You can see that when we print the value returned by the function we get back the integer one.

Now update the function by removing the return statement, then print the output of the function again.

>>> def custom():
...     x = 1
... 
>>> print(custom())
None

The value returned by the function is None because the function doesn’t have a return statement.

Now, try to add the return statement without returning any value.

>>> def custom():
...     x = 1
...     return
... 
>>> print(custom())
None

Even in this case, the value returned by the function is None because even if the return statement is present that statement doesn’t return any value.

None as Default Value For Optional Parameters

In Python, None is often used as the default value for optional parameters in a function. Passing different values for optional parameters allows customization of the function’s behaviour.

To explain how you can use None with an optional parameter let’s create a function that prints a simple message.

def say_hello():
    print("Hello user!")

Let’s call the function and confirm it works fine:

say_hello()

[output]
Hello user!

Now, let’s add the parameter name to the function. We will make this parameter optional.

To make the parameter of a Python function optional you can assign the value None to it in the function signature.

def say_hello(name=None):
    if name is None:
        print(f"Hello user!")
    else:
        print(f"Hello {name}!")

You can see that in the implementation of the function we are using the is operator to check if the optional parameter name is equal to None or not. Depending on that we execute one of the two print statements.

# Without passing the optional argument
say_hello()

# Passing the optional argument
say_hello('Codefather')

[output]
Hello user!
Hello Codefather!

How Do You Set a Variable to null in Python?

In other programming languages, a variable that doesn’t refer to any object is represented with the value null.

Let’s see if the value null is applicable to Python.

>>> number = null
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'null' is not defined

When we try to assign the value null to a variable we get back a NameError because the name “null” is not defined in Python.

The value null is not applicable to the Python programming language. To represent the concept of null you can use the value None.

Is None the Same as Zero or Empty String in Python?

None in Python is not the same as 0, is not the same as an empty string, and is not the same as a boolean with value False. None is a specific value that represents null objects and variables.

How to Fix Python TypeError: NoneType object is not iterable

Are you executing a Python program and are you getting the following error?

TypeError: 'NoneType' object is not iterable

How can you solve this error in Python?

This error is caused by the fact that you are trying to iterate over an object that has a value equal to None.

For example, imagine you are using a for loop to go through the elements of a Python list but the value of the list, for some reason, is None.

>>> numbers = None
>>> for number in numbers:
...     print(number)
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable

We have set the value of the list numbers to None. Then while iterating through the list using a for loop the Python interpreter throws the error “TypeError: ‘NoneType’ object is not iterable”.

Once again, this TypeError in Python occurs because the list we are iterating through is equal to None and hence it’s not an iterable object.

In this case, the root cause of the problem is obvious because we have assigned None explicitly to the numbers variable.

In the normal execution of a program, it might be a bit more difficult to understand why the variable you are iterating through is equal to None considering that its value might be the result of another function called by your Python code.

Conclusion

Now you should have an understanding of what None is in Python and how you can use it in your programs.

You have seen that None is of type NoneType, that you can assign it to a variable, and that you can use it as a return value in a function and also to set optional function parameters.

Related article: in this tutorial, we have briefly discussed custom Python functions. Read the Codefather tutorial that will teach you how to create your Python functions.

Claudio Sabato - Codefather - Software Engineer and Programming Coach

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Понравилась статья? Поделить с друзьями:
  • Nothing here ошибка
  • Notepad поиск ошибок
  • Notepad ошибка при сохранении файла
  • Node js ошибка 403
  • Node js не устанавливается на windows 10 ошибка