top of page

# Functions

In this section, we'll talk about functions in Python. Functions are blocks of code which only run when called. These functions contain parameters that allow us to pass in data into them, which enables the function to return a result based on this data.

## Functions

We'll go through the syntax, and end with a few examples and exercises.

### Syntax

When we make a function, we put the keyword "def", followed by the name of our function, followed by parenthesis with the parameter values.

def my_function():
print("Hello World")

In this example, we declared the function named "my_function". It does not have parameters. This means that no matter what, when we call the function, it will return the same things. Under the function, we write print("hello World") to signify that when we call the function, we want it to print "Hello World".

### Examples

Example 1:

def name(fname, lname):
print(fname + " " + lname)

In this example, we defined the function "name" to take in 2 parameters. It will then print the concatenation of these parameters with a space in between. What will happen when we call

name("henry","jacobson")?

Example 2:

print(num1+num2)

In this example, we defined the function "add" to take in 2 input values, from which, we will print their concatenation, and if they are integers, we would print their sum. What will happen if we call

### List Functions

We can also use functions to work with lists. These work in exactly the same way.

Example 1:

def my_function(store):
for x in store:
print(x)

Example 2:

sum = 0

for x in list:

sum += x

print(sum)

Try to guess what these functions do!

### Exercises:

1. Write a function which sums the elements of an int list and returns it

2. Write a function that iterates through a string list and returns the longest string.

3. Write the same function as in (2), but print the result within the function.

bottom of page