Function Structure
Function is a reusable block of code that has 2 parts:
- A
defstatement that defines the function name – E.g.def example_1():ordef example(param_in): - Function body that contains a block of code that will be executed when the function is called
The following snippet will declare a function, but it won’t execute it:
Example
def example_1(): # Define a function named example_1
temp_val = 10 # Create a local variable temp_val and assign it the value 10
print(temp_val) # Print the value of temp_val when the function is called
def example_1():
temp_val = 10
print(temp_val)
Result
If you want to execute\call it, use example_1() somewhere else without def statement:
Example
def example_1(): # Define a function named example_1
temp_val = 10 # Create a local variable temp_val and assign it the value 10
print(temp_val) # Print the value of temp_val when the function is called
example_1(): # Call the function to execute its code
def example_1():
temp_val = 10
print(temp_val)
example_1()
Result
10
Function
You can define a function using the def statement, followed by the function’s name, then (): and the rest have to be indented (spaces or tabs). To call the function, use the function name + ().
Example
def temp_function(): # Define a function named temp_function that takes no parameters
print(“What’s up”) # Print the message “What’s up” when the function is calledtemp_function() # Call the function to execute its code
def temp_function():
print("What's up")
temp_function()
Result
What's up
Also, you can define a function that takes arguments using the def statement, followed by the function’s name, then add your parameters inside (): and the rest has to be indented (spaces or tabs). To call the function, use the function name + the arguments inside().
Example
def temp_function(param): # Define a function named temp_function with one parameter called param
print(param) # Print the value passed into param when the function is calledtemp_function(“What’s up”) # Call the function and pass the string “What’s up” as an argument
def temp_function(param):
print(param)
temp_function("What's up")
Result
What's up
Functions Arguments & Parameters
To pass arguments to a function E.g. Tim, declare a function and add parameters inside the parentheses what_is_your_name(first_param):
Example
def what_is_your_name(first_param): # Define a function that takes one parameter called first_param
print(“You passed”, first_param) # Print the message along with the value passed to the functionwhat_is_your_name(“Tim”) # Call the function with a string
what_is_your_name(1) # Call the function with an integer
what_is_your_name([“Nancy”, 2]) # Call the function with a list containing a string and an integer
def what_is_your_name(first_param):
print("You passed", first_param)
what_is_your_name("Tim")
what_is_your_name(1)
what_is_your_name(["Nancy",2])
Result
You passed Tim
You passed 1
You passed ['Nancy', 2]
Multiple Arguments & Parameters
You can pass multiple arguments to a function if a function is declared with multiple parameters. You cannot declare a function with duplicate parameters; they must be unique. E.g. you declared def sayFirstLast(first, last): that has first and last as parameters and prints(first, last) in the body.
Example
def sayFirstLast(first, last): # Define a function with two parameters: first and last
print(first, last) # Print the values of first and last separated by a spacesayFirstLast(“Dennis”,”Smith”) # Call the function with first=”Dennis” and last=”Smith”
sayFirstLast(“Sara”,”Mars”) # Call the function with first=”Sara” and last=”Mars”
def sayFirstLast(first, last):
print(first, last)
sayFirstLast("Dennis","Smith")
sayFirstLast("Sara","Mars")
Result
Dennis Smith
Sara Mars
Re-declaring Functions
You can declare or re-declare a function using the same def statement. If you have a function named say_hello() that prints Hello, you can re-declare again and change Hello to Hi (Because Python executes code line by line)
Example
def say_hello(): # Define a function named say_hello
print(“Hello”) # Print “Hello” when the function is calledsay_hello() # Call the first version of say_hello
def say_hello(): # Redefine the function say_hello (overwrites the previous one)
print(“Hi”) # Print “Hi” when the new function is calledsay_hello() # Call the new version of say_hello
def say_hello():
print("Hello")
say_hello()
def say_hello():
print("Hi")
say_hello()
Result
Hello
Hi
Function Return
If you want to return a value from a function, use the return statement. Let’s say that you have a function named multiply_by_4 that multiplies any number you pass to it (It does not output the number); you can get the result using the return statement.
Example
def say_hello(param_1): # Define a function that takes one parameter called param_1
return param_1 * 4 # Return the value of param_1 multiplied by 4returned_value = say_hello(10) # Call the function with 10; the result (10*4=40) is stored in returned_value
print(returned_value) # Print the value stored in returned_value → Output: 40
print(say_hello(100)) # Call the function with 100; returns 100*4=400
print(say_hello(say_hello(1))) # Nested call: Inner say_hello(1) returns 1*4 = 4, outer say_hello(4) returns 4*4 = 16
def say_hello(param_1):
return param_1 * 4
returned_value = say_hello(10)print(returned_value)
print(say_hello(100))
print(say_hello(say_hello(1)))
Result
40
400
16
Empty Function
A function with an empty block will cause an error. E.g. IndentationError: expected an indented block. To write an empty function, you can use the pass statement in the body.
def empty_function(): # Define a function named empty_function that does nothing
pass # pass is a placeholder; it allows the function to exist without any actionempty_function() # Call the function; nothing happens because it contains only pass
Example
def empty_function():
pass
empty_function()
Result
Function Overloading
You can use the function overloading technique to define multiple functions with the same name but taking different arguments
Example
from functools import singledispatch # Import singledispatch to create a function that behaves differently based on input type
@singledispatch
def temp_function(param_in): # Define the generic function for types that don’t have a specific handler
print(“Other:”, param_in) # Default behavior for unregistered types@temp_function.register(int) # Register a special behavior for int type
def _(param_in):
print(“Integer:”, param_in) # Print “Integer:” followed by the value if param_in is an int@temp_function.register(str) # Register a special behavior for str type
def _(param_in):
print(“String:”, param_in) # Print “String:” followed by the value if param_in is a stringtemp_function(1) # Call with an int
temp_function(“Test”) # Call with a string
temp_function({1,2,3}) # Call with a set
from functools import singledispatch
@singledispatch
def temp_function(param_in):
print("Other:", param_in)
@temp_function.register(int)
def _(param_in):
print("Integer:", param_in)
@temp_function.register(str)
def _(param_in):
print("String:", param_in)
temp_function(1)
temp_function("Test")
temp_function({1,2,3})
Output
Integer: 1
String: Test
Other: {1, 2, 3}