Python functions
Created By: chatGPT
Functions in Python are defined using the
def
keyword. A function is a block of code that only runs when it is called. You can pass data, known as parameters, into a function and it can return data as a result.def greet(name):
return f'Hello, {name}!'
In the example above, we defined a function called
greet
that takes one parameter, name
. It uses an f-string to return a greeting message.print(greet('Alice')) # Output: Hello, Alice!
Functions can have default parameter values. If no value is provided for a parameter, the default value will be used.
def greet(name='Guest'):
return f'Hello, {name}!'
Now, if we call
greet()
without any argument, it will use the default value 'Guest'.print(greet()) # Output: Hello, Guest!
You can also define functions that can take an arbitrary number of arguments using
*args
. This allows you to pass a variable number of arguments to the function.def add_numbers(*args):
return sum(args)
In this example,
add_numbers
can take any number of arguments and return their sum.print(add_numbers(1, 2, 3, 4)) # Output: 10
Similarly, to pass key-value pairs, you can use
**kwargs
, which allows you to handle named arguments.def display_info(**kwargs):
for key, value in kwargs.items():
print(f'{key}: {value}')
This function prints each key-value pair passed to it. You can call
display_info
with any number of named arguments.display_info(name='Alice', age=30, city='New York')
Remember, a return statement is used to exit a function and return a value. If a function does not return a value, Python will return
None
by default.def square(x):
return x ** 2
You can use this function to calculate the square of a number.
print(square(4)) # Output: 16