Python Functions
About Python functions
In Python, a function is a block of reusable code that performs specified task when it is called.
Python has a number of built-in functions. Moreover, it allows programmers to define their own functions.
Python function needs to be called.
Python function can take zero or single or multiple parameters.
Python function may have return type or not.
Typical syntax of Python function
-
def: The 'def' keyword is used to start the function definition. -
function_name: This is the name of a function. Replace it with a meaningful name. -
parameter:Parameter is optional. You can pass data to the function using parameters. -
# code to perform the task: The block of code to perform the specific tasks. -
return result: This is used to return a value from the function.
Please remember, a function name is followed by a parentheses '()'. Parameters are placed inside the parentheses. Colon ':' is part of the syntax. Use parentheses with function name, when a function is defined or called.
Create and Call Python Function
Following is a typical example of creating and calling a Python function:
Example of Python function
Output of the above example
Hello world!
Explanation of example:
-
def print_Message(messageParameter):This line defines a function named 'print_Message' with a parameter named 'messageParameter'. -
print(messageParameter): The code block to be executed when the 'print_Message' function is called. It will print the messege passed as parameter. -
print_Message("Hello world!"): The 'print_Message' function is called passing "Hello world!" as value for 'messageParameter'.
Calling Python function: You can call a Python function by using its name followed by parentheses. You need to pass parameters if the function has parameters.
Python function return type
In Python, a function may return a value or may not return any value. It is optional to specify the return type of a Python function. If you specify the return type, it is called type hinting. Type hinting is used to indicate the expected data type of the return value of a function.
Python function may be defined without specifying the return type as demonstrated in the following example:
Example of function without type hints
Output of the above example
The sum is: 13
Explanation of example:
-
def addNumber(a, b):defines a function named 'addNumber' that takes two parameters 'a' and 'b'. Types of the parameters are not specified. -
return a + b: This line adds 'a' and 'b' using '+' operator and return the added value. Here return type is not specified. It will be resolved dynamically. -
sum = addNumber(6, 7): The code block calls the 'addNumber' function passing '6' and '7' as parameters and returned value is stored in 'sum' variable. -
print("The sum is:", sum): The line prints the returned value sored in 'sum'.
Python function may be defined by specifying the return type as demonstrated in the following example:
Example of function with type hints
Output of the above example
The sum is: 13
Explanation of example:
-
def addNumber(a: int, b: int) -> int:: This defines a function named 'addNumber' that takes two parameters 'a' and 'b'. Types of the parameters are specified as 'int'. Return type of the function is int as defined using-> intcode. -
return a + b: This line adds 'a' and 'b' using '+' operator and return the added value. Here return type is specified as 'int' but it will be resolved dynamically at runtime. If the function returns a value of type other than 'int', it will not raise an error but it will be a violation of type hinting. -
sum = addNumber(6, 7): The code block calls the 'addNumber' function passing '6' and '7' as parameters and returned value is stored in 'sum' variable. -
print("The sum is:", sum): The line prints the returned value sored in 'sum'.
Python function with different types of parameters & arguments
In Python, the terms "parameters" and "arguments" are related to one another in function.
Parameters are the variables placed inside the parentheses in the function when it is defined.
Arguments are the values passed to the function against the parameters when it is called.
There are different types of parameters in Python function.
1. Positional Parameters
In Python function, positional parameters are defined in a specific order and arguments are passed to the function according to the order of the parameters.
Example of positional parameters
Output of the above example
Hello, John!
Explanation of example:
-
def greeting(name, message):: This line defines a function named 'greeting' with two parameters 'name' and 'message'. -
print(f"{message}, {name}!"): It will print the message when the function is called. -
greeting("John", "Hello"): The 'greeting' function is called passing 2 arguments "John" and "Hello" following the order of parameters 'name' and 'message'.
2. Default Parameters
In Python function, default parameters are defined with default values. It is optional to pass arguments for default parameters when the function is called. If no argument is provided, the default value is used in the function.
Example of default parameters
Output of the above example
Hello, John!
Good Morning, Joe!
Explanation of example:
-
def greeting(name, message = "Hello"):: This line defines a function named 'greeting' with two parameters 'name' and 'message'. The 'message' parameter has a default value "Hello". -
print(f"{message}, {name}!"): It will print the message when the function is called. -
greeting("John"): The 'greeting' function is called passing only one argument "John" for 'name' parameter. Here the function uses default value of 'message' parameter and the output of the function is 'Hello, John!'. -
greeting("Joe", "Good Morning"): Here the 'greeting' function is called passing two argument "John" for 'name' parameter and "Good Morning" for 'message' parameter. Here the function replaces the default value of 'message' parameter and the output of the function is 'Good Morning, Joe!'.
3. Keyword Parameters
In Python function, keyword parameters are defined not to follow the order of parameters when arguments are passed. It is necessary to explicitly specify the names of the parameters with arguments (values).
Example of keyword parameters
Output of the above example
Good Morning, Joe!
Explanation of example:
-
def greeting(name, message):: This line defines a function named 'greeting' with two parameters 'name' and 'message'. -
print(f"{message}, {name}!"): It will print the message when the function is called. -
greeting(message = "Good Morning", name = "Joe"): Here the 'greeting' function is called passing two arguments "Good Morning" for 'message' parameter and "Joe" for 'name' parameter. The names of the paramters are specified along with the arguments (message = "Good Morning" and name = "Joe") without following the order of parameters. Still the output of the function is 'Good Morning, Joe!'.
4. Variable-length Positional Parameters (*args)
In Python function, variable-length positional parameters allow a function to accept an arbitrary number of positional arguments. These arguments are accessible as a tuple within the function. '*' sign is used before the parameter.
Example of variable-length positional parameters
Output of the above example
Hello, Alice!
Hello, John!
Hello, Joe!
Explanation of example:
-
def greeting(*names):: This line defines a function named 'greeting' with a variable-length positional parameter '*name'. -
for name in names:: This line defines a for loop through parameter 'names' which is used as a tuple. -
print(f"Hello, {name}!"): It will print the message when the function is called. -
greeting("Alice", "John", "Joe"): Here the 'greeting' function is called passing three arguments "Alice", "John" and "Joe" for 'names' parameter. The output of the function is three message for three persons: 'Hello, Alice!', 'Hello, John!' and 'Hello, Joe!.'
5. Variable-length Keyword Parameters (**kwargs)
In Python function, variable-length keyword parameters allow a function to accept an arbitrary number of keyword arguments. These arguments are accessible as a dictionary within the function.
Arguments passed as key-value pairs are treated as keyword arguments. '**' sign is used before the parameter.
Keyword arguments are passed as key-value pairs. The keys are the parameter names and the values are the corresponding argument values.
Conventionally, '**kwargs' is used for variable-length keyword parameters. You can replace 'kwargs' with your parameter name.
Example of variable-length keyword parameters
Output of the above example
Hello, Alice!
Good morning, John!
Explanation of example:
-
def greeting(**kwargs):: This line defines a function named 'greeting' with a variable-length keyword parameter '**kwargs'. -
for name, message in kwargs.items():: This line defines a for loop through the items of parameter 'kwargs' which is used as a dictionary in the function. -
print(f"{message}, {name}!"): It will print the message when the function is called. -
greeting(Alice = "Hello", John = "Good morning"): Here the 'greeting' function is called passing two argumentsAlice = "Hello"andJohn = "Good morning"for 'kwargs' parameter as key-value paired. The output of the function is two messages for two persons: 'Hello, Alice!' and 'Good morning, John!'.
6. Positional-only Parameters
In Python function, positional-only parameters are specified by placing a '/' in the parameter list. Arguments must be passed in order of parameters without specifying the parameter names. Parameters before '/' are treated as position-only parameters.
Example of position-only parameters
Output of the above example
Good Morning, Joe!
Explanation of example:
-
def greeting(name, /, message):: This line defines a function named 'greeting' with two parameters 'name' and 'message' with '/' in the list of parameters. -
print(f"{message}, {name}!"): It will print the message when the function is called. -
greeting( "Joe", "Good Morning"): Here the 'greeting' function is called passing two arguments "Joe" and "Good Morning"' without specifying the names of parameters. The output of the function is 'Good Morning, Joe!'. - If you specify the name of 'name' parameter but not specifying the 'message' parameter as shown in the following code, it raises an exception: 'SyntaxError: positional argument follows keyword argument'. You can not specify the name of 'name' parameter because it is a positional-only parameter. But you can specify the name of 'message' parameter because it is not a positional-only parameter.
7. Keyword-only Parameters
In Python function, keyword-only parameters are specified by placing a '*' in the parameter list. Arguments must be passed in order of parameters by specifying the parameter names. Parameters after '*' are treated as keyword-only parameters.
Example of keyword-only parameters
Output of the above example
Good Morning, Joe!
Explanation of example:
-
def greeting(*, name, message):: This line defines a function named 'greeting' with two parameters 'name' and 'message' with '*' in the list of parameters. Here parameters are keyword-only parameters. -
print(f"{message}, {name}!"): It will print the message when the function is called. -
greeting(name = "Joe", message= "Good Morning"): Here the 'greeting' function is called passing two arguments name = "Joe" and message= "Good Morning" with specifying the names of parameters. The output of the function is 'Good Morning, Joe!'. -
greeting(name = "Joe", "Good Morning"): Here the 'greeting' function is called specifying the name of 'name' parameter but not specifying the 'message' parameter. It raises an exception: 'SyntaxError: positional argument follows keyword argument'.
Python Compiler For Live Practice
Practice the above Python code in the following Python Editor. Create more Python functions with different parameters in the following Python code editor and click Execute button to check the output. Output will be displayed in Python Code Output section.
Python Editor