函数

本文深入探讨了Python中函数的定义与使用方法,包括参数传递、默认参数、可变参数、关键字参数等高级特性,以及如何通过函数实现代码复用和模块化,提高编程效率。
print("----")
def greet_user():
    print("Hello!")

greet_user()

print("----")
def greet_user(username):
    print("Hello, " + username.title() + "!")
greet_user("jesse")

print("====")
def display_message():
    print("Learned method.")
display_message()

print("====")
def favorite_book(bookname):
    print("One of my favorite books is " + bookname + ".")
favorite_book("Alice in Wonderland")

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

print("----")
def describe_pet(animal_type, pet_name):
    print("I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet("hamster", "harry")
describe_pet("dog", "willie")

print("----")
def describe_pet(animal_type, pet_name):
    print("I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet("harry", "hamster")

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

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

print("----")
def describe_pet(pet_name, animal_type = "dog"):
    print("I have a " + animal_type + ".")
    print("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")

# print("----")
# def describe_pet(animal_type, pet_name):
    # print("I have a " + animal_type + ".")
    # print("My " + animal_type + "'s name is " + pet_name.title() + ".")
# describe()

print("====")
def make_shirt(size, text):
    print("The size is " + size + ".")
    print("Text is " + text + ".")
make_shirt("xxxl", "I love my family")

print("====")
def describe_city(cityname, countryname = "China"):
    print(cityname.title() + " is in " + countryname.title() + ".")

describe_city("Changchun")
describe_city("Beijing", countryname = "China")
describe_city("London", "England")

print("----")
def get_formatted_name(first_name, last_name):
    full_name = first_name + " " + last_name;
    return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

print("----")
def get_formatted_name(first_name, middle_name, last_name):
    full_name = first_name + " " + middle_name + " " + last_name
    return full_name.title()
musician = get_formatted_name('john', 'lee', 'hooker')
print(musician)

print("----")
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.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

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

print("----")
def build_person(first_name, last_name):
    person = {'first':first_name, 'last':last_name}
    return person
musician = build_person("jimi", "hendrix")
print(musician)

print("----")
def build_person(first_name, last_name, age=""):
    person = {'first':first_name, 'last':last_name}
    if age:
        person['age'] = age
    return person
musician = build_person('jimi', 'hendrix', age = 27)
print(musician)

def get_formatted_name(first_name, last_name):
    full_name = first_name + " " + last_name
    return full_name.title()
# while True:
    # print("Please tell me your name:")
    # f_name = input("First name: ")
    # l_name = input("Last name: ")

    # formatted_name = get_formatted_name(f_name, l_name)
    # print("\nHello, " + formatted_name + "!")

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

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
    formatted_name = get_formatted_name(f_name, l_name)
    print("\nHello, " + formatted_name + "!")
    
print("====")
def city_country(city, country):
    temp = city + "," + country
    return temp
print(city_country('Shanghai','China'))
print(city_country('Soul','South Korea'))
print(city_country('PyoungYang','North Korea'))

print("====")
def make_albumn(singer, albumnName):
    singer_albumn = {"singer":singer, "albumn":albumnName}
    return singer_albumn
print(make_albumn("ZhouJielun", "albumn1"))
print(make_albumn("Linyilian", "Zhishaohaiyouni"))
print(make_albumn("Shaonvshidai", "gee"))

print("====")
def make_albumn(singer, albumnName, cnt = ''):
    if cnt:
        singer_albumn = {"singer":singer, "albumn":albumnName, "count":cnt}
    else:
        singer_albumn = {"singer":singer, "albumn":albumnName}
    return singer_albumn
print(make_albumn("ZhouJielun", "albumn1",12))
print(make_albumn("ShaoNvShiDai", "Gee",33))
print(make_albumn("LinJunjie", "YiQianNianYiHou"))

print("====")
def make_albumn(singer, albumnName, cnt = ''):
    if cnt:
        singer_albumn = {"singer":singer, "albumn":albumnName, "count":cnt}
    else:
        singer_albumn = {"singer":singer, "albumn":albumnName}
    return singer_albumn
while True:
    print("Please input singername and albumn name.")
    print("Please enter 'q' to quit.")
    singername = input("Singer name:")
    if singername == 'q':
        break
    
    albumnname = input("Albumn name:")
    if albumnname == 'q':
        break
    
    print(make_albumn(singername, albumnname))

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

names = ['hannah', 'try', 'margot']
greet_users(names)

print("----")
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
while unprinted_designs:
    current_design = unprinted_designs.pop()
    print("Printing model:" + current_design)
    completed_models.append(current_design)
print("The following models have been printed:")
for completed_model in completed_models:
    print(completed_model)

print("----")
def print_models(unprinted_designs, completed_models):
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print("Printing model: " + current_design)
        completed_models.append(current_design)

def show_completed_models(completed_models):
    print("The following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

print("----")
def print_models(unprinted_designs, completed_models):
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print("Printing model: " + current_design)
        completed_models.append(current_design)
def show_completed_models(completed_models):
    print("The following codels have been printed:")
    for completed_model in completed_models:
        print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs[:], completed_models)
show_completed_models(completed_models)
print(unprinted_designs)
        
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
print(unprinted_designs)

print("====")
def show_magicians(magicians):
    for magician in magicians:
        print(magician)
magicians = ['LiuQian', 'Magician2',"Magician3"]
show_magicians(magicians)

print("====")
def show_magicians(magicians):
    for magician in magicians:
        print(magician)
magicians = ["LiuQian", 'Magician2', "Magician3"]
show_magicians(magicians)

def make_great(magicians):
    great_magicians = []
    for magician in magicians:
        great_magicians.append("the Great " + magician)
    magicians.clear()
    for magician in great_magicians:
        magicians.append(magician)
    
make_great(magicians)
show_magicians(magicians)

print("====")
def show_magicians(magicians):
    for magician in magicians:
        print(magician)
magicians = ["LiuQian", 'Magician2', 'Magician3']
show_magicians(magicians)

def make_great(magicians):
    great_magicians = []
    for magician in magicians:
        great_magicians.append("the Great " + magician)
    
    magicians.clear()
    for magician in great_magicians:
        magicians.append(magician)
    return great_magicians
great_magicians = make_great(magicians[:])
print(">")
show_magicians(magicians)
show_magicians(great_magicians)

print("----")
def make_pizza(*toppings):
    print(toppings)
make_pizza("pepperoni")
make_pizza('mushrooms', 'green peppers', 'extra cheese')

print("----")
def make_pizza(*toppings):
    print("\nMaking a pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)
make_pizza("pepperoni")
make_pizza('mushrooms', 'green peppers', 'extra cheese')

print("----")
def make_pizza(size, *toppings):
    print("\nMaking a " + str(size) +
        "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

print("----")
def build_profile(first, last, **user_info):
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile('albert', 'einstein', location = 'princeton',field = 'physics')
print(user_profile)

print("====")
def addSandwich(seq):
    if seq == 1:
        print("Add banana.")
    elif seq == 2:
        print("Add meat.")
    elif seq == 3:
        print("Add seafood.")
print("Start add to the sandwich.")
addSandwich(1)
addSandwich(2)
addSandwich(3)

print("====")
def user_profile(firstname, lastname, **data):
    print("Name:"+firstname.title() + " " + lastname.title())
    for key,value in data.items():
        print(key.title() + ":" + value)

user_profile("Piao", "Yongyou", height = "188cm", weight = "91kg")

print("====")
def make_car(brand, model, **data):
    car = {}
    car['brand'] = brand
    car['model'] = model
    for key, value in data.items():
        car[key] = value
    return car

mycar = make_car("audi", "Q5", color='white', num='HD6KB01')
print(mycar)

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值