(functions_python)=
{index}
Functions in Python are blocks of code that will only be executed when called. They look like this:
def function_name(arg1, arg2, ...):
# some code to execute
return # return some variables, optional
Function names should be descriptive. The arguments are separated by commas and will become local variables within the function. Any object, and any number of objects, can be returned from a function.
Functions have to appear in the code before you execute them:
a = 1
b = 2
# Create a function
def subtract_numbers(a, b):
return f"{a} - {b} = {a-b}"
# Call the function
print(subtract_numbers(a, b))
print(subtract_numbers(17,5))
print(subtract_numbers(9, 28))
1 - 2 = -1 17 - 5 = 12 9 - 28 = -19
Even though we have variables a
and b
in the code, the function does not use them unless they are arguments to the function. Variables a
and b
inside the function are local variables and they only exist there. If we want to use global variables (variables outside of the function), the code will look like this:
a = 10
# Create a function
def add_to_variable_a(b):
global a # Make 'a' a global variable
a += b
return a
# Call the function
print("a =", add_to_variable_a(2))
print("a =", add_to_variable_a(4))
# Note how variable a changed
a = 12 a = 16
(functions_exercises)=
def double_list1(l):
for element in l:
element *= 2
def double_list2(l):
for i in range(len(l)):
l[i] *= 2
l = [1,2,3]
print("Original list:", l)
double_list1(l)
print("double_list1:", l)
double_list2(l)
print("double_list2:", l)
Original list: [1, 2, 3] double_list1: [1, 2, 3] double_list2: [2, 4, 6]
Let us have some fun with mutability. Define a function which takes a list and doubles the elements at the even indices and negates the ones at odd indices. Test it with your input.
HINT use the for i in range(len(l)):
structure of the for loop, a different one might not mutate the list.
{admonition}
:class: dropdown
```python
def funnyFunc(l):
for i in range(len(l)):
if i%2==0:
l[i]*=2
else:
l[i]*=(-1)
return l
print(funnyFunc([1,2,3,4,7,4,3]))
```
def simpleSearch(l, a):
.{admonition}
:class: dropdown
```python
def simpleSearch(l,a):
for i in l:
if a == i:
return True
return False
print(simpleSearch([1,2,3],5))
print(simpleSearch(["Boo", "Foo"], "Moo"))
print(simpleSearch([True, True],False))
print(simpleSearch([1.,1.],1))
```
temp = ['009','679','568','444']
Jenny produced so many measurements that she would not be able to change them manually. You have to help her! In addition she needs to provide a function avgList(l)
which will compute the average of temperature reads from a transformed list. Jenny needs you!
{admonition}
:class: dropdown
```python
def revNums(l):
for i in range(len(l)):
l[i] = int(l[i][::-1])
return l
def avgList(l):
return sum(l)/len(l)
temp = ['009','679','568','444']
print(revNums(temp))
print(avgList(temp))
```