• Home
• /
• Blog
• /
• Types of Functions in Python Explained to Kids

# Types of Functions in Python Explained to Kids

July 3, 2021

This post is also available in: हिन्दी (Hindi) العربية (Arabic)

As a beginner, we write very small programs. When a program is small enough, we can keep all of the details of the program in our heads at once. Real application programs are 100 to 10000 times larger than any program you have likely written (or maybe even worked on); they are simply too large and complex to hold all their details in our heads.

Coding For Kids eBook

A must read for every parent

Country
• Afghanistan 93
• Albania 355
• Algeria 213
• American Samoa 1-684
• Andorra 376
• Angola 244
• Anguilla 1-264
• Antarctica 672
• Antigua & Barbuda 1-268
• Argentina 54
• Armenia 374
• Aruba 297
• Australia 61
• Austria 43
• Azerbaijan 994
• Bahamas 1-242
• Bahrain 973
• Belarus 375
• Belgium 32
• Belize 501
• Benin 229
• Bermuda 1-441
• Bhutan 975
• Bolivia 591
• Bosnia 387
• Botswana 267
• Bouvet Island 47
• Brazil 55
• British Indian Ocean Territory 246
• British Virgin Islands 1-284
• Brunei 673
• Bulgaria 359
• Burkina Faso 226
• Burundi 257
• Cambodia 855
• Cameroon 237
• Cape Verde 238
• Caribbean Netherlands 599
• Cayman Islands 1-345
• Central African Republic 236
• Chile 56
• China 86
• Christmas Island 61
• Cocos (Keeling) Islands 61
• Colombia 57
• Comoros 269
• Congo - Brazzaville 242
• Congo - Kinshasa 243
• Cook Islands 682
• Costa Rica 506
• Croatia 385
• Cuba 53
• Cyprus 357
• Czech Republic 420
• Denmark 45
• Djibouti 253
• Dominica 1-767
• Egypt 20
• Equatorial Guinea 240
• Eritrea 291
• Estonia 372
• Ethiopia 251
• Falkland Islands 500
• Faroe Islands 298
• Fiji 679
• Finland 358
• France 33
• French Guiana 594
• French Polynesia 689
• French Southern Territories 262
• Gabon 241
• Gambia 220
• Georgia 995
• Germany 49
• Ghana 233
• Gibraltar 350
• Greece 30
• Greenland 299
• Guam 1-671
• Guatemala 502
• Guernsey 44
• Guinea 224
• Guinea-Bissau 245
• Guyana 592
• Haiti 509
• Heard & McDonald Islands 672
• Honduras 504
• Hong Kong 852
• Hungary 36
• Iceland 354
• India 91
• Indonesia 62
• Iran 98
• Iraq 964
• Ireland 353
• Isle of Man 44
• Israel 972
• Italy 39
• Jamaica 1-876
• Japan 81
• Jersey 44
• Jordan 962
• Kazakhstan 7
• Kenya 254
• Kiribati 686
• Kuwait 965
• Kyrgyzstan 996
• Laos 856
• Latvia 371
• Lebanon 961
• Lesotho 266
• Liberia 231
• Libya 218
• Liechtenstein 423
• Lithuania 370
• Luxembourg 352
• Macau 853
• Macedonia 389
• Malawi 265
• Malaysia 60
• Maldives 960
• Mali 223
• Malta 356
• Marshall Islands 692
• Martinique 596
• Mauritania 222
• Mauritius 230
• Mayotte 262
• Mexico 52
• Micronesia 691
• Moldova 373
• Monaco 377
• Mongolia 976
• Montenegro 382
• Montserrat 1-664
• Morocco 212
• Mozambique 258
• Myanmar 95
• Namibia 264
• Nauru 674
• Nepal 977
• Netherlands 31
• New Caledonia 687
• New Zealand 64
• Nicaragua 505
• Niger 227
• Nigeria 234
• Niue 683
• Norfolk Island 672
• North Korea 850
• Northern Mariana Islands 1-670
• Norway 47
• Oman 968
• Pakistan 92
• Palau 680
• Palestine 970
• Panama 507
• Papua New Guinea 675
• Paraguay 595
• Peru 51
• Philippines 63
• Pitcairn Islands 870
• Poland 48
• Portugal 351
• Puerto Rico 1
• Qatar 974
• Romania 40
• Russia 7
• Rwanda 250
• Samoa 685
• San Marino 378
• Saudi Arabia 966
• Senegal 221
• Serbia 381 p
• Seychelles 248
• Sierra Leone 232
• Singapore 65
• Slovakia 421
• Slovenia 386
• Solomon Islands 677
• Somalia 252
• South Africa 27
• South Georgia & South Sandwich Islands 500
• South Korea 82
• South Sudan 211
• Spain 34
• Sri Lanka 94
• Sudan 249
• Suriname 597
• Svalbard & Jan Mayen 47
• Swaziland 268
• Sweden 46
• Switzerland 41
• Syria 963
• Sao Tome and Principe 239
• Taiwan 886
• Tajikistan 992
• Tanzania 255
• Thailand 66
• Timor-Leste 670
• Togo 228
• Tokelau 690
• Tonga 676
• Tunisia 216
• Turkey 90
• Turkmenistan 993
• Turks & Caicos Islands 1-649
• Tuvalu 688
• U.S. Outlying Islands
• U.S. Virgin Islands 1-340
• UK 44
• US 1
• Uganda 256
• Ukraine 380
• United Arab Emirates 971
• Uruguay 598
• Uzbekistan 998
• Vanuatu 678
• Vatican City 39-06
• Venezuela 58
• Vietnam 84
• Wallis & Futuna 681
• Western Sahara 212
• Yemen 967
• Zambia 260
• Zimbabwe 263
• Less Than 5 Years
• 5 - 8 Years
• 9 - 13 Years
• 14 - 18 Years
• 18+ Years

