Python Series Part 5: Functions

Jarret B

Well-Known Member
Staff member
Joined
May 22, 2017
Messages
360
Reaction score
403
Credits
13,016
Functions are a very useful thing in any programming language.

A function is a block of code that you can execute over and over with no need to write the code in the program more than once. Most times, you can give the function a name and call it by the name of the function.

Types of Functions

There are two types of functions in Python, those that are built in and those that are created by the programmer.

The built-in functions are basically all the existing commands, such as 'print'. The print function is the one we have used most often.

The programmer can create user-defined functions and can be called from anywhere needed within the code. Sometimes, a programmer can break a program into logical sections and make each section a function.

For example, if a program needed a user to enter their information, then look up their account in a database, calculate a payment, and then inform the user how much they owe. You can accomplish this through four functions.

If there is a team of programmers working on a program, then you can make smaller teams to create each function.

Defining a Function

Defining a function is easy. The syntax is:

Code:
def function_name(arguments):
# function code
# function code
return

Let's create a simple example. We'll create a function named 'product'. In this function, we will accept two arguments and then multiply them together.

Code:
def product(a, b):
return a*b

There is no extra code needed unless we wanted to handle the function in this way:

Code:
def product(a, b):
val=a*b
return val

We call the function with the name 'product' and pass two arguments to it.

Since we are using the keyword 'return' with a value, we are allowing the function to assign a value. So, we can 'catch' the value into a variable with:

Code:
value = product(3, 9)

A function is receiving the arguments 3 and 9. So in the function, a is '3' and b is '9'. The variable 'val' will be equal to '3 * 9' or '27'. The function returns the value of 'val', so in our calling statement, the value of 27 is set equal to the variable 'value'. We could have simply used the line:

Code:
print (product(3, 9))

We can print the value of 27, but in case we need to perform more operations on the value, we should probably place the value into a variable.

We can perform more tasks without having to key in the function's code over and over:

Code:
value=product(2, 3)
value=product(value, 4)
value=product(value, 5)

You can see that we do not have to use literal numbers for the arguments, but can use variables.

Recursive Functions

Recursive functions are those functions that call itself. Let's look at a quick example:

Code:
def sum_n(n):
if n == 0:
  return 0
else:
  return n + sum_n(n-1)

print(sum_n(2))

In this function, we take a number and all numbers to it that are smaller until we reach zero. We could technically make it one, since zero adds nothing anyway.

For this example, we are using '2'. So in the first round, we will return '2 + sum_n(1)'. In the second round, the result is '1 + sum_n(0)'. The third round gives a result of '0'. Now, going back to the second round, the result is '1 + 0' or '1'. We then go back to the first round and get '2 + 1' or '3'. The recursive lines are in memory and when we hit the answer, we stop the recursion and work backwards to get the conclusive answer.

Let’s look at this in a linear way:

2+sum_n(1)
1+sum_n(0)
0


Since the 'sum_n(0) is '0', we can go to the second line and solve 'sum_n(0):

2+sum_n(1)
1+0 -> 1

0

Now the iterations look like:

2+sum_n(1)
1

0

We now know that the sum_n(1) is '1', so we get:

2+1
1

0

For a final answer of 3.

Hopefully, you can understand how the code works. At least I hope you comprehend how recursive functions work.

Lambda Functions

With a Lambda Function, you do not define it at the beginning of the code, but at the point where it is used.

The syntax is: 'lambda arguments:'.

For an easy example, let's look at:

Code:
name = lambda x: print ("Hello", x)
name ("Jarret")

The response is 'Hello Jarret'. Now, this is a simple function to show its usage.

Let's look at an example that is a little more involved, not much, but includes a defined functioned and lambda functions.

Code:
def power(n):
return lambda x: x**n

square = power(2)
cube = power(3)
quad = power(4)

print (square(5))
print (cube(6))
print (quad(7))

The answers will be:

25
216
2401


