4. Functions
Just a quick introduction to some basic data types in Python.
- Why functions?
- Function calls
- Math functions
- Add new functions
- Parameters and arguments
- Functions with return value(s) and void functions
- Argument checking
- Return more than one value
In the context of programming, a function is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later, you can "call" the function by name.
Why functions?
We know the area of a circle is: $A= πr^2$. Suppose we need to calculate the areas of three circles, we can do:
$r_1 = 20.16$
$r_2 = 9.13$
$r_3 = 11.55$
$A_1 = 3.14 * r_1^2$
$A_2 = 3.14 * r_2^2$
$A_3 = 3.14 * r_3^2$
Question: Is there an easier way to do this?
Question: What if we change $π$ to 3.14159 instead of 3.14?
If a function area_of_cicle(x) is defined, then we could reuse it many times, like this
a_1 = area_of_cicle(r_1)
a_2 = area_of_cicle(r_2)
a_3 = area_of_cicle(r_3)
type(42)
The name of the function is type. The expression in parentheses is called the argument of the function. The result, for this function, is the type of the argument.
It is common to say that a function "takes" an argument and "returns" a result. The result is also called the return value.
To know more about this function, visit the documentation https://docs.python.org/3/library/functions.html#type.
type('42')
int('42')
int('Hello')
int(3.99)
int(-2.3)
float(42)
float('3.14')
str(42)
str(3.14)
abs(-100)
abs(-100, 42)
max(1, 2)
max(43, 5345, -654, 2, 0, 99999)
Exercise 01
Play with functions round(), min(), ord(), chr(). Read documentation https://docs.python.org/3/library/functions.html.
import math
This statement creates(borrows) a module object named math. If you display the module object, you get some information about it:
math
help(math)
How to call a function? By using dot.
ratio = 100
math.log10(ratio)
degrees = 45
radians = degrees / 180.0 * math.pi # math.pi is not a function. It is a constant.
math.sin(radians)
Exercise 02
From the documentation of math module https://docs.python.org/3/library/math.html, pick up two functions and play with them.
def print_lyrics():
print("Hey Jude. Don't make it bad.")
print("Take a sad song and make it better.")
type(print_lyrics)
print_lyrics()
We can use a function inside another function.
def repeat_lyrics():
print_lyrics()
print('Na - na - na - na - na, na - na - na - na')
print_lyrics()
repeat_lyrics()
def print_twice(whatever_name):
print(whatever_name)
print(whatever_name)
print_twice('Babson')
my_name = 'Jack'
print_twice(my_name)
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
This function takes two arguments, concatenates them, and prints the result twice. Here is an example that uses it:
line1 = 'Bing tiddle '
line2 = 'tiddle bang.'
cat_twice(line1, line2)
However, when cat_twice terminates, the variable cat is destroyed. If we try to print it, we get an exception:
print(cat)
Parameters are also local. For example, outside function print_twice, there is no such thing as whatever_name.
def give_me_a_break():
str1 = 'break'
return str1
print(give_me_a_break())
def give_me_a_break():
str1 = 'break'
return str1
print('another break')
print(give_me_a_break())
result = print_twice('Bing')
print(result)
def nop():
pass
We can use pass in other statements as well.
age= int(input())
if age >= 18:
pass # without pass, you will see error.
abs('A')
Exercise 05
Modify the function my_abs to first only allow integers and floating numbers, then return the absolute value of any number. You may need a built-in function isinstance() https://docs.python.org/3/library/functions.html#isinstance.
import math
def move(x, y, step, angle):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
x, y = move(100, 100, 60, math.pi / 6)
print(x, y)
def quadratic(a, b, c):
pass # please modify it so the function solves the quadratic equation and return two values