Вывод none в python

Why is «None» printed after my function’s output?

The accepted answer explains the importance of return ing a value from the function, rather than print ing it. For more information, see What is the purpose of the return statement? How is it different from printing?. To understand the None result itself, see What is a ‘NoneType’ object?. If you are print ing inside the function in order to see multiple values, it may be better to instead collect those values so that they can be printed by the calling code. For details, see How can I use `return` to get back multiple values from a loop? Can I put them in a list?.

@Georgy I’ve edited the canonical for that link into the question. I’ve been doing a fair bit of work cleaning up canonicals for Python questions lately.

7 Answers 7

It’s the return value of the function, which you print out. If there is no return statement (or just a return without an argument), an implicit return None is added to the end of a function.

You probably want to return the values in the function instead of printing them:

def jiskya(x, y): if x > y: return y else: return x print(jiskya(2, 3)) 

@MichaWiedenmann I could not find any statement to that effect in the Python reference, but here is the comment (and code) adding the return None in cpython.

Читайте также:  Css не качает с сервера

@PatrickT In the example of the question that makes no sense, but yes, if you want your function to return None then return None is great, and probably clearer than just a bare return .

@phihag: I didn’t find one in the reference, but the official tutorial on defining functions says: «The return statement returns with a value from a function. return without an expression argument returns None . Falling off the end of a function also returns None .»

Ok, to start off when you do this:

You getting something pretty much equivalent to this:

So, what is going on? The print(2) is printing out 2, and returns None which is printed by the outer call. Straightforward enough.

You get 2 because if you print out a function you get whatever the return value is. (The return value is denoted by the return someVariable .

Now even though print doesn’t have parenthesis like most functions, it is a function just a little special in that respect. What does print return? Nothing. So when you print print someVariable , you will get None as the second part because the return value of print is None .

def jiskya(x, y): if x > y: print(y) else: print(x) 
def jiskya(x, y): if x > y: return y else: return x 

What if the print argument is in a while loop? If I replace «print» with «return», then I can only get one value printed instead of the full iteration.

It’s what the function returned.

In Python, every function returns something. It could «be multiple things» using a tuple, or it could «be nothing» using None , but it must return something. This is how we deal with the fact that there is no way to specify a return type (which would make no sense since you don’t specify types for anything else). When interpreted as a string for printing, None is replaced with the string «None».

None is a special object that is supposed to represent the absence of any real thing. Its type is NoneType (it is an instance of that class). Whenever you don’t explicitly return anything, you implicitly return None.

You wrote the function to print one of the two values x or y , but not to return anything. So None was returned. Then you asked Python to print the result of calling the function. So it called the function (printing one of the values), then printed the return value, which was None , as the text «None».

Источник

Почему функция выводит 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 

Источник

Почему выводит none в консоль. (python 3.7.8)

вы возвращаете то, что возвращает функция print() , а функция print() всегда возвращает None .

Вы наверно хотели вернуть строку — значит, удалите print из команды return и добавите еще одно return :

if year_div == 0: return '<> is leap year.'.format(year_input) else: return '<> year is not leap year'.format(year_input) 

В вашем коде input берет аргумент print(‘Enter year: ‘), функция print печатает Enter year: , а потом input печатает значение функции print, которая возвращает None. Так же input возвращает тип str, поэтому не нужно прописывать str()

def is_year_leap(): year_input = input('Enter year: ') year_div = int(year_input) % 4 if year_div == 0: print('<> is leap year.'.format(year_input)) else: print('<> year is not leap year'.format(year_input)) is_year_leap() 

смотрим строку year_input = str(input(print(‘Enter year: ‘)))

  1. str — убираем, т.к. результат и так str year_input = input(print(‘Enter year: ‘))
  2. так как вы написали, это все равно что: val = print(‘Enter year: ‘) input(val) посмотрите что такое val print(val)
  3. пишем так: year_input = input(‘Enter year: ‘)

Похожие

Подписаться на ленту

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.7.21.43541

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Источник

Вывод none в python

Last updated: Feb 18, 2023
Reading time · 3 min

banner

# Why does my function print None in Python [Solved]

Functions often print None when we pass the result of calling a function that doesn’t return anything to the print() function.

All functions that don’t explicitly return a value, return None in Python.

Copied!
def example(): print('bobbyhadz.com') print(example()) # 👇️ Output # bobbyhadz.com # None

all functions that dont return value return none

Notice that we called the print() function twice.

When we call the example() function, the print() function gets called with hello world , and then we print the result of calling the example() function.

# Functions that don’t return anything return None

The example function doesn’t return anything, so it ends up implicitly returning None , so None gets printed.

If we were to return a value from the function, the value would get printed.

Copied!
def example(): print('bobbyhadz.com') return 'abc' print(example()) # 👇️ Output # bobbyhadz.com # abc

We used the return statement to return a value from the function.

Now when the example() function is called, we print the strings bobbyhadz.com and abc , instead of None .

If you don’t want to return anything from the function, remove the print() call when calling the example() function.

Copied!
def example(): print('hello world') example() # 👇️ Output # hello world

There is no point in printing the result of calling a function that doesn’t return anything because we’re always going to print None .

# The most common sources of None values in Python

The most common sources of None values are:

  1. Having a function that doesn’t return anything (returns None implicitly).
  2. Explicitly setting a variable to None .
  3. Assigning a variable to the result of calling a built-in function that doesn’t return anything.
  4. Having a function that only returns a value if a certain condition is met.

Note that there are many built-in functions (e.g. sort() ) that mutate the original object in place and return None .

# Some built-in methods return None

Some built-in functions, such as sort() , append() , extend() return None because they mutate the object in place.

Copied!
a_list = ['z', 'a', 'b', 'c'] print(a_list.sort()) # 👉️ None print(a_list) # 👉️ ['a', 'b', 'c', 'z']

some built in methods return none

Notice that the call to the list.sort() method printed None .

The list.sort() method sorts a list in place and returns None .

Make sure to not store the result of calling methods that return None in variables.

Copied!
a_list = ['z', 'a', 'b', 'c'] # ⛔️ don't do this result = a_list.sort() print(result) # 👉️ None print(a_list) # 👉️ ['a', 'b', 'c', 'z']

There is a convention in Python for methods that mutate an object in place to return None .

# A function that returns a value only if a condition is met

Another common source of None values is having a function that returns a value only if a condition is met.

Copied!
def get_list(a): if len(a) > 3: return a # 👇️ None my_list = get_list(['a', 'b']) print(my_list) # 👉️ None

functions returning value only if condition is met

The if statement in the get_list function is only run if the passed in argument has a length greater than 3 .

To get around this, we could return a default value if the condition is not met, e.g. an empty string, an empty list, 0 , or any other value that suits your use case.

Copied!
def get_list(a): if len(a) > 3: return a return [] # 👈️ return an empty list if condition not met # 👇️ [] my_list = get_list(['a', 'b']) print(my_list) # 👉️ []

Now the function is guaranteed to return a value regardless if the condition is met.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью