《Python编程从入门到实践》_第八章_函数

冷不防 2022-05-15 06:49 306阅读 0赞

《Python编程从入门到实践》_第八章_函数

  1. print("8.1定义函数")
  2. def greet_user():
  3. print("hello!")
  4. greet_user()
  5. def greet_user(username):
  6. print("Hello, " + username.title() + "!")
  7. greet_user('Mars')
  8. # 在函数greet_user的定义中,变量username是一个形参——函数完成其工作所需的一项信息。
  9. # 在代码greet_user('Mars')中,其'Mars'就是一个实参,实参是调用函数时传递给函数的信息。
  10. print("8.2 传递实参")
  11. def describe_pet(animal_type, pet_name):
  12. print("I have a " + animal_type + ". ")
  13. print("My " + animal_type + "'s name is " + pet_name.title() + ".")
  14. describe_pet('hamster', 'harry')
  15. describe_pet('dog', 'wii')
  16. describe_pet("dog", "gii")
  17. print("8.2.2关键字实参")
  18. print("可以直接将形参和实参关联起来,这样就不必要在意顺序了。")
  19. describe_pet(animal_type='hamster', pet_name='harry')
  20. describe_pet( pet_name='harry',animal_type='hamster')
  21. print("8.2.3默认值")
  22. def describe_pet(pet_name,animal_type = 'dog'):
  23. print("I have a " + animal_type + ". ")
  24. print("My " + animal_type + "'s name is "+ pet_name.title() + ".")
  25. describe_pet(pet_name = 'ggii')
  26. describe_pet('aggii')
  27. # 由于显示的给提供了实参 就会忽略给定形参的默认值
  28. describe_pet(animal_type='hamster', pet_name='harry')
  29. print("8.2.4 等效的函数调用")
  30. def describe_pet(pet_name,animal_type = 'dog'):
  31. print("I have a " + animal_type + ". ")
  32. print("My " + animal_type + "'s name is "+ pet_name.title() + ".")
  33. # 一条名为dd的小狗
  34. describe_pet('aa')
  35. describe_pet(pet_name='cc')
  36. # 一只名为haa的仓鼠
  37. describe_pet('haa','hamster')
  38. describe_pet(pet_name='haa',animal_type='hamster')
  39. describe_pet(animal_type='hamster',pet_name='haa')
  40. #########################################################################################
  41. C:\Anaconda3\python.exe H:/python/venv/text
  42. 8.1定义函数
  43. hello!
  44. Hello, Mars!
  45. 8.2 传递实参
  46. I have a hamster.
  47. My hamster's name is Harry.
  48. I have a dog.
  49. My dog's name is Wii.
  50. I have a dog.
  51. My dog's name is Gii.
  52. 8.2.2关键字实参
  53. 可以直接将形参和实参关联起来,这样就不必要在意顺序了。
  54. I have a hamster.
  55. My hamster's name is Harry.
  56. I have a hamster.
  57. My hamster's name is Harry.
  58. 8.2.3默认值
  59. I have a dog.
  60. My dog's name is Ggii.
  61. I have a dog.
  62. My dog's name is Aggii.
  63. I have a hamster.
  64. My hamster's name is Harry.
  65. 8.2.4 等效的函数调用
  66. I have a dog.
  67. My dog's name is Aa.
  68. I have a dog.
  69. My dog's name is Cc.
  70. I have a hamster.
  71. My hamster's name is Haa.
  72. I have a hamster.
  73. My hamster's name is Haa.
  74. I have a hamster.
  75. My hamster's name is Haa.
  76. Process finished with exit code 0
  77. #########################################################################################
  78. print("8.3返回简单值")
  79. def get_formatted_name(first_name, last_name):
  80. full_name = first_name + " " + last_name
  81. return full_name.title()
  82. print("函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值")
  83. musician = get_formatted_name('jimi','hendrix')
  84. print(musician)
  85. print("8.3.2让实参变为可选的")
  86. def get_formatted_name(first_name, middle_name, last_name):
  87. full_name = first_name + " " + middle_name + " " + last_name
  88. return full_name.title()
  89. musician = get_formatted_name('jimi','lee', 'hendrix')
  90. print(musician)
  91. def get_formatted_name(first_name, last_name, middle_name=''):
  92. full_name = first_name + " " + middle_name + " " + last_name
  93. return full_name.title()
  94. musician = get_formatted_name('jimi','hendrix')
  95. print(musician)
  96. musician = get_formatted_name('jimi', 'lee', 'hendrix')
  97. print(musician)
  98. print("8.3.3返回字典")
  99. def build_person(first_name, last_name):
  100. person = {'first': first_name, 'last': last_name}
  101. return person
  102. musician = build_person('jim', 'aa')
  103. print(musician)
  104. def build_person(first_name, last_name, age = ''):
  105. person = {'first': first_name, 'last': last_name}
  106. if age:
  107. person['age'] = age
  108. return person
  109. musician = build_person('jim', 'aa',age=27)
  110. print(musician)
  111. print("8.3.4结合使用while循环和函数")
  112. while True:
  113. print("please tell me your name: ")
  114. print("(enter 'q' at any time to quit)")
  115. f_name = input("First name: ")
  116. if f_name == 'q':
  117. break
  118. l_name = input("Last name: ")
  119. if l_name == 'q':
  120. break
  121. formatted_name = get_formatted_name(f_name, l_name)
  122. print("Hello, " + formatted_name + "!")
  123. ######################################################################################
  124. C:\Anaconda3\python.exe H:/python/venv/text
  125. 8.3返回简单值
  126. 函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值
  127. Jimi Hendrix
  128. 8.3.2让实参变为可选的
  129. Jimi Lee Hendrix
  130. Jimi Hendrix
  131. Jimi Hendrix Lee
  132. 8.3.3返回字典
  133. {'first': 'jim', 'last': 'aa'}
  134. {'first': 'jim', 'last': 'aa', 'age': 27}
  135. 8.3.4结合使用while循环和函数
  136. please tell me your name:
  137. (enter 'q' at any time to quit)
  138. First name: Mars
  139. Last name: Liu
  140. Hello, Mars Liu!
  141. please tell me your name:
  142. (enter 'q' at any time to quit)
  143. First name: q
  144. Process finished with exit code 0
  145. ########################################################################################
  146. print("8.4传递列表")
  147. def greet_users(names):
  148. for name in names:
  149. msg = "Hello, " + name.title() + "!"
  150. print(msg)
  151. usernames=['a', 'b', 'c']
  152. greet_users(usernames)
  153. print("8.4.1在函数中修改列表")
  154. def print_models(upprint,completed):
  155. '''
  156. 弹出已打印的给完成的列表,并打印
  157. '''
  158. while upprint:
  159. current = upprint.pop()
  160. print("print:", current)
  161. completed.append(current)
  162. def show_models(completed):
  163. '''
  164. 显示已打印的
  165. '''
  166. print("The following models have been print:")
  167. for c in completed:
  168. print(c)
  169. upprint = ["apple", "book", "shirt"]
  170. completed = []
  171. print_models(upprint, completed)
  172. show_models(completed)
  173. # 在这个例子中,函数执行结束后,
  174. # upprint列表就空了,为了解决这个问题,
  175. # 可向函数传递列表的副本而不是原件,这样函数所做的任何修改都只影响副本,而不会影响原件
  176. print(upprint) # 发现运行之后upprint列表就空了
  177. # 切片表示法[:],创建列表副本。
  178. upprint = ["apple", "book", "shirt"]
  179. completed = []
  180. print_models(upprint[:], completed)
  181. show_models(completed)
  182. print(upprint)
  183. # 发现运行之后upprint列表还是原样
  184. # 虽然向函数传递列表的副本可以保留原始的列表的内容,但除非有充分的理由需要传递副本,
  185. # 否则还是应该讲原始数据传递给函数,因为让函数使用现成列表可以避免花时间和内存创建副本
  186. # 从而提高效率,在处理大型列表时尤其如此。
  187. print("8.5 传递任意数量的实参")
  188. print("有时候,你预先不知道函数需要接受多少个实参,好在Python允许函数从调用语句中收集任意数量的实参:")
  189. print("形参名*toppings的星号让Python创建一个名为toppings的空元祖,并将收到的所有值都封装想到这个元组中。")
  190. def make_pizza(*toppings):
  191. # 概述要制作的pizza
  192. print("\nMaking a pizza with the following toppings:")
  193. for topping in toppings:
  194. print("--", topping)
  195. make_pizza('pepperoni')
  196. make_pizza('mushrooms', 'green peppers', 'extra cheese')
  197. print("8.5.1结合使用位置实参和任意数量实参")
  198. def make_pizza(size,*toppings):
  199. # 概述要制作的pizza
  200. print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
  201. for topping in toppings:
  202. print("--", topping)
  203. make_pizza(16, 'pepperoni')
  204. make_pizza(12, 'mushrooms', 'grenn peppers', 'extra cheese')
  205. print("8.5.2使用任意数量的关键字实参")
  206. # 在下面的例子中,函数build_profile()接收名和姓,同时还接收任意数量的关键字和实参:
  207. # **info中的两个星号让python创建一个空字典,将收到的所有名称-值对都封装到这个字典里
  208. def build_profile(first_name, last_name, **info):
  209. # 创建一个字典,其中包含我们知道的有关用户的一切
  210. profile = {}
  211. profile["first_name"] = first_name
  212. profile["last_name"] = last_name
  213. for key, value in info.items():
  214. profile[key] = value
  215. return profile
  216. user_profile = build_profile("bin","liu",location="princeton",field="physics")
  217. # location="princeton",field="physics"两个键-值对
  218. print(user_profile)
  219. #########################################################################################
  220. C:\Anaconda3\python.exe H:/python/venv/text
  221. 8.4传递列表
  222. Hello, A!
  223. Hello, B!
  224. Hello, C!
  225. 8.4.1在函数中修改列表
  226. print: shirt
  227. print: book
  228. print: apple
  229. The following models have been print:
  230. shirt
  231. book
  232. apple
  233. []
  234. print: shirt
  235. print: book
  236. print: apple
  237. The following models have been print:
  238. shirt
  239. book
  240. apple
  241. ['apple', 'book', 'shirt']
  242. 8.5 传递任意数量的实参
  243. 有时候,你预先不知道函数需要接受多少个实参,好在Python允许函数从调用语句中收集任意数量的实参:
  244. 形参名*toppings的星号让Python创建一个名为toppings的空元祖,并将收到的所有值都封装想到这个元组中。
  245. Making a pizza with the following toppings:
  246. -- pepperoni
  247. Making a pizza with the following toppings:
  248. -- mushrooms
  249. -- green peppers
  250. -- extra cheese
  251. 8.5.1结合使用位置实参和任意数量实参
  252. Making a 16-inch pizza with the following toppings:
  253. -- pepperoni
  254. Making a 12-inch pizza with the following toppings:
  255. -- mushrooms
  256. -- grenn peppers
  257. -- extra cheese
  258. 8.5.2使用任意数量的关键字实参
  259. {'first_name': 'bin', 'last_name': 'liu', 'location': 'princeton', 'field': 'physics'}
  260. Process finished with exit code 0
  261. #########################################################################################
  262. # pizza.py 例子:先创建一个打印方式make_pizza.py
  263. #pizza打印方式模块
  264. def make_pizza1(size,*toppings):
  265. # 概述要制作的pizza
  266. print("\n Making a " + str(size) +
  267. "-inch pizza with the following toppings:")
  268. for topping in toppings:
  269. print("----" + topping)
  270. def make_pizza2(size,*toppings):
  271. # 概述要制作的pizza
  272. print("\nsize:",size)
  273. print("toppings:")
  274. for topping in toppings:
  275. print("====",topping)
  276. ##############################################################
  277. # import pizza
  278. # from pizza import make_pizza1, make_pizza2
  279. # pizza.make_pizza1(16,'pepperoni','mushrooms')
  280. # pizza.make_pizza2(16,'pepperoni','mushrooms')
  281. # 要调用被导入的模块中的函数,可指定导入模块的名称make_pizza和函数名make_pizza1(),并用句点来分割他们。
  282. # 这就是一种导入方法,只需编写一条import语句并在其中指定模块名,就可以在程序中使用该模块中的所有函数
  283. # make_pizza1(16, 'pepperoni', 'mushrooms')
  284. # make_pizza2(16, 'pepperoni', 'mushrooms')
  285. print("8.6.4使用as给模块定义别名")
  286. # import pizza as p
  287. # p.make_pizza1(16, 'pepperoni')
  288. # p.make_pizza2(15,'pepperoni', 'mushrooms')
  289. print("语法:from module_name import function_name as fn")
  290. print("8.6.3使用as给函数定义别名")
  291. # 给模块指定别名的通用语法如下
  292. print("语法:from module_name import function_name as fn")
  293. #pizza
  294. # from pizza import make_pizza1 as pz1, make_pizza2 as pz2
  295. # pz1(16, 'pepperoni', 'mushrooms')
  296. # pz2(16, 'pepperoni', 'mushrooms')
  297. print("8.6.5导入模块中所有的函数")
  298. print(" *可以代表前面指定模块里的所有函数")
  299. from pizza import *
  300. make_pizza1(16, 'pepperoni')
  301. make_pizza2(15,'pepperoni', 'mushrooms')
  302. ######################################################################
  303. C:\Anaconda3\python.exe H:/python/venv/text
  304. 8.6.4使用as给模块定义别名
  305. 语法:from module_name import function_name as fn
  306. 8.6.3使用as给函数定义别名
  307. 语法:from module_name import function_name as fn
  308. 8.6.5导入模块中所有的函数
  309. *可以代表前面指定模块里的所有函数
  310. Making a 16-inch pizza with the following toppings:
  311. ----pepperoni
  312. size: 15
  313. toppings:
  314. ==== pepperoni
  315. ==== mushrooms
  316. Process finished with exit code 0
  317. #####################################################################################3
  318. 给形参指定默认值时,等号两边不要有空格
  319. def function_name(parameter_0, parameter_1='default value')
  320. 对于函数调用中的关键字实参 也遵循这种约定
  321. function_name(value_0,parameter_1='value')

发表评论

表情:
评论列表 (有 0 条评论,306人围观)

还没有评论,来说两句吧...

相关阅读