1. 程式人生 > 實用技巧 >python基礎之函式

python基礎之函式

定義函式

def greet_user():
	print("Hello")
greet_user()

函式傳參

def greet_user(username):
	print("Hello " + username.title() + '!')
greet_user('huny')

關鍵字引數

def describe_pet(pet_name, animal_type):
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')

預設引數

def describe_pet(pet_name, animal_type='dog'):
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
describe_pet('willie')
describe_pet(pet_name='willie')

函式返回值

def get_formatted_name(first_name,last_name,middle_name=''):
	if middle_name:
		full_name = first_name + " " + middle_name + ' ' + last_name
	else:
		full_name = first_name + ' ' + last_name

	return full_name

musician = get_formatted_name('jimi','hendrix')
print(musician)

musician = get_formatted_name('john','hooker','lee')
print(musician)

函式結合迴圈

def get_formatted_name(first_name,last_name):
	full_name = first_name + " " + last_name
	return full_name

while True:
	f_name = input("First name: ")
	if f_name == "q":
		break
	l_name = input("Last name: ")
	if l_name == "q":
		break

	formatted_name = get_formatted_name(f_name,l_name)
	print('Hello, ' + formatted_name + '!')

函式結合列表

def greet_users(names):
	for name in names:
		msg = "Hello, " + name.title() + "!"
		print(msg)

username= ['hannah','ty','margot']
greet_users(username)

任意數量的引數

def make_pizza(size,*toppings):
	print(size)

	for topping in toppings:
		print("-: " + topping)

make_pizza(16,'pepperoni')
make_pizza(12,'green peppers','extra cheese')