I’m YouKoutaku. These codes are from the book python_Crash_Course, 2nd edition. I learned python and took these notes for this book.
8.Function
8.1 Define function
def functionname
"""function detail"""
1
2
3
4
5
6
| def greet_user():
"""a sample greet"""
print("Hello!")
greet_user()
|
8.1.1 sent message to function
local value = parameter
globle value = argument
1
2
3
4
5
| def greet_user(username):
"""a sample greet"""
print(f"Hello,{username.title()}!")
greet_user('jesse')
|
8.2 argument
8.2.1 position argument
1
2
3
4
5
6
7
| def describe_pet(animal_type, pet_name):
"""pet info"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('cat','harry')
describe_pet('dog','smich')
|
1
2
3
4
5
| I have a cat.
My cat's name is Harry.
I have a dog.
My dog's name is Smich.
|
8.2.2 keyword argument
1
2
3
4
5
6
| def describe_pet(animal_type, pet_name):
"""pet info"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='cat',pet_name='harry')
|
1
2
| I have a cat.
My cat's name is Harry.
|
8.2.3 Default value
default value can’t be the frist argument
1
2
3
4
5
| def describe_pet(animal_type='dog',pet_name):
"""pet info"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='harry')
|
1
2
3
4
| Input In [10]
def describe_pet(animal_type='dog',pet_name):
^
SyntaxError: non-default argument follows default argument
|
1
2
3
4
5
6
| def describe_pet(pet_name, animal_type='dog'):
"""pet info"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='harry')
describe_pet(animal_type='cat',pet_name='harry')
|
1
2
3
4
5
| I have a dog.
My dog's name is Harry.
I have a cat.
My cat's name is Harry.
|
8.2.4 complex using
1
2
3
4
5
6
7
8
9
10
11
12
13
| def describe_pet(pet_name, animal_type='dog'):
"""pet info"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('willie')
describe_pet(pet_name='willie')
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| I have a dog.
My dog's name is Willie.
I have a dog.
My dog's name is Willie.
I have a hamster.
My hamster's name is Harry.
I have a hamster.
My hamster's name is Harry.
I have a hamster.
My hamster's name is Harry.
|
8.2.5 avoid argument error
1
2
3
4
5
6
| def describe_pet(pet_name, animal_type='dog'):
"""pet info"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet()
|
1
2
3
4
5
6
7
8
9
10
11
| ---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [12], in <cell line: 6>()
3 print(f"\nI have a {animal_type}.")
4 print(f"My {animal_type}'s name is {pet_name.title()}.")
----> 6 describe_pet()
TypeError: describe_pet() missing 1 required positional argument: 'pet_name'
|
8.3 retrun
8.3.1 sample
1
2
3
4
5
6
7
8
| def get_formatted_name(first_name, last_name):
"""retrun full name"""
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
|
8.3.2 making optional argument
1
2
3
4
5
6
7
8
9
| def get_formatted_name(first_name, last_name, middle_name=''):
"""retrun full name"""
full_name = f"{first_name} {middle_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker','lee')
print(musician)
|
1
2
| Jimi Hendrix
John Lee Hooker
|
8.3.3 return dictionary
1
2
3
4
5
6
7
| def build_person(first_name, last_name):
"""ruturn a dictionary which include a persional info"""
person = {'first': first_name, 'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
|
1
| {'first': 'jimi', 'last': 'hendrix'}
|
1
2
3
4
5
6
7
8
9
10
11
| def build_person(first_name, last_name, age=None):
"""ruturn a dictionary which include a persional info"""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
m1 = build_person('jimi', 'hendrix')
m2 = build_person('you', 'koutaku', '18')
print(m1)
print(m2)
|
1
2
| {'first': 'jimi', 'last': 'hendrix'}
{'first': 'you', 'last': 'koutaku', 'age': '18'}
|
8.3.4 function with while loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| def get_formatted_name(first_name, last_name):
"""return full name"""
full_name = f"{first_name} {last_name}"
return full_name.title()
# a infinity loop!
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
l_name = input("Last name: ")
if f_name == 'q' or l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print(f"\nHello, {formatted_name}!")
|
1
2
3
4
5
6
7
| Please tell me your name:
(enter 'q' at any time to quit)
Hello, You Koutaku!
Please tell me your name:
(enter 'q' at any time to quit)
|
8.4 fuction to return list
1
2
3
4
5
6
7
8
| def greet_users(names):
"""greet"""
for name in names:
msg = f"Hello, {name.title()}!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
|
1
2
3
| Hello, Hannah!
Hello, Ty!
Hello, Margot!
|
8.4.1 change list in function
1
2
3
4
5
6
7
8
9
10
11
| olds = ['phone case', 'robot pendant', 'dodecahedron']
news = []
while olds:
c = olds.pop()
print(f"Printing model: {c}")
news.append(c)
print("\nThe folloing models have been printed :")
for new in news:
print(new)
|
1
2
3
4
5
6
7
8
| Printing model: dodecahedron
Printing model: robot pendant
Printing model: phone case
The folloing models have been printed :
dodecahedron
robot pendant
phone case
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| def print_models(olds, news):
while olds:
c = olds.pop()
print(f"Printing model: {c}")
news.append(c)
def show_new (news):
print("\nThe following models have been printed:")
for new in news:
print(new)
olds = ['phone case', 'robot pendant', 'dodecahedron']
news = []
print_models(olds,news)
show_new(news)
print(olds)
|
1
2
3
4
5
6
7
8
9
| Printing model: dodecahedron
Printing model: robot pendant
Printing model: phone case
The following models have been printed:
dodecahedron
robot pendant
phone case
[]
|
8.4.2 disable change list in function
create a copy of the list to sent function
```python
def print_models(olds, news):
while olds:
c = olds.pop()
print(f"Printing model: {c}")
news.append(c)
def show_new (news):
print("\nThe following models have been printed:")
for new in news:
print(new)
olds = ['phone case', 'robot pendant', 'dodecahedron']
news = []
print_models(olds[:], news)
show_new(news)
print(olds)
1
2
3
4
5
6
7
8
9
| Printing model: dodecahedron
Printing model: robot pendant
Printing model: phone case
The following models have been printed:
dodecahedron
robot pendant
phone case
['phone case', 'robot pendant', 'dodecahedron']
|
8.5 passing any number of arguments
*arguments'name
create a tuple to save all of the arguments
1
2
3
4
| def pizza(*toppings):
print(toppings)
pizza('pepperoni')
pizza('pepperoni', 'green pepers', 'extra cheese')
|
1
2
| ('pepperoni',)
('pepperoni', 'green pepers', 'extra cheese')
|
8.5.1 Using both of positon arguments and any number of arguments
the any number of arguments must be at the end.
1
2
3
4
5
6
| def pizza(size, *toppings):
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"-{topping}")
pizza(16,'pepperoni')
pizza(12,'pepperoni', 'green pepers', 'extra cheese')
|
1
2
3
4
5
6
7
| Making a 16-inch pizza with the following toppings:
-pepperoni
Making a 12-inch pizza with the following toppings:
-pepperoni
-green pepers
-extra cheese
|
8.5.2 Using any number of keywords arguments
create a any number of arguments(it's a dictionary) by keywords
```python
def profile (first, last, **user_info):
user_info['f_name'] = first
user_info['l_name'] = last
return user_info
user_profile = profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
1
| {'location': 'princeton', 'field': 'physics', 'f_name': 'albert', 'l_name': 'einstein'}
|
8.6 modules
8.6.1 import modules
module_name.function_name()
1
2
3
4
5
| # pizza.py
def pizza(size, *toppings):
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"-{topping}")
|
1
2
3
4
5
| #m_pizza.py
import pizza
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'pepperoni', 'green pepers', 'extra cheese')
|
8.6.2 import function
from module_name import function_name
1
2
3
4
| from pizza import make_pizza
make_pizza(16,'pepperoni')
make_pizza(12,'pepperoni', 'green pepers', 'extra cheese')
|
8.6.3 using as to rename function
from module_name import function_name as function_newname
1
2
3
4
| from pizza import make_pizza as mp
mp(16,'pepperoni')
mp(12,'pepperoni', 'green pepers', 'extra cheese')
|
8.6.4 using as to rename module
import module_name as module_newname
1
2
3
4
| import pizza as p
p.make_pizza(16,'pepperoni')
p.make_pizza(12,'pepperoni', 'green pepers', 'extra cheese')
|
8.6.5 import all of the module
from module_name import *
1
2
3
4
| from pizza import *
make_pizza(16,'pepperoni')
make_pizza(12,'pepperoni', 'green pepers', 'extra cheese')
|