# Python Tutorial 6: Functions

If you remember your pre-university Math, you might remember how your functions are defined as y = f(x) where x is your input, y is your output, and f(x) will be some convoluted expression of math.

Similar, functions in programming serves similar purpose, except with far more variety and flexilibility for work process beside math. In Python, we have either use functions that comes with the installation (inbuilt), or write your own!

## 1. Pre-defined functions

Functions in python usually have the name of the function followed by a (), (e.g. sum(),len(),input() and print(). Functions can take many parameters, or take none at all (f(x,y) = x+y for example). A function may have compulsory parameters and also optional ones!

We will start with some pre-defined functions in Python that is in-built in your bare minimum installation of python.

## Output function

Output function in Python is very simple. With whatever variables you have, you can simply pass the variable into the print() function. It does not matter what kind of variable data type it is, Python will try and interpret it and print it out accordingly

In :
```StringOutput = "Hello World!"NumberOutput = 3.14159ListOutput = [1,2,3,4,5,6]DictionaryOutput = {'Alice':13,'Brad':14,'Charlie':15}print(StringOutput,NumberOutput,ListOutput,DictionaryOutput)
```

```Hello World! 3.14159 [1, 2, 3, 4, 5, 6] {'Alice': 13, 'Brad': 14, 'Charlie': 15}
```

Note that you can pass any number of variables into the print() function with a comma and it will separate the variables with a whitespace. If you want to concatcenate separate strings you can use ‘+’ between variables of similar data type. You can also immediately perform basic math calculation inside the function, and it will be calculated before the output.

In :
```FirstString = "Hello"SecondString = "World"FirstNumber = 1SecondNumber = 2print(FirstString+SecondString)print(FirstNumber+SecondNumber)
```

```HelloWorld3
```

There are other functionality of the print() function, for example:

• You don’t want a new line to be printed, you simply add extra parameter, print(FirstString,end= ” “)
• You want the output to be separated by ‘x’ instead of whitespaces, you can add print(FirstString,SecondString,sep=’,’)

## Input function

What is the point of programming if you can only change the output of the programme by changing variables in script everytime before you run the program? Here we will use the input function, which is simply, input()

In :
```FirstInput = input()print(FirstInput)print(type(FirstInput))
```

```Hello World!Hello World!

```

Go ahead and try enter the following and see their corresponding output.

• Hello World!
• 145

You might realise that for the first input, it returns an string as an output, which is what we expected. However when we enter numbers, or calculations, it returns “145” as a string (str)! Remember that input only take what you typed as a string!

Here you need to use the typecasting methods that we have mentioned in Chapter 2 to convert the string type to, maybe, integer

Try out the code below but enter the same string and numbers into it! You realise now typing invalid input such as ‘Hello World!’ will return an error while typing numbers will not.

In :
```SecondInput = int(input())print(SecondInput)print(type(SecondInput))
```

```44

```

Some of you might be wondering at this point, What happen if you put things into the brackets of the input function? Input function here takes in a string that can help you prompt the users for the correct input, for example:

In :
```ThirdInput = int(input("Please enter an integer!"))print(ThirdInput)
```

```Please enter an integer!  44
```

## More pre-defined functions

We will introduce a few more pre defined functions in Python’s installation that are often used. You might have realise some of the ways we define data structures in Chapter 3 are also pre-defined functions (e.g. list(), set())

1. sum()
2. len()
3. sorted()
4. split()

Function names, like variable names are case-sensitive so please be careful when using them!

#### 1. Sum returns addition of all elements in the object

In :
```NumberList = [1,2,3,4,5,6]print(sum(NumberList))
```

```21
```

#### 2. Len returns the length of the items in the object (usually a list)

In :
```NumberList = [1,2,3,4,5,6]print(len(NumberList))
```

```6
```

#### 3. Sorted, well, sorts the list

In :
```NumberList= [3,2,4,1,2,5,6]print(sorted(NumberList))
```

```[1, 2, 2, 3, 4, 5, 6]
```

#### 4. Split is useful when you want to split a string of numbers from the input function into something like a list for you to manipulate.

Without putting anything into the function, the default delimiter is whitespace. Note that the string is now converted to a list, but the elements inside are still characters.

In :
```NumberString = "3 4 5 2 1 4 5"NumberList = NumberString.split()DateString = "23/12/2014"DateList = DateString.split("/")print(NumberList)print(DateList)
```

```['3', '4', '5', '2', '1', '4', '5']['23', '12', '2014']
```

## 2. User Defined functions

What is the point of programming if you are stuck with the functions that is in-built with the programming language? There is no difference buying a software that does limited things for you right?

At some point in time doing data analysis, you might realise that you are using same code over and over again. You can consider Ctrl-C and V the code multiple times, and screw up. User-defined functions are reusable code blocks; they only need to be written once, then they can be used multiple times. They can even be used in other applications, too.

In this chapter, we will now explore how we can write our own set of instructions.

In :
```#general structure of an user-defined function in Pythondef FunctionName(parameter1,parameter2):	#Reusable Code goes here	sumof = parameter1+parameter2	return sumofprint(FunctionName(1,2))
```

```3
```

## Print? Return?

You might have noticed that instead of using print to generate output in normal code, we use ‘return’ instead. There is a major difference between return and print() function during programming.

• print() – Generates a textual output in the complier
• return – Causes the function to inherently adopt the value of what is after return

Hence, if you use return and you want to view the result of the function, you still need to print it. In comparsion if your function uses print, you don’t have to print again as the print function is already executed within the function call as seen from the example below:

In :
```def FunctionNameReturn(parameter1,parameter2):    sumof = parameter1+parameter2    return sumofdef FunctionNamePrint(parameter1,parameter2):	sumof = parameter1+parameter2	print(sumof)print(FunctionNameReturn(1,2))FunctionNamePrint(1,2)
```

```33
```

So why do we use return instead of print inside a function? This is useful if the function merely serve as an intermediate step to your eventual program. Let’s look at the example below

In :
```def FunctionNameReturn(parameter1,parameter2):    sumof = parameter1+parameter2	return sumofdef FunctionNamePrint(parameter1,parameter2):	sumof = parameter1+parameter2	print(sumof)FurtherAddition = FunctionNameReturn(1,2) + 1
print(FurtherAddition)FurtherSubstraction = FunctionNamePrint(1,2) - 1#Now for the second function, it will print 3 and throw the information out of the program.#That is why the output is wrong, as it no longer have information stored as 3 to be substracted
```

```43
```

```---------------------------------------------------------------------------TypeError Traceback (most recent call last)in ()9 FurtherAddition = FunctionNameReturn(1,2) + 110 print(FurtherAddition)---> 11 FurtherSubstraction = FunctionNamePrint(1,2) - 112 #Now for the second function, it will print 3 and throw the information out of the program.13 #That is why the output is wrong, as it no longer have information stored as 3 to be substractedTypeError: unsupported operand type(s) for -: 'NoneType' and 'int'
```
There are times where we need a function to have a default value for a parameter unless we specify otherwise, and we can do so simply by:
In :
```def EmployeeSalaryEvaluation(empRank = "Associate",YearsofExperience = 0):	if empRank == "Associate":		Salary = 3000+(500*YearsofExperience)		return Salary	elif empRank == "Manager":		Salary = 5000+(800*YearsofExperience)		return Salary	else:		return "Contract Staff - See agreement"print(EmployeeSalaryEvaluation())#Without declaring anything, it returns 3000 as salaryprint(EmployeeSalaryEvaluation(YearsofExperience = 5))#Without declaring the rank, but defining experience, you get the adjusted salaryprint(EmployeeSalaryEvaluation("Manager"))
```

```300055005000
```

You might be wondering, why I do explicitly says YearsofExperience = 5 but simply mention "Manager" for rank. In this case you need to remember if you explicitly declare all the parameter with ParameterName = "something", the order of the parameters keyed into the function does not matter. Else, they will only interpret values by the order which is keyed in. This is why you cannot key in EmployeeSalaryEvaluation(5) and expect a proper answer.