Over a million developers have joined DZone. {{announcement.body}}
{{announcement.title}}

DZone's Guide to

# Python Functions Tutorial: Working With Functions in Python, Part 3

If you're new to Python or data science, read on to learn more about recursive functions, user-defined functions, and applying what we've learned in this series.

· Big Data Zone ·
Free Resource

Comment (1)

Save
{{ articles.views | formatCount}} Views

How to Simplify Apache Kafka. Get eBook.

Welcome to the third and final part of this Python functions series! If you missed Part 1 or Part 2, follow those links to check them out.

## Python Recursive Functions

### What Is Recursion in Python?

Recursion is the process of defining something in terms of itself.

A real world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.

### Python Recursive Function

We know that in Python a function can call other functions. It is even possible for the function to call itself. These type of construct are called recursive functions.

The following is an example of a recursive function to find the factorial of an integer.

The factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 5 (denoted as 5!) is 1*2*3*4*5 = 120.

Example:

``````# An example of a recursive function to
# find the factorial of a number

def calc_factorial(x):
<em>"""This is a recursive function
to find the factorial of an integer"""

</em>if x == 1:
return 1
else:
return (x * calc_factorial(x-1))

num = 4
print("The factorial of", num, "is", calc_factorial(num)) ``````

In the above example, `calc_factorial()` is a recursive function, as it calls itself.

When we call this function with a positive integer, it will recursively call itself by decreasing the number.

Each function calls multiples of the number with the factorial of number 1 until the number is equal to 1.

Our recursion ends when the number reduces to 1. This is called the base condition. Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely.

### Advantages of Recursion

1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.

### Disadvantages of Recursion

1. Sometimes the logic behind recursion is hard to follow.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.

Next up on this Python functions article, let's check Lambda functions in Python.

## Python Lambda Functions

### What Are Lambda Functions?

In Python, an anonymous function is a function that is defined without a name.

While normal functions are defined using the `def`keyword, in Python anonymous functions are defined using the `lambda` keyword.

Hence, anonymous functions are also called lambda functions.

### How To Use Lambda Functions In Python?

A Lambda function in Python has the following syntax:

``lambda arguments: expression``

Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.

Example

``````# Program to show the use of lambda functions

double = lambda x: x * 2

# Output: 10
print(double(5))``````

Output

10

In :

In the above program, `lambda x: x * 2`is the Lambda function. Here is the argument and `x * 2` is the expression that gets evaluated and returned.

This function has no name. It returns a function object which is assigned to the identifier `double`. We can now call it the same way we'd call a normal function. The statement

``double = lambda x: x * 2``

is nearly the same as

``````def double(x):
return x * 2``````

Next up, let's check out  how we can make use of user-defined functions in Python

## Python User-Defined Functions

### What Are User-Defined Functions in Python?

Functions that we define ourselves to do a certain task are referred to as user-defined functions. The way in which we define and call functions in Python has already been discussed.

Functions that readily come with Python are called built-in functions. If we use functions written by others via a library they are called library functions.

All the other functions that we write on our own fall under user-defined functions. So, our user-defined function could be a library function to someone else.

### Advantages of User-Defined Functions

1. User-defined functions help to decompose a large program into small segments, which makes the program easy to understand, maintain, and debug.
2. If repeated code occurs in a program, the function can be used to include those codes and execute when needed by calling that function.
3. Programmers working on a large project can divide the workload by making different functions.

Syntax

`````` def function_name(argument1, argument2, ...) :
statement_1
statement_2
....``````

Example

``````# Program to illustrate
# the use of user-defined functions

sum = x + y
return sum

num1 = 5
num2 = 6

print("The sum is", add_numbers(num1, num2))``````

Output

``````Enter a number: 2.4
Enter another number: 6.5
The sum is 8.9``````

Now, let's check out how we can create a simple application using Python.

## Python Program to Create a Simple Calculator Application

In this example, you will learn to create a simple calculator that can add, subtract, multiply or divide depending upon the input from the user.

Code

``````# Program make a simple calculator that can add, subtract, multiply and divide using functions

# This function adds two numbers
return x + y

# This function subtracts two numbers
def subtract(x, y):
return x - y

# This function multiplies two numbers
def multiply(x, y):
return x * y

# This function divides two numbers
def divide(x, y):
return x / y

print("Select operation.")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

# Take input from the user
choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if choice == '1':

elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")``````

Output

``````Select operation.
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15 * 14 = 210``````

In this program, we ask the user to choose the desired operation. Options 1, 2, 3, and 4 are valid. Two numbers are taken and an `if...elif...else` branching is used to execute a particular section. User-defined functions `add()``subtract()``multiply()` and `divide()` evaluate respective operations.

The concepts discussed in this tutorial should help you build your own functions using Python by adding functionality and operability.

This will be very handy when you are trying to create an application by making the process easy and makes it suited for your personal needs. Now, you should also be able to use these Python functions to develop applications easily with the help of Python directly.

12 Best Practices for Modern Data Ingestion. Download White Paper.

Topics:
big data ,python tutorial for beginners ,python tutorial ,python functions

Comment (1)

Save
{{ articles.views | formatCount}} Views

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

# {{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}