Functions in Python🤗
Functions
- Built-in functions, such as
help()
to ask for help,min()
to get the minimum value,print()
to print an object to the terminal,… - User-Defined Functions (UDF 's), which are functions that users create to help them out;
- Anonymous functions, which are also called lambda functions because they are not declared with the standard
def
keyword.
The four steps to defining a function in Python are the following:
- Use the keyword
def
to declare the function and follow this up with the function name. - Add parameters to the function: they should be within the parentheses of the function. End your line with a colon.
- Add statements that the functions should execute.
- End your function with a return statement if the function should output something. Without the return statement, your function will return an object
None
.
There are several types by which arguments can be passed, they are Default arguments, Keyword arguments and Arbitrary arguments.
Default arguments:
Default arguments in Python functions are those arguments that take default values if no other values are passed to these arguments from the function call. The below code is an example of how to define a function with one default argument.
you can also pass values through the default arguments and while defining you must place the default argument at last.
Example
def sum(a=5,b):
OUTPUT
Keyword arguments:
Arbitrary arguments:
If you want to pass an iterable argument through a function you can use this syntax is * symbol before the argument.
def sq(*a):
return a**2
print(sq(1,2,3,4,5))
Lambda function:
They are also known as an anonymous function, not defined with any name. For simple one or two-line functions we can use lambda functions instead of the traditional methods.
lambda arguments : expression
x = lambda a : a + 10
print(x(5))15x= lambda a: a**2
print(x(7))49
Comments
Post a Comment