Python/Python Crash Course

Python Crash Course: 챕터 8

1june 2024. 7. 1. 00:39

Python Crash Course, 3rd Edition

 

  • function
def favorite_book(title):
    """Display a message about someone's favorite book."""
    print(f"{title} is one of my favorite books.")

favorite_book('The Abstract Wild')

Start with def

Give a variable with parentheses (parameter), and end with colon

Explain the function in triple quotes

Write a code about what the function does

Call the function with arguement in parentheses

 

functions are named blocks of code designed
to do one specific job. When
you want to perform a
particular task that you’ve
defined in a function, you call
the function responsible for it. If
you need to perform that task
multiple times throughout your
program, you don’t need to
type all the code for the same task again
and again; you just call the function
dedicated to handling that task

 

 

  • Positional Arguments
def describe_pet(animal_type, pet_name):
	"""Display information about a pet."""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name.title()}.")
    
describe_pet('hamster', 'harry')
I have a hamster.
My hamster's name is Harry.

Python must match each
argument in the function call with a parameter in the
function definition. The simplest way to do this is based on
the order of the arguments provided.

 

  • Keyword Arguements
  •  Keyword arguments free you from
    having to worry about correctly ordering your arguments in
    the function call, and they clarify the role of each value in
    the function call.
def describe_pet(animal_type, pet_name):
	"""Display information about a pet."""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name.title()}.")
    
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')

You can mix up the order as long as you provide keywords when you are calling a function

 

  • Default value in parameters
def describe_pet(pet_name, animal_type='dog'):
	"""Display information about a pet."""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='willie')
I have a dog.
My dog's name is Willie.

 If an argument for a parameter is provided
in the function call, Python uses the argument valueIf not,
it uses the parameter’s default value. So when you define a
default value for a parameter, you can exclude the
corresponding argument 

Notice how the order of the parameters has changed due to the positional argument rule.

If you define values for arguments even though there are default values for parameters, Python will print the values for arguments ignoring the values for parameters.

 

 

  • Return Values
def get_formatted_name(first_name, last_name, middle_name=''):
	"""Return a full name, neatly formatted."""
	if middle_name:
			full_name = f"{first_name} {middle_name} {last_name}"
	else:
		full_name = f"{first_name} {last_name}"

	return full_name.title()

musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
Jimi Hendrix
John Lee Hooker

When you call a function that returns value, you must give variable where returned value can be assigned to

In this case, it's musician

If you want to make one of your parameter optional, 1. put it on the end of the parentheses of the function def 2. assign empty string to it or give None 3. Use if statement

 

def get_formatted_name(first_name, last_name, middle_name):
	"""Return a full name, neatly formatted."""
	if middle_name:
			full_name = f"{first_name} {middle_name} {last_name}"
	else:
		full_name = f"{first_name} {last_name}"

	return full_name.title()

while True:
	print("\nPlease tell me your name:")
	print("(Enter 'q' at any time to quit)")

	f_name = input("First name: ")
	if f_name == 'q':
		break

	l_name = input("Last name: ")
	if l_name == 'q':
		break

	m_name = input("Middle name: ")
	if m_name == 'q':
		break

	formatted_name = get_formatted_name(f_name, l_name, m_name)
	print(f"\nHello, {formatted_name}!")

You can use a While loop and input() and call the fuction you have defined already

While loop or copying the list [ : ] is used to prevent list being modified by function  

 

 

  • Passing an Arbitrary number of Arguments
def make_pizza(*toppings):
	"""Print the list of toppings that have been requested."""
    print(toppings)
    
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

* in the arguement of parameter allows to pass multiple arguments 

('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

It produces a tuple called toppings, containing all the values this function receives.

 

  • Mixing Positional and Arbitrary Arguments

the parameter that accepts an arbitrary number
of arguments must be placed last in the function definition.
Python matches positional and keyword arguments first and
then collects any remaining arguments in the final
parameter.

def make_pizza(size, *toppings):
	"""Summarize the pizza we are about to make."""
	print(f"\nMaking a {size}-inch pizza with the following toppings:")
	for topping in toppings:
		print(f"- {topping}")
        
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

 

  • Using Arbitrary Keyword Arguments
def build_profile(first, last, **user_info):
	"""Build a dictionary containing everything we know abouta user."""
	user_info['first_name'] = first
	user_info['last_name'] = last
	return user_info
    
user_profile = build_profile('albert', 'einstein',location='princeton',field='physics')
print(user_profile)

parameter **user_info cause Python to create a dictionary
called user_info containing all the extra name-value pairs
the function receives.

Since the user always have to provide first and last, include them in the dictionary user_info 

*args

**kwargs 

 

  • Modules

You can store your
functions in a separate file called a module and then
importing that module into your main program. An import
statement tells Python to make the code in a module
available in the currently running program file

Storing your functions in a separate file allows you to hide
the details of your program’s code and focus on its higher-
level logic. It also allows you to reuse functions in many
different programs.

import pizza # Import the module saved
pizza.make_pizza(13, 'hi') #Specify the module_name, separated by dot(.) and function_name within the module.

or

from module_name import function_0, function_1, function_2

 

from pizza import make_pizza as mp

mp(13, 'hi')

as keyword renames a function using the alias you provide

 

import pizza as p

p.make_pizza(13, 'hi')

You can also provide an alias for a module name.

 

from pizza import *

make_pizza(13, 'hi')

You can import all functions from the specified module

'Python > Python Crash Course' 카테고리의 다른 글

Python Crash Course: 챕터 10  (0) 2024.07.10
Python Crash Course: 챕터 9  (0) 2024.07.01
Python Crash Course: 챕터 7  (0) 2024.06.29
Python Crash Course: 챕터 6  (0) 2024.06.28
Python Crash Course: 챕터 5  (0) 2024.06.27