Lesson 8: What are Functions?
Why do programmers use functions?
- Allows for code to be reused
- Makes complicated code easier to understand
- Values can be passed to functions as arguments
- Functions can return values
How to create a function
A programmer must define a function before using it on data. In Python, the keyword for defining a new function is def
.
Example: The following simple function, HelloWorld(), outputs the string statement “Hello World”:
def HelloWorld():
print("Hello World")
Calling a function
After a function has been defined, it can be used when the function is called. In Python, you call a function by typing the name of the function. To call the above function, HelloWorld(), use:
HelloWorld()
What are function arguments?
A function can take either no arguments or one or more arguments.
Example: HelloWorld() has an empty parenthesis because the function has no arguments.
Addition(x,y) requires two arguments, x and y, to be passed in order for the function to return the sum of x and y.
def Addition(x, y):
return x + y
To find the sum of the numbers 5 and 7 using this Addition() function, a programmer simply passes these values on calling the function:
print('The sum of 5 and 7 is', Addition(5, 7))
A function UserInformation() takes three arguments (name, age, and address) and prints this information as string statements when the function is called:
def UserInformation(name, age, address):
print("The name of the User is", name)
print("The age of the user is", age)
print("The address of the user is", address)
UserInformation('Patrick', 28, 'Raheen')