One key solution to managing the complexity of large software is modular programming: the code is composed of many different code modules commonly known as developed functions. This allows different developers to take on discrete pieces of the system and design and implement them without having to understand all the rest. In this article, we’ll look into different types of functions in Python.

## What is a Function?

A function is a block of code that performs some specific task. It can be called and reused multiple times. You can pass information and it can send information back. Many programming languages have two types of functions:

• Built-In Functions: A function that is built into an application or programming language and can be accessed by end-users. For example, most spreadsheet applications support a built-in SUM function that adds up all cells in a row or column. Similarly, in C printf() and scanf() are built-in functions that are used to print and read values.
• User-Defined Functions: A user can define functions to do a task relevant to their programs. Such functions are called user-defined functions. The main() function in which we write all our programs is a user-defined function.

When you call a function, the program will pause the current program and execute the function. The function will be read from top to bottom. Once the function is complete, the program continues to run where it had paused. If the function returned a value, that value will be used where the function was called.

## Types of Functions in Python

As mentioned above you use functions in programming to bundle a set of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub-program and called when needed. That means that a function is a piece of code written to carry out a specified task. To carry out that specific task, the function might or might not need multiple inputs. When the task is carried out, the function can or can not return one or more values.

There are three types of functions in Python:

• Built-in functions: These are the functions built-in in Python such as help() to ask for help, min() to get the minimum value, print() to print an object to the terminal.
• User-Defined Functions (UDFs): These are the functions created by the user according to their programming needs.
• Anonymous functions: These functions are also called lambda functions because they are not declared with the standard def keyword.

## Functions vs Methods

### Function

A function is a block of code to carry out a specific task, contains its own scope, and is called by its name. All functions may contain zero (no) arguments or more than one argument. On exit, a function can or can not return one or more values.

Basic Function Syntax

def functionName( arg1, arg2,….):
…….
# Function_body
……..


Following is an example of a function greet which prints a greeting message for a name passed in the function.

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
>>> greet('Paul')
Hello, Paul. Good morning!


### Method

A method in Python is somewhat similar to a function, except it is associated with objects/classes. Methods in Python are very similar to functions except for two major differences.

• The method is implicitly used for an object for which it is called.
• The method is accessible to data that is contained within the class.

Basic Method Syntax

class ClassName:
def method_name():
…………..
# Method_body
………………


Let’s understand the method through the following simple code:

class Pet(object):
def my_method(self):
print("I am a Cat")
cat = Pet()
cat.my_method()

Output:

I am a Cat

In the above code, we first defined the class Pet, then we created an object cat from this blueprint. Next, we call our custom method called my_method with the object (i.e., cat).

