Sunday, July 23, 2023

Functions in Python

What is a Function?

A function is a block of code.

It runs when it is called with pair of parenthesis at the end.

There are some functions which are built-in like: print(), input(), type(), len(), list(), etc.

There are also functions which are user defined.

We can pass data to function through parameter. Parameters are separated by commas.

We can pass any number of arguments into a function.

And a function can return data as result.

Parameters or Arguments ?

Both term’s are used for the Information passed into a function

First Function

A function is defined using the “def” keyword.

A function has a name and a body.

It may or may not have parameters (or arguments).

def my_function():
 print("Hello from a function")

Name: my_function Arguments: no args Body: print()

Problem

  • Create a function that takes an integer as input and tells whether it is divisible by 7.
 
def div_by_7(x):
    if x % 7 == 0:
        print("yes, it is divisible by ")
    else:
        print("no, not divisible by 7")

x = int(input("Enter a natural number: "))

div_by_7(x)

Problem: Passing of Arguments (With Name and Without Name)

# Passing arguments with keywords i.e ( bind arguments with parameters name )

# Ordering of parameter has no mean in this case

# define a function with three parameter

def get_youngest_child(child3, child2, child1):   
  print("The youngest child is " + child3)

# What will be output?

get_youngest_child("Emil", "Tobias", "Linus")

# Calling of function by passing key value pairs, order does not matter

get_youngest_child(child1 = "Emil", child2 = "Tobias", child3 = "Linus") 

Argument Passing With / Without Names

Argument passing by positions:

First argument goes to the first variable, second argument goes to the second variable, so on, so forth.

def get_youngest_child(child3, child2, child1):
  get_youngest_child("Emil", "Tobias", "Linus") 

Argument passing by name

def get_youngest_child(child3, child2, child1): 
get_youngest_child(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Method vs. Function: Difference Between Methods and Function

Definition Method: Method definitions are always present inside a class. Function: No class is needed to define a function. Association Method: Associated with the class object. Function: Not associated with any objects. Call Method: It is called on an object. Function: It is called by its name. Dependency Method: It depends on the class they belong to. Function: It doesn’t depend on any class, i.e., it is an identical entity. self Method: It requires the self as its first argument. Function: It doesn’t require any self-argument. Operation Method: It operates on the data of the object it associates with. Function: It operates on the data that you pass to them as an argument.

Local Variable and Global Variable

Take a look at this code:
If you run the program, you will get the output below. INSIDE THE FUNCTION Global Variable Local Variable OUTSIDE THE FUNCTION Global Variable NameError: name 'message2' is not defined In the code above, message1 is a global variable while message2 is a local variable declared inside the function myFunction(). Within the function, both the local and global variables are accessible. Outside the function, the local variable message2 is no longer accessible. We get a NameError when we try to access it outside the function. The second concept to understand about variable scope is that if a local variable shares the same name as a global variable, any code inside the function is accessing the local variable. Any code outside is accessing the global variable. Try running the code below:
You’ll get the output as follows: INSIDE THE FUNCTION Local Variable (shares same name as a global variable) OUTSIDE THE FUNCTION Global Variable (shares same name as a local variable)

Default Parameter Values

Now that we understand how functions and variable scope work, let us look at some interesting variations that Python allows when defining a function. First, let’s look at default values. Python allows us to define default values for the parameters of a function. If a parameter has a default value, we do not have to pass in any value for the parameter when calling the method. For instance, suppose a function has 5 parameters a, b, c, d and e. We can define the function as def someFunction(a, b, c=1, d=2, e=3): print(a, b, c, d, e) Here, we assign default values for the last three parameters. All parameters with default values must be placed at the end of the parameter list. In other words, we cannot define a function as follows because r comes after q which has a default value: def someIncorrectFunction(p, q=1, r): print(p, q, r) To call someFunction(), we can write someFunction(10, 20) we’ll get 10, 20, 1, 2, 3 We do not have to pass in any values for c, d and e. If we write someFunction(10, 20, 30, 40) we’ll get 10, 20, 30, 40, 3 The two additional arguments that we pass in (30 and 40) are assigned to the parameters with default values in order. Hence, 30 replaces the default value for c while 40 replaces d.

Variable Length Argument List

In addition to having default values for parameters, Python also allows us to pass a variable number of arguments to a function. This is very useful if we do not know the number of arguments a function has in advance. For instance, we may have a function that adds a series of numbers, but we do not know how many numbers there are in advance. In cases like this, we can use the * symbol. The example below shows how this can be done. def addNumbers(*num): sum = 0 for i in num: sum = sum + i print(sum) When we add a single asterisk in front of num, we are telling the compiler that num stores a variable-length argument list that contains several items. The function then loops through the argument to find the sum of all the numbers and return the answer. To call the function, we write addNumbers(1, 2, 3, 4, 5) we’ll get 15 as the output. We can also add more numbers by writing addNumbers(1, 2, 3, 4, 5, 6, 7, 8) we’ll get 36 as the output. As we can see in the examples above, when we add an asterisk in front of a parameter name, we can pass in a variable number of arguments to the function. This is known as a non-keyworded variable length argument list. If we want to pass in a keyworded variable length argument list to the function, we can use double asterisks. For instance, consider the following example: def printMemberAge(**age): for i, j in age.items(): print("Name = %s, Age = %s" %(i, j)) This function has a parameter called age. The double asterisks denote that this parameter stores a keyworded variable length argument list, which is essentially a dictionary. The for loop then loops through the argument and prints out the values. To call the function, we can write printMemberAge(Peter = 5, John = 7) we’ll get Name = Peter, Age = 5 Name = John, Age = 7 If we write printMemberAge(Peter = 5, John = 7, Yvonne = 10) we’ll get Name = Peter, Age = 5 Name = John, Age = 7 Name = Yvonne, Age = 10 If our function uses a normal argument (also known as a formal argument), a non-keyworded variable length argument list and a keyworded variable length argument list, we must define the function using the following order: def someFunction2(farg, *args, **kwargs): That is, the formal argument must come first, followed by the non-keyworded argument and the keyworded argument in that order.
Credits
Aman Kumar
LinkedIn

No comments:

Post a Comment