What is None in Python

Опубликовано: 09 Октябрь 2024
на канале: Parag Dhawan
341
9

In Python, None is a built-in constant that represents the absence of a value or the lack of a value. It is often used to indicate the absence of a return value or the absence of a default value for a function argument.

Here are some examples of using None in Python:

Function that returns None
def my_function():
print('Hello, World!')

result = my_function() # Output: 'Hello, World!'
print(result) # Output: None

Hello, World!
None

In the above example, we define a function my_function() that prints a message but does not return a value. When we call this function, the return value is None.

Function with default value of None
def my_function2(arg=None):
if arg is None:
arg = 'default value'
print(arg)

my_function2() # Output: 'default value'
my_function2('new value')# Output: 'new value'

default value
new value

We also define a function my_function2() that takes an optional argument arg. If no argument is provided, the default value of arg is None. Inside the function, we check if arg is None and if so, we assign it a default value. We then print the value of arg.

None is often used as a sentinel value to represent the absence of a value. It can be used in a variety of contexts, such as to indicate the absence of a key in a dictionary or to represent the absence of a match in a regular expression.

Overall, None is a useful built-in constant in Python that represents the absence of a value or the lack of a value.

‪@ParagDhawan‬

https://paragdhawan.blogspot.com/2023...