Python编程:从入门到实践第八章读书笔记8.3返回值
今天在调试书中代码例子时,在8.3.3的person.py中进行age的添加时遇到问题:不论按照书上原代码还是我自己调整代码,始终打印不出年龄,却也始终没有报错,这个问题截止现在尚未解决,在此做下记录,以备后查。
#coding:gbk
#函数返回的值称为返回值
#在函数中,可使用return语句将值返回到调用函数的代码行
#返回值让你能够将程序的大部分繁重工作移到函数中去完成,从而简化主程序
#8.3.1返回简单值
#formatted_name.py
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)
#调用返回值的函数时,需要提供一个变量,用于存储返回的值
#在这里将返回值存储在了变量musician中
#8.3.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 = ""): #为了让中间名变成可选的,可让形参middle_name指定一个默认值——空字符串,
"""返回整洁的姓名""" #并在用户没有提供中间名时不使用这个形参。
if middle_name: #Python将费控字符串解读为True,若无提供中间名,则执行if代码块,反之则执行else代码块
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)
#8.3.3返回字典
#person.py
def build_person(first_name,last_name):
"""返回一个字典"""
person = {'first':first_name,'last':last_name}
return person
musician = build_person('jimi','hendirx')
print(musician)
def build_person(first_name, last_name, age=''):
"""返回一个字典,其中包含有关一个人的信息"""
person = {'first':first_name,'last':last_name}
if age:
person[age] = age
return person
musican = build_person('jimi', 'hendrix',age = 27) #不显示年龄???
print(musician)
#8.3.4结合使用函数和while循环
#greeter.py
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 + "!")