1.函数是带名字的代码块,用于完成具体的工作,存储在被称为模块的独立文件中。
(1)定义函数def 函数名(形参),函数体(功能),返回值
(2)形参与实参。
定义一个 获取姓名与成绩的函数,函数名为get_full_information,函数功能为将name与score拼接起来,返回值为names+scores。函数需指定两个变量names与scores,称为形式参数。
调用函数时,get_full_information(name, score),name与score为实际参数,也叫实参。
def get_full_information(names, scores):
information = names+' '+scores
return information.title()
while True:
print("(enter 'q' to quit)")
name = input("What's your name: ")
if name == 'q':
break
score = input("Your score: ")
full_information = get_full_information(name, score)
print(get_full_information)
out:(enter 'q' to quit)
What's your name: wangming
Your score: 99
<function get_full_information at 0x00000192B97D5EE0>
(enter 'q' to quit)
What's your name: lihang
Your score: 88
<function get_full_information at 0x00000192B97D5EE0>
(enter 'q' to quit)
What's your name: q
2.通过while循环,不断循环将姓名与成绩信息通过input()函数输入函数中并调用。
调用函数时,有三种方式:
第一种,实参的顺序默认和形参对应一致。例子中name对应names,score对应scores。
第二种,在实参中将名称和值关联,采用如下方式调用函数。
full_information = get_full_information(names='name', scores='score')
第三种,定义函数时,为形参scores设定默认值scores='99',调用时,只需指定根据实参name为形参names指定值即可
def get_full_information(names, scores='99'):
information = names+' '+scores
return information.title()
while True:
print("(enter 'q' to quit)")
name = input("What's your name: ")
if name == 'q':
break
#scores = input("your score: ")
full_information = get_full_information(name)
print(full_information)
设定默认真。
3.传递列表
编写两个函数,一个负责处理成绩统计,另一个概述完成了那些成绩统计。
def scores_finished(unfinished_score,finished_score):
while unfinished_score:
finishing_score = unfinished_score.pop()
print('finishing score: '+finishing_score)
finished_score.append(finishing_score)
def show_finished_score(finished_score):
print("The following scores have been finished:")
for score in finished_score:
print(finished_score)
unfinished_score=['wangming','tom','tony']
finished_score=[]
scores_finished(unfinished_score,finished_score)
show_finished_score(finished_score)
out:finishing score: tony
finishing score: tom
finishing score: wangming
The following scores have been finished:
['tony', 'tom', 'wangming']
['tony', 'tom', 'wangming']
['tony', 'tom', 'wangming']
参考文献《Python 编程从入门到实践》,中国工信出版社