返回值
函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数的返回值被称为返回值。
1. 简单的返回值
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)
调用返回值的函数时,需要提供一个变量存储返回的值。
2. 让实参变成可选的
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)
然而并非每个人都有中间名,怎样让中间名变成可选呢?
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('john', 'hooker', 'lee') print(musician) musician = get_formatted_name('jimi', 'hendrix') print(musician)
给形参中间名一个空字符为默认值,将其移动至形参列表的末尾;调用函数时确保实参中间名方最后。
相关推荐:《Python视频教程》
3. 返回字典
def build_person(first_name, last_name): person = {'first': first_name, 'last': last_name} return person musician = build_person('jimi', 'hendrix') print(musician)
扩展函数,使其接受可选值
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)
4. 结合使用函数和while循环
def get_formatted_name(first_name, last_name): full_name = first_name + ' ' + last_name return full_name.title() while True: print("\nPlease 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 + "!")
循环调用定义的函数,say hello everyone!!! 该在什么地方提供推出呢?
def get_formatted_name(first_name, last_name): full_name = 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 formatted_name = get_formatted_name(f_name, l_name) print("\nHello, " + formatted_name + "!")
每次提示用户输入时均可推出。