Loading lessons...
Functions
A function is a named block of code you can run again and again.
Define and call
python
def my_function():
print("Hello from a function")
my_function()
### Hello from a function
def defines it; the name followed by () calls it.
Arguments
Pass values in parentheses:
python
def greet(name):
print("Hello " + name)
greet("Ada")
### Hello Ada
Parameters vs arguments
- Parameter: the variable in the definition (
name). - Argument: the value you pass when calling (
"Ada").
Number of arguments must match
python
def full(fname, lname):
print(fname + " " + lname)
full("Emil", "Refsnes")
### ok
full("Emil")
### TypeError: missing argument
Return a value
return sends a result back:
python
def add(a, b):
return a + b
print(add(5, 3))
### 8
pass as a placeholder
python
def empty():
pass
TL;DR
def name():defines;name()calls.- Arguments go in parentheses; counts must match.
returngives back a value.- A function without return gives None.