The Lambda Function, named 'square', calls the defined function 'power'. When we call 'square', the value of 'n' is '2'. The variable for our Lambda call is '5'. The equation is then '5**2' or five squared, which is 25.

When we call 'cube(6)', the power value is '3' and the value of 'x' is '6'. So, six cubed is 216.

Finally, the last example is 'quad(7)'. So, 'quad' is to the fourth power. We are passing the lambda value of '7'. The answer of seven to the fourth power is 2401.

If you decide to pass multiple arguments to the Lambda Function, just separate them with commas. No parenthesis is used. When calling the Lambda Function, you need to use parenthesis around the arguments.

Nesting Functions

You can create a function inside another function. The problem is that the second function can only be called by the first function. So, this lets you know that if you have code within a function that is repeated, you can create another function to reduce the code.

Let's do a quick example.

Code:
def FirstFunction():
#code

def SecondFunction():
#code

SecondFunction()
FirstFunction()

The first thing we do is define the FirstFunction. This is usually called the 'outer function'. We can have some code, then we define the SecondFunction. The SecondFunction is usually known as the 'inner function'. Now, after defining the SecondFunction, we can call it.

From our main line of code, we can call the FirstFunction to get everything started.

Let's look at something a little more usable.

Code:
def getinput():
def checkinitial(x):
ok = 0
if (x.isalpha() and len(x) == 1):
  ok = 1
return ok

ok =0
while (ok == 0):
  First = input("Enter your first initial:")
  ok = checkinitial(First)
  First = First.upper()
  ok = 0
  while (ok == 0):
    Last = input("Enter your last initial:")
    ok = checkinitial(Last)
    Last = Last.upper()
    return First, Last

f, l = getinput()
print ("Your initials are: ",f,l)

Okay, so we have a nested function. The first, or outer, function asks the user for the input of their first and last initials. After it is input, it checks to verify that the input is a letter between 'A' and 'Z', which is handled by the second function. The first function then returns the valid initials.

The second, or inner, function is used to check if the value 'isalpha' and has a length of one character.

The '.isalpha' check if the character is alphabetic. It returns a 'true' value if it is between 'A' and 'Z' (upper- or lower-cased). The character being tested is in the variable 'x'. The 'len(x)' is to test the length of the variable 'x'. and we check if the value is '1'.

In the function 'getinput()' we first define 'checkinitial'. After this, we set the variable 'ok' to '0'. Now, while 'ok' equals '0', we set the variable 'First' equal to the function 'checkinitial'. We keep looping until 'ok' is equal to something other than 0, which happens only when the input of the first initial is valid. If the user enters numbers, punctuation or anything other than a letter, the value of 'ok' stays a zero.

After the 'while' loop, we have a valid character and we upper-it with the command 'First = First.upper()'.

We then set the variable 'ok' equal to 0 and perform the same 'while' loop for the variable 'Last'.

Once both initials are valid, we return the value of the variables 'First, Last'. Outside the function, we call the function with 'f, l = getinput()'. Here, you can see that we are accepting the return of two values, one for 'f' (first) and 'l' (last) initials.

The last line will print out the results of the input characters.

Now, back to the second, or inner, function. We set the variable 'ok' to 0. You should notice that the variable name 'ok' exists in both of the nested functions. Even though the variable has the same name, they are not the same value or using the same memory space. The variables depend on the function and not 'global' variable. A 'global' variable is one that has the same memory space everywhere in the code. Each function can access and change the value. In our case, the variable 'ok' is not the same between the functions.

We then check if the value of 'x' is alphabetic (isalpha), and the length of the variable's value is 1. If the result of the line is 'true', then we set the value of 'ok' to 1. We then return the value of 'ok' back to the variable 'ok' in the function 'getinput'. The code in the second function is used twice, but only exists once in the program.

Conclusion

Try out the function ability to get an understanding of how they work.

Functions can help reduce code that will you use over and over. Ultimately, this will make your code look cleaner and smaller.
 
Last edited:


Latest posts

Top