## Parameters vs Arguments

The terms parameter and argument are used interchangeably by many programmers, but they both have different meanings.

A parameter is a special kind of variable used in a function to refer to one of the pieces of data provided as input to the function. These data are the values of the arguments with which the function will be called/invoked.

In simpler terms, the argument is the actual value supplied to a function, whereas the parameter is the variable inside the definition of the function. We can say that a parameter is a type that appears in function definitions, while an argument is an instance that appears in the function calls. In the above example name is called parameter and Paul is called an argument.

## How To Define a User-Defined Function (UDF) in Python?

The four steps in defining a function in Python are the following:

• Use the keyword def to declare the function and follow this up with the function name.
• Add parameters to the function. These should be written within the parentheses of the function. End your line with a colon.
• Add statements that the function should execute.
• End your function with a return statement if the function should output something. Without the return statement, your function will return an object None.

## Function Arguments in Python

Above you learned about the difference between the parameters and arguments. In short, arguments are the things that are given to any function all, while the function code refers to the arguments by their parameter names. There are four types of arguments that Python UDFs can take:

• Default arguments
• Required arguments
• Keyword arguments
• Variable number of arguments

### Default arguments

Default arguments are those that take a default value if no argument value is passed during the function call. You can assign this default value by with the assignment operator =, just like in the following example:

# Define plus() function
def plus(a,b = 2):
return a + b
# Call plus() with only a parameter
plus(a=1)
# Call plus() with a and b parameters
plus(a=1, b=3)


### Required arguments

As the name suggests, the required arguments of a UDF are those that have to be there. These arguments need to be passed during the function call and in precisely the right order, just in the following example:

# Define plus() with required arguments
def plus(a,b):
return a + b


You need arguments that map to the a as well as the b parameters to call the function without getting any errors. If you switch around a and b, the result won’t be different, but it might be if you change the function plus() to the following:

# Define plus() with required arguments
def plus(a,b):
return a/b


### Keyword arguments

If you want to make sure that you call all the arguments in the right order, you can choose the keyword arguments in your function call. You use these to identify the arguments by their parameter name. Let’s take the example from the above to make it clear.

# Define plus() function
def plus(a,b):
return a + b
# Call plus() function with parameters
plus(2,3)
# Call plus() function with keyword arguments
plus(a=1, b=2)


Note that by using the keyword arguments, you can also switch around the order of the parameters and still get the same result when you execute your function:

# Define plus() function
def plus(a,b):
return a + b
# Call plus() function with keyword arguments
plus(b=2, a=1)


### Variable number of arguments

In cases where you don’t know the exact number of arguments that you want to pass to a function, you can use the following syntax with *args:

# Define plus() function to accept a variable number of arguments
def plus(*args):
return sum(args)
# Calculate the sum
plus(1,4,5)
plus(5,6,7,8,4)


Output:

10

30

The asterisk (*) is placed before the variable name that holds the values of all non-keyword variable arguments. Note here that you might as well have passed *varint, *var_int_args, or any other name to the plus() function. Try replacing *args with another name that includes the asterisk. You’ll see that the above code keeps working!

## Global vs Local Variables

In general, variables that are defined inside a function have a local scope, and those defined outside have a global scope. That means that local variables are defined within a function block and can only be accessed inside that function, while global variables can be accessed by all the functions that might be there in your script.

# Global variable init
init = 1
# Define plus() function to accept a variable number of arguments
def plus(*args):
# Local variable sum()
total = 0
for i in args:
total += i
# Access the global variable
print("this is the initialized value " + str(init))
# (Try to) access the local variable
print("this is the sum " + str(total))


You’ll see that you’ll get a NameError that says that the name ‘total’ is not defined when you try to print out the local variable total that was defined inside the function body. The init variable, on the other hand, can be printed out without any problems.

## Anonymous Functions in Python

Anonymous functions are also called lambda functions in Python because instead of declaring them with the standard def keyword, you use the keyword lambda.

double = lambda x: x*2
double(5)


Output:

10

lambda x: x*2 is the anonymous or lambda function. x is the argument, and x*2 is the expression or instruction that gets evaluated and returned. What’s special about this function is that it has no name, like the examples that you have seen in the above example functions.