当前位置:   article > 正文

《Python编程:从入门到实践》习题答案——第4章 操作列表_零基础学python第四章实战答案

零基础学python第四章实战答案
  1. # 4.1披萨:
  2. citys = ['Shanghai','Beijing','Wuhu','Shenzhen','HongKong']
  3. for city in citys:
  4. print("I like " + city + ".\n")
  5. print("I really love city.")
  6. # 4.2动物:
  7. animals = ['cat', 'dog', 'panda', 'monkey']
  8. for animal in animals:
  9. print(animal)
  10. print(f"A {animal} would make a great pet.")
  11. print("\nAny of these animals would make a great a great pet!")
  12. # 4-3 数到20
  13. for value in range(1,21):
  14. print(value)
  15. # 4-4 一百万
  16. one_millions =list(range(1,1000001))
  17. print(f"打印1~1000000的列表:{one_millions}")
  18. # 4-5 计算1~1000000的总和
  19. print(min(one_millions))
  20. print(max(one_millions))
  21. print(sum(one_millions))
  22. # 4-6 奇数:用range()创建一个列表,包含1~20的奇数;再用for循环打印出来
  23. odd_numbers = list(range(1,20,2))
  24. print(f"1~20之间的奇数:{odd_numbers}")
  25. for value in odd_numbers: # 再用for循环打印出来
  26. print(value)
  27. # 4-7 3的倍数:创建一个列表,包含3~30内能被3整除的数字;再用for循环打印出来
  28. three_numbers = list(range(3,31,3))
  29. print(f"3~30之间的奇数:{three_numbers}")
  30. for value in three_numbers:
  31. print(value)
  32. # 4-8 立方:打印1~10的立方
  33. cubes =[]
  34. for value in range(1,11):
  35. cube = value*value*value
  36. cubes.append(cube)
  37. print(cubes)
  38. for num in cubes:
  39. print(num)
  40. # 或者:不使用中间变量cube
  41. cubes = []
  42. for value in range(1,11):
  43. cubes.append(value*value*value)
  44. print(cubes)
  45. # 4-9 立方解析
  46. cubes = [value*value*value for value in range(1,11) ]
  47. print(f"1~10的立方:{cubes}")
  48. for value in cubes:
  49. print(value)
  50. # 4-10 切片
  51. my_list = [1,2,3,4,5,6,7,8,9]
  52. print(f"前三个元素:{my_list[:3]}")
  53. print(f"中间三个元素:{my_list[3:6]}")
  54. print(f"末尾三个元素:{my_list[-3:]}")
  55. # 4-11 你的披萨和我的披萨
  56. my_magicians = ['alice','david','carolina']
  57. friend_magicians = my_magicians[:] # 相当于副本
  58. my_magicians.append('bob')
  59. friend_magicians.append('liming')
  60. print(f"My_magicians are {my_magicians}")
  61. for my_magician in friend_magicians:
  62. print(my_magician)
  63. print("\n")
  64. print(f"Friend_magicians are {friend_magicians}")
  65. for friend_magician in friend_magicians:
  66. print(friend_magician)
  67. # 4-12 使用多个循环:
  68. my_foods = ['pizza', 'falafel', 'carrot cake']
  69. friend_foods = my_foods[:]
  70. for my_food in my_foods:
  71. print(my_food)
  72. # 4-13-自助餐
  73. foods = ('rich','peanut','dumpling','potato','cake') # 创建一个食物元组
  74. for food in foods:
  75. print(food)
  76. # foods[0] = ice cream #尝试修改元组,但出现报错,说明元组不可修改
  77. foods = ('rich','beef','dumpling','bacon','noodle') # 重新定义变量,这是可以的
  78. print("\n")
  79. for food in foods:
  80. print(food)
  81. # 4-14 PEP8:
  82. # 4-15 代码审核:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/561520
推荐阅读
相关标签
  

闽ICP备14008679号