Python 3home |
Introduction to Python
davidbpython.com
A user-defined function is a block of code that can be executed by name.
def add(val1, val2):
valsum = val1 + val2
return valsum
ret = add(5, 10) # int, 15
ret2 = add(0.3, 0.9) # float, 1.2
A function is a block of code:
calling means activating the function and running its code.
def print_hello():
print("Hello, World!")
print_hello() # prints 'Hello, World!'
print_hello() # prints 'Hello, World!'
print_hello() # prints 'Hello, World!'
The arguments are the inputs to a function.
def print_hello(greeting, person): # note we do not
full_greeting = f'{greeting}, {person}!' # refer to 'name1'
print(full_greeting) # 'place2', etc.
# inside the function
name1 = 'Hello'
place1 = 'World'
print_hello(name1, place1) # prints 'Hello, World!'
name2 = 'Bonjour'
place2 = 'Python'
print_hello(name2, place2) # prints 'Bonjour, Python!'
A function's return value is passed back from the function using the return statement.
def print_hello(greeting, person):
full_greeting = f'{greeting}, {person}!'
return full_greeting
msg = print_hello('Bonjour', 'parrot')
print(msg) # 'Bonjour, parrot!'
Ex. 9.1 - 9.5