当前位置:   article > 正文

蟒蛇书:python编程:从入门到实践-动手试一试答案_蟒蛇书答案

蟒蛇书答案

目录

第二章和第三章:变量和简单数据类型、列表简介

第四章:操作列表

第五章:if语句

第六章:字典

第七章:用户输入和while循环

第八章:函数

第九章:类 


蟒蛇书答案,自己写的,可能有错,包含了基础部分第2章到第9章的内容

第二章和第三章:变量和简单数据类型、列表简介

  1. #p18
  2. a = "Hello python world!"
  3. # print(a)
  4. a = "again good luck!"
  5. print(a)
  6. #p23
  7. Name = "Eric"
  8. print("hello "+Name+",would you like to learn some Python today?")
  9. print(Name.lower())
  10. print(Name.upper())
  11. print(Name.title())
  12. #2-5&2-6
  13. Famous_person = "Albert Einstein"
  14. message = "A person who never made a mistake never tried anything new."
  15. print(Famous_person.title()+" once said: "+message.title())
  16. #2-7
  17. person_name = "\tJ\n\tJ\nJ"
  18. print(person_name)
  19. person_name_a = ' J '
  20. print(person_name_a.lstrip())
  21. print(person_name_a.rstrip())
  22. print(person_name_a.strip())
  23. #####2-8#####
  24. print(2+6)
  25. print(10-2)
  26. print(2*4)
  27. print(int(16/2))
  28. #####2-9#####
  29. number = 1
  30. message = "My favorite number is "+str(number)+"!"
  31. print(message)#str:将非字符串转换为字符串
  32. #####3-1&3-2#####
  33. names = ['C','J','L','C']
  34. for i in range(4):
  35. print(names[i].title()+" How is your day?")
  36. ###3-3#####
  37. tool = ['walk','bicycle']
  38. print("I would like the "+tool[1].title()+' rather than '+tool[0].title())
  39. #####3-4#####
  40. name_list = ['A','B','C','D']
  41. for i in range(4):
  42. print(name_list[i]+", would you like to have dinner with me?")
  43. #####3-5#####
  44. name_list = ['A','B','C','D']
  45. print('B cannot be here.')
  46. name_list[1] = 'E'
  47. for i in range(4):
  48. print(name_list[i]+", would you like to have dinner with me?")
  49. #####3-6#####
  50. name_list = ['A','B','C','D']
  51. print('B cannot be here.')
  52. name_list[1] = 'E'
  53. print('I have found a bigger place')
  54. name_list.insert(0,'F')
  55. name_list.insert(2,'G')
  56. name_list.append('H')
  57. for i in range(len(name_list)):
  58. print(name_list[i]+", would you like to have dinner with me?")
  59. #####3-7#####
  60. name_list = ['A','B','C','D']
  61. print('B cannot be here.')
  62. name_list[1] = 'E'
  63. print('I have found a bigger place')
  64. name_list.insert(0,'F')
  65. name_list.insert(2,'G')
  66. name_list.append('H')
  67. print("Only two")
  68. for i in range(len(name_list)):
  69. if i <5:
  70. print("Sorry"+name_list.pop())
  71. else:
  72. print("Welcome" + name_list[i-5])
  73. del name_list[0]
  74. del name_list[0]
  75. print(name_list)
  76. ######方法的调用是列表.方法();如果是函数,列表作为参数使用格式是:函数(列表),括号中都可以增加一些参数的说明比如reverse = True
  77. #####3-8#####
  78. place = ['Nuowei','Fenlan','England','Jiangnan','Haibian']
  79. # print(place)
  80. # print(sorted(place))
  81. # print(sorted(place,reverse=True))
  82. # print(place)
  83. # place.reverse()
  84. # print(place)
  85. # place.reverse()
  86. # print(place)
  87. place.sort()
  88. print(place)
  89. place.sort(reverse=True)
  90. print(place)
  91. ######3-9######
  92. name_list = ['A','B','C','D']
  93. print('B cannot be here.')
  94. name_list[1] = 'E'
  95. print('I have found a bigger place')
  96. name_list.insert(0,'F')
  97. name_list.insert(2,'G')
  98. name_list.append('H')
  99. print(len(name_list))
  100. ######3-11######
  101. place = ['Nuowei','Fenlan','England','Jiangnan','Haibian']
  102. print(place[4])

第四章:操作列表

  1. ######4-1######
  2. pizzas = ['vegetable','fruit','french fries','liulian']
  3. for pizza in pizzas:
  4. print(pizza)
  5. pizzas = ['vegetable','fruit','french fries','liulian']
  6. for pizza in pizzas:
  7. print('I like '+pizza+' pizza!')
  8. pizzas = ['vegetable','fruit','french fries','liulian']
  9. for pizza in pizzas:
  10. print('I like '+pizza+' pizza!')
  11. print('I really love pizza!')
  12. ######4-3######
  13. for number in range(1,21):
  14. print(number)
  15. ######4-4######
  16. numbers = list(range(1,1000001))
  17. for number in numbers:
  18. print(number)
  19. ######4-5######
  20. numbers = list(range(1,1000001))
  21. print(min(numbers))
  22. print(max(numbers))
  23. print(sum(numbers))
  24. ######4-6######
  25. numbers = list(range(1,21,2))
  26. for number in numbers:
  27. print(number)
  28. ######4-7######
  29. numbers = []
  30. for value in range(1,11):
  31. number = value*3
  32. numbers.append(number)
  33. print(numbers)
  34. ######4-8######
  35. numbers = []
  36. for value in range(1,11):
  37. number = value**3
  38. numbers.append(number)
  39. print(number)
  40. print(numbers)
  41. ######4-9######
  42. numbers=[number**3 for number in range(1,11)]
  43. print(numbers)
  44. ######4-10######
  45. numbers=list(range(1,11))
  46. print('The original list is:')
  47. print(numbers)
  48. print('The first three items in the list are:')
  49. print(numbers[0:3])
  50. print('Three items from the middle of the list are:')
  51. print(numbers[3:6])
  52. print('The last three items in the list are:')
  53. print(numbers[-3:])
  54. #####4-11#####
  55. pizzas = ['vegetable','fruit','french fries','liulian']
  56. friend_pizzas = pizzas[:]
  57. pizzas.append('cake')
  58. friend_pizzas.append('candy')
  59. print('My favorite pizzas are:')
  60. for pizza in pizzas:
  61. print(pizza)
  62. print("My friend's favorite pizzas are:")
  63. for friend_pizza in friend_pizzas:
  64. print(friend_pizza)
  65. #####4-12#####
  66. my_foods = ['pizza','falafel','carrot cake']
  67. friend_foods = my_foods[:]
  68. for my_food in my_foods:
  69. print('Me:'+my_food)
  70. for friend_food in friend_foods:
  71. print("My friend's: " + friend_food)
  72. #####4-13#####
  73. foods = ('apple','pear','soup','noodle','dessert')
  74. for food in foods:
  75. print(food)
  76. foods[0] = ['juice']
  77. foods = ('juice','coffee','soup','noodle','dessert')
  78. for food in foods:
  79. print(food)

第五章:if语句

  1. #####5-1#####
  2. food = 'apple'
  3. print('Is fruit == apple? I predict True.')
  4. print(food == 'apple')
  5. print('\nIs fruit == pear? I predict False.')
  6. print(food == 'pear')
  7. food = 'orange'
  8. print('Is fruit == orange? I predict True.')
  9. print(food == 'orange')
  10. print('\nIs fruit == pear? I predict False.')
  11. print(food == 'pear')
  12. food = 'strawberry'
  13. print('Is fruit == strawberry? I predict True.')
  14. print(food == 'strawberry')
  15. print('\nIs fruit == pear? I predict False.')
  16. print(food == 'pear')
  17. food = 'banana'
  18. print('Is fruit == banana? I predict True.')
  19. print(food == 'banana')
  20. print('\nIs fruit == pear? I predict False.')
  21. print(food == 'pear')
  22. food = 'pineapple'
  23. print('Is fruit == pineapple? I predict True.')
  24. print(food == 'pineapple')
  25. print('\nIs fruit == pear? I predict False.')
  26. print(food == 'pear')
  27. #####5-2#####
  28. character = 'Good luck'
  29. if character != 'lucky':
  30. print('Lucky is not the character')
  31. else:
  32. print('Lucky is the original character')
  33. food = 'Soup'
  34. print(food == 'soup')
  35. print(food.lower() == 'soup')
  36. number = 55
  37. print(number == 55)
  38. print(number == 67)
  39. print(number > 67)
  40. print(number < 67)
  41. print(number >= 80)
  42. print(number <= 80)
  43. number_1 = 67
  44. number_2 = 98
  45. print(number_1>20 and number_2<100)
  46. print(number_1<20 or number_2>100)
  47. numbers = [13,35,46,68,79,80,98]
  48. print(24 in numbers)
  49. print(98 not in numbers)
  50. #####5-3#####
  51. alien_color = ['green','yellow','red']
  52. color = 'yellow'
  53. if color == 'green':
  54. print("You get 5 points!")
  55. else:
  56. color = 'green'
  57. #####5-4#####
  58. alien_color = ['green','yellow','red']
  59. color = 'yellow'
  60. if color == 'green':
  61. print("You get 5 points!")
  62. else:
  63. print("You get 10 points!")
  64. if color == 'green':
  65. print("You get 5 points!")
  66. if color != 'green':
  67. print("You get 10 points!")
  68. #####5-5#####
  69. alien_color = ['green','yellow','purple']
  70. color = 'purple'
  71. if color == 'green':
  72. print("You get 5 points!")
  73. elif color == 'yellow':
  74. print("You get 10 points!")
  75. else:
  76. print("You get 15 points!")
  77. if color == 'green':
  78. print("You get 5 points!")
  79. if color == 'yellow':
  80. print("You get 10 points!")
  81. if color == 'purple':
  82. print('You get 15 points!')
  83. #####5-6#####
  84. age = 1
  85. if age < 2:
  86. print('You are a baby')
  87. elif age>=2 and age<4:
  88. print("You're a toddler")
  89. elif age>=4 and age<13:
  90. print("You are a child")
  91. elif age>=13 and age<20:
  92. print("You are a teenager")
  93. elif age >= 20 and age < 65:
  94. print("You are an adult")
  95. else:
  96. print("You are an older")
  97. #####5-7#####
  98. favorite_fruits = ['apple','orange','banana']
  99. if 'grape' in favorite_fruits:
  100. a =1
  101. if 'banana' in favorite_fruits:
  102. print('You really like bnanas!')
  103. if 'pineapple' in favorite_fruits:
  104. a =1
  105. if 'strawberry' in favorite_fruits:
  106. a =1
  107. if 'lemon' in favorite_fruits:
  108. a =1
  109. #####5-8#####
  110. names = ['Admin','Eric','Tom','Lisa','Jenny']
  111. for name in names:
  112. if name == 'Admin':
  113. print('Hello, '+name+', would you like to see a status report')
  114. else:
  115. print('Hello '+name+', thank you for logging in again')
  116. #####5-9#####
  117. names = ['Admin','Eric','Tom','Lisa','Jenny']
  118. names = []
  119. if names :
  120. for name in names:
  121. if name == 'Admin':
  122. print('Hello, '+name+', would you like to see a status report')
  123. else:
  124. print('Hello '+name+', thank you for logging in again')
  125. else:
  126. print('We need to find some users!')
  127. #####5-10#####
  128. current_users = ['Admin','Eric','Tom','Lisa','Jenny']
  129. new_users = ['Admin','ERIC','Linda','Jack','John']
  130. for new_user in new_users:
  131. is_duplicate = False # 初始化状态为不重复
  132. for current_user in current_users:
  133. if new_user.lower() == current_user.lower():
  134. is_duplicate = True # 如果找到相同用户名,更新状态为重复
  135. break
  136. if is_duplicate:
  137. print(new_user + ' You need to input another name.')
  138. else:
  139. print(new_user + ' is OK.')
  140. #####5-11#####
  141. numbers = [1,2,3,4,5,6,7,8,9]
  142. for number in numbers:
  143. if number == 1:
  144. print(str(number)+'st')
  145. elif number == 2:
  146. print(str(number)+'nd')
  147. elif number == 3:
  148. print(str(number)+'rd')
  149. else:
  150. print(str(number)+'th')

第六章:字典

  1. #####6-1#####
  2. acquaintance = {'first_name':'a','last_name':'B','age':'87','city':'C'}
  3. print(acquaintance['last_name'])
  4. print(acquaintance['first_name'])
  5. print(acquaintance['age'])
  6. print(acquaintance['city'])
  7. #####6-2#####
  8. like_number = {'A':'1','B':'2','C':'3','D':'4','E':'5'}
  9. print(like_number['A'])
  10. print(like_number['B'])
  11. print(like_number['C'])
  12. print(like_number['D'])
  13. print(like_number['E'])
  14. #####6-3#####
  15. code = {'for':'一种循环','if':'条件假设','and':'与运算','or':'或运算','==':'判断是否相等'}
  16. print('for if and or ==')
  17. print(code['for'],code['if'],code['and'],code['or'],code['=='])
  18. #####6-4#####
  19. code = {'for':'一种循环','if':'条件假设','and':'与运算','or':'或运算','==':'判断是否相等','!=':'不等于','tensor':'创建张量','plt.show()':'绘制图像','x.label':'给x轴起坐标轴的名字','y.label':'给y轴起坐标轴的名字'}
  20. for n,w in code.items():
  21. print('\nName:'+ n)
  22. print('\nWork:'+ w)
  23. #####6-5#####
  24. River_Country = {'nile':'egypt','Changjiang':'China','Yellow River':'China','nile':'egypt'}
  25. for r,c in River_Country.items():
  26. print('The '+ r +' runs through '+c)
  27. for r in River_Country.keys():
  28. print(r.title())
  29. for c in River_Country.values():
  30. print(c.title())
  31. #####6-6#####
  32. favorite_languages = {'jen':'Python','sarah':'c','edward':'ruby','phil':'python'}
  33. for name in favorite_languages.keys():
  34. list = ['jen','edward']
  35. if name in list:
  36. print(name+', thank you for taking the poll.')
  37. else:
  38. print(name+', please take the poll!')
  39. #####6-7#####
  40. acquaintance_1 = {'first_name':'a','last_name':'B','age':'87','city':'C'}
  41. acquaintance_2 = {'first_name':'d','last_name':'E','age':'88','city':'F'}
  42. acquaintance_3 = {'first_name':'g','last_name':'H','age':'89','city':'I'}
  43. acquaintances = [acquaintance_1,acquaintance_2,acquaintance_3]
  44. for ac in acquaintances:
  45. print(ac)
  46. #####6-8#####
  47. dog = {'Hashiqi':'John'}
  48. cat = {'Buou':'Mike'}
  49. fish = {'Gold':'Linda'}
  50. pets = [dog,cat,fish]
  51. for pet in pets:
  52. print(pet)
  53. #####6-9#####
  54. favorite_places = {'Linda':'A,B,C','Mike':'D,E,F','Jack':'G,H,I'}
  55. for name,place in favorite_places.items():
  56. print('\n'+name+' likes '+place)
  57. #####6-10#####
  58. like_number = {'A':'1','B':'2','C':'3','D':'4','E':'5'}
  59. like_number['A'] = ['1,2,3,4']
  60. like_number['B'] = ['5,6,7,8']
  61. like_number['C'] = ['9,10,11,12']
  62. like_number['D'] = ['13,14,15,16']
  63. like_number['E'] = ['17,18,19,20']
  64. for name,numbers in like_number.items():
  65. print(name+"'s favorite number are:")
  66. for number in numbers:
  67. print("\t"+number)
  68. #####6-11#####
  69. cities = {'CityA':{'Country':'A','population':'B','fact':'C'},'CityD':{'Country':'E','population':'F','fact':'G'},'CityH':{'Country':'I','population':'J','fact':'K'}}
  70. for city,infos in cities.items():
  71. print("City's name:"+city)
  72. country = infos['Country']
  73. population = infos['population']
  74. fact = infos['fact']
  75. print('Country: ' + country)
  76. print('Population: ' + population)
  77. print('Fats: ' + fact)

第七章:用户输入和while循环

  1. #####7-1#####
  2. car = input('What kind of car do you like?')
  3. print('Let me see if I can find you a '+ car +'~')
  4. #####7-2#####
  5. guests = input('How many people are dinning?:')
  6. guests = int(guests)
  7. if guests<8:
  8. print("Luckily,there are empty positions~")
  9. else:
  10. print("Sorry,our restaurant is full")
  11. #####7-3#####
  12. number = input("Please input a number:")
  13. number = int(number)
  14. if number%10 == 0:
  15. print('The number is a multiple of 10~')
  16. else:
  17. print('The number is not a multiple of 10')
  18. #####7-4#####
  19. prompt = "What toppings do you like on your pizza?:"
  20. prompt += "\nEnter 'quit' to end the program."
  21. topping = ""
  22. while topping != 'quit':
  23. topping = input(prompt)
  24. if topping !='quit':
  25. print('We will add '+topping)
  26. #####7-5#####
  27. ask = "What is your age?"
  28. ask += "\nEnter 'quit' to end the program."
  29. age = ""
  30. active = True
  31. while active:
  32. age = input(ask)
  33. if age == 'quit':
  34. active = False
  35. else:
  36. age = int(age)
  37. if age<3:
  38. print("Your ticket is free")
  39. elif age>=3 and age<12:
  40. print("Your ticket is $10")
  41. else:
  42. print("Your ticket is $15")
  43. #####7-6#####
  44. ##7-4改写##
  45. prompt = "What toppings do you like on your pizza?:"
  46. prompt += "\nEnter 'quit' to end the program."
  47. topping = ""
  48. while True:
  49. topping = input(prompt)
  50. if topping =='quit':
  51. break
  52. else:
  53. print('We will add '+topping)
  54. ##7-5改写##
  55. ask = "What is your age?"
  56. ask += "\nEnter 'quit' to end the program."
  57. age = ""
  58. while True:
  59. age = input(ask)
  60. if age == 'quit':
  61. break
  62. else:
  63. age = int(age)
  64. if age<3:
  65. print("Your ticket is free")
  66. elif age>=3 and age<12:
  67. print("Your ticket is $10")
  68. else:
  69. print("Your ticket is $15")
  70. #####7-7#####
  71. while True:
  72. print("Keep on going!Trust yourself!")
  73. #####7-8#####
  74. sandwich_orders = ['fruit','egg','chicken']
  75. finished_sandwiches = []
  76. while sandwich_orders:
  77. current_sandwich = sandwich_orders.pop()
  78. print("I made your "+current_sandwich+" sandwich~")
  79. finished_sandwiches.append(current_sandwich)
  80. print("\nThe following sandwiches have been finished:")
  81. for finished_sandwich in finished_sandwiches:
  82. print(finished_sandwich.title())
  83. #####7-9#####
  84. sandwich_orders = ['fruit','pastrami','egg','pastrami','chicken','pastrami']
  85. print("We have ",sandwich_orders)
  86. #这里要注意字符串拼接错误,字符串如果要和列表拼接,需要写成print("We have " + str(sandwich_orders))
  87. #或者是print("We have", sandwich_orders)
  88. print("But now we have run out of pastrami TAT")
  89. while 'pastrami' in sandwich_orders:
  90. sandwich_orders.remove('pastrami')
  91. print(sandwich_orders)
  92. #####7-10#####
  93. places = {}
  94. active = True
  95. while active:
  96. name = input("What is your name?")
  97. place = input("If you could visit one place in the world, where would you go?")
  98. places[name] = place
  99. repeat = input("Wouuld you like to let another person respond?(yes/no)")
  100. if repeat == 'no':
  101. active = False
  102. print('\n--- Poll Results ---')
  103. for n,p in places.items():
  104. print(n+" would like to go to "+p)

第八章:函数

  1. #####8-1#####
  2. def display_message():
  3. """打印本章学习的内容"""
  4. print("学习函数")
  5. display_message()
  6. #####8-2#####
  7. def favorite_book(Book_name):
  8. print("One of my favorite books is "+Book_name.title())
  9. favorite_book('alice in wonderland')
  10. #####8-3####
  11. def make_shirt(size,characters):
  12. print("This T-shirt's size is "+ size)
  13. print("\nWith "+ characters.upper() +' on it.')
  14. make_shirt(size="M",characters="GOOD LUCK")#关键字实参
  15. make_shirt("M","GOOD LUCK")#位置实参
  16. #####8-4####
  17. def make_shirt(size = "L",characters = "I Love Python"):
  18. print("This T-shirt's size is "+ size)
  19. print("With "+ characters.upper() +' on it.\n')
  20. make_shirt()
  21. make_shirt(size="M")
  22. make_shirt(characters="GOOD LUCK")
  23. #####8-5####
  24. def describe_city(name,country = "A"):
  25. print(name.title()+" is in "+country)
  26. describe_city(name = "B")
  27. describe_city(name = "C",country="D")
  28. describe_city(name="E", country="F")
  29. #####8-6####
  30. def city_country(city,country):
  31. full = city+","+country
  32. return full.title()
  33. Full = city_country('santiago','chile')
  34. print(Full)
  35. #####8-7####
  36. def make_album(singer,album,number =""):
  37. infor = {'singer':singer,'album':album}
  38. if number:
  39. infor['number'] = number
  40. return infor
  41. music = make_album('Jack','Long Time')
  42. print(music)
  43. music = make_album('Jack','Short Time',3)
  44. print(music)
  45. music = make_album('Jack','No Time',1)
  46. print(music)
  47. #字典添加值,字典名称['键名'] = 值,是数值不用加引号,是字符需要添加引号
  48. #对于可选择的参数,如果想要在最后的结果中不显示,可以在形参时设置为""但是两个引号之间不要加负号,否则不管给不给number赋值,都会在结果中被打印出来
  49. #####8-8####
  50. #定义函数
  51. def make_album(singer,album,number =""):
  52. infor = {'singer':singer,'album':album}
  53. if number:
  54. infor['number'] = number
  55. return infor
  56. #while循环
  57. while True:
  58. print("Please input your favorite singer and album:")
  59. print("(enter 'q' at any time to quit)")
  60. singer = input("The singer:")
  61. if singer == 'q':
  62. break
  63. album = input("The album:")
  64. if album == 'q':
  65. break
  66. prefer = make_album(singer,album)#作为形参名称传递时,不需要添加引号;作为形参内容传递时,添加上引号
  67. print("Here is your favorite singer and album: "+ str(prefer))
  68. #不可以将字符串和字典类型进行直接的拼接,需要将字典转换为字符串
  69. #也就是说,只有相同类型的数据才可以进行直接拼接,不同类型的数据需要进行类型转换,转换成相同类型才可以拼接
  70. #需要注意的是,不是所有的类型都可以转换为字符串类型,如果尝试将不可转换为字符串类型的数据使用 str() 进行转换,会抛出 TypeError 异常。
  71. #####8-9#####
  72. def show_magicians(names):
  73. """打印出每个魔术师的名字"""
  74. for name in names:
  75. print("Hey,your name is "+ name)
  76. magicians = ["Linda","Max","Caroline"]
  77. show_magicians(magicians)
  78. #####8-10#####
  79. def show_magicians(original_names,modi_names):
  80. """打印出每个魔术师的名字"""
  81. while original_names:
  82. current_name = original_names.pop()
  83. print("Hey "+ current_name)
  84. modi_names.append(current_name)
  85. def add_The_Great(modi_names):
  86. """为每个魔术师名字增加The Great"""
  87. modified_names = []
  88. while modi_names:
  89. current_name = modi_names.pop()
  90. modified_names.append("The Great: " + current_name)
  91. print(modified_names)
  92. original_names = ["Linda","Max","Caroline"]
  93. modi_names = []
  94. show_magicians(original_names,modi_names)
  95. add_The_Great(modi_names)
  96. #####8-11#####
  97. def make_great(magicians):
  98. for i in range(len(magicians)):
  99. magicians[i] = "the Great " + magicians[i]
  100. return magicians
  101. def show_magicians(magicians):
  102. for magician in magicians:
  103. print(magician)
  104. magicians = ["David Copperfield", "Criss Angel", "David Blaine"]
  105. great_magicians = make_great(magicians[:])
  106. show_magicians(great_magicians)
  107. show_magicians(magicians)#调用副本,原列表没有发生改变
  108. great_magicians = make_great(magicians)
  109. show_magicians(great_magicians)
  110. show_magicians(magicians)#调用原来的列表,列表发生了改变
  111. #####8-12#####
  112. def make_sandwiches(*toppings):
  113. """概述要制作的三明治食材"""
  114. print('\nMaking a sandwich with the following toppings: ')
  115. for topping in toppings:
  116. print('-'+topping)
  117. make_sandwiches('chicken','egg','vegetables','bread')
  118. #####8-13#####
  119. def build_profile(first,last,**user_info):
  120. """创建一个新的字典,包含用户的一切"""
  121. profile = {}
  122. profile['first_name'] = first
  123. profile['last_name'] = last
  124. for key,value in user_info.items():
  125. profile[key] = value#方括号表示法可以使用变量作为键名,而单引号或双引号则表示使用字符串作为键名
  126. return profile
  127. build_profile('AE','V',location = 'pricton',field = 'physics',prefer = 'swimming')
  128. #如果键是字符串,可以使用单引号或者双引号括起来
  129. #如果键是数字,则不需要括起来
  130. #如果键是变量,使用不带引号的变量名
  131. # 在这里,键由user_info参数传入的字符串类型,所以在代码中使用方括号表示法来表示键名,不用括号括起来
  132. #####8-14#####
  133. def car_info(productor,model,**car_info):
  134. """创建一个新的字典,包含汽车的一些信息"""
  135. profile = {}
  136. profile['productor'] = productor
  137. profile['model'] = model
  138. for key,value in car_info.items():
  139. profile[key] = value
  140. return profile
  141. info = car_info('subaru','outback',color = 'blue',tow_package = True)
  142. print(info)
  143. #####8-15#####printing_functions.py
  144. #因为没有找到print_models的代码,所以沿用了上一题代码
  145. def car_info(productor,model,**car_info):
  146. """创建一个新的字典,包含汽车的一些信息"""
  147. profile = {}
  148. profile['productor'] = productor
  149. profile['model'] = model
  150. for key,value in car_info.items():
  151. profile[key] = value
  152. return profile
  153. #####8-15#####print_models.py
  154. from printing_functions import car_info
  155. info = car_info('Audi','L6',color = 'black',tow_package = True)
  156. print(info)
  157. #####8-16#####print_models.py
  158. import printing_functions
  159. info = printing_functions.car_info('Audi','L6',color = 'black',tow_package = True)
  160. print(info)
  161. from printing_functions import car_info
  162. info = car_info('Audi','L6',color = 'black',tow_package = True)
  163. print(info)
  164. from printing_functions import car_info as ci
  165. info = ci('Audi','L6',color = 'black',tow_package = True)
  166. print(info)
  167. import printing_functions as p
  168. info = p.car_info('Audi','L6',color = 'black',tow_package = True)
  169. print(info)
  170. from printing_functions import *
  171. info = car_info('Audi','L6',color = 'black',tow_package = True)
  172. print(info)

第九章:类 

  1. #####9-1#####
  2. class Restaurant():
  3. def __init__(self,restaurant_name,cuisine_type):
  4. """初始化属性restaurant_name和cuisine_type"""
  5. self.restaurant_name = restaurant_name#获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例
  6. self.cuisine_type = cuisine_type
  7. def describe_reataurant(self):
  8. """打印属性信息"""
  9. print("Our reataurant's name is "+ self.restaurant_name.title() + ' .')
  10. print("Our restaurant's type is "+ self.cuisine_type.upper() + ' .')
  11. def open_restaurant(self):
  12. """指出餐厅正常营业"""
  13. print("We are opening now! Welcome~")
  14. restaurant = Restaurant('GOOD','bbq')
  15. restaurant.describe_reataurant()
  16. restaurant.open_restaurant()
  17. #####9-2#####
  18. class Restaurant():
  19. def __init__(self,restaurant_name,cuisine_type):
  20. """初始化属性restaurant_name和cuisine_type"""
  21. self.restaurant_name = restaurant_name#获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例
  22. self.cuisine_type = cuisine_type
  23. def describe_reataurant(self):
  24. """打印属性信息"""
  25. print("Our reataurant's name is "+ self.restaurant_name.title() + ' .')
  26. print("Our restaurant's type is "+ self.cuisine_type.upper() + ' .')
  27. def open_restaurant(self):
  28. """指出餐厅正常营业"""
  29. print("We are opening now! Welcome~")
  30. restaurant_a = Restaurant('GOOD','bbq')#根据类创建实例
  31. restaurant_a.describe_reataurant()#调用方法
  32. restaurant_b = Restaurant('LUCK','hot pot')
  33. restaurant_b.describe_reataurant()
  34. restaurant_c = Restaurant('Work hard','noodle')
  35. restaurant_c.describe_reataurant()
  36. #####9-3#####
  37. class User():
  38. def __init__(self,first_name,last_name,gender,birthday):
  39. """初始化属性"""
  40. self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
  41. self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
  42. self.gender = gender
  43. self.birthday = birthday
  44. def describe_user(self):
  45. """打印属性信息"""
  46. print("first_name: "+ self.first_name.title())
  47. print("last_name: "+ self.last_name.title())
  48. print("gender: "+ self.gender.title())
  49. print("birthday: "+ self.birthday.title())
  50. def greet_user(self):
  51. """发出个性化问候"""
  52. print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
  53. user_a = User('Jack','Black','m','3.2')#仅仅创建实例是不会打印结果的,要调用方法
  54. user_a.describe_user()
  55. user_a.greet_user()
  56. user_b = User('Linde','Wanda','f','9.7')
  57. user_b.describe_user()
  58. user_b.greet_user()
  59. #####9-4#####
  60. class Restaurant():
  61. def __init__(self,restaurant_name,cuisine_type):
  62. """初始化属性restaurant_name和cuisine_type"""
  63. self.restaurant_name = restaurant_name#获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例
  64. self.cuisine_type = cuisine_type
  65. self.number_served = 6
  66. def describe_reataurant(self):
  67. """打印属性信息"""
  68. print("Our reataurant's name is "+ self.restaurant_name.title() + ' .')
  69. print("Our restaurant's type is "+ self.cuisine_type.upper() + ' .')
  70. def open_restaurant(self):
  71. """指出餐厅正常营业"""
  72. print("We are opening now! Welcome~")
  73. def set_number_served(self,numbers):
  74. """设置就餐人数"""
  75. self.number_served = numbers
  76. def increment_number_served(self,incre):
  77. """将就餐人数进行递增"""
  78. self.number_served += incre
  79. def number_of_diners(self):
  80. """打印出有多少人就餐"""
  81. print("Here are "+str(self.number_served)+" guests~")
  82. restaurant = Restaurant('GOOD','bbq')
  83. restaurant.describe_reataurant()
  84. restaurant.open_restaurant()
  85. restaurant.set_number_served(30)
  86. restaurant.number_of_diners()
  87. restaurant.increment_number_served(10)
  88. restaurant.number_of_diners()
  89. #####9-5#####
  90. class User():
  91. def __init__(self,first_name,last_name,gender,birthday):
  92. """初始化属性"""
  93. self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
  94. self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
  95. self.gender = gender
  96. self.birthday = birthday
  97. self.login_attempts = 0
  98. def describe_user(self):
  99. """打印属性信息"""
  100. print("first_name: "+ self.first_name.title())
  101. print("last_name: "+ self.last_name.title())
  102. print("gender: "+ self.gender.title())
  103. print("birthday: "+ self.birthday.title())
  104. def greet_user(self):
  105. """发出个性化问候"""
  106. print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
  107. def increment_login_attempts(self):
  108. """login_attempts值增加1"""
  109. self.login_attempts += 1
  110. return self.login_attempts
  111. def reset__login_attempts(self):
  112. """将属性login_attempts清0"""
  113. self.login_attempts = 0
  114. return self.login_attempts
  115. user_a = User('Jack','Black','m','3.2')#仅仅创建实例是不会打印结果的,要调用方法
  116. user_a.describe_user()
  117. user_a.greet_user()
  118. num = user_a.increment_login_attempts()
  119. print(num)
  120. num = user_a.increment_login_attempts()
  121. print(num)
  122. num = user_a.increment_login_attempts()
  123. print(num)
  124. num = user_a.reset__login_attempts()
  125. print(num)
  126. #####9-6#####
  127. class Restaurant():
  128. def __init__(self,restaurant_name,cuisine_type):
  129. """初始化属性restaurant_name和cuisine_type"""
  130. self.restaurant_name = restaurant_name#获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例
  131. self.cuisine_type = cuisine_type
  132. def describe_reataurant(self):
  133. """打印属性信息"""
  134. print("Our reataurant's name is "+ self.restaurant_name.title() + ' .')
  135. print("Our restaurant's type is "+ self.cuisine_type.upper() + ' .')
  136. def open_restaurant(self):
  137. """指出餐厅正常营业"""
  138. print("We are opening now! Welcome~")
  139. class IceCreamStand(Restaurant):#括号里不要忘记指定父类
  140. """继承自Restaurant类的IceCreamStand类"""
  141. def __init__(self,restaurant_name,cuisine_type):
  142. super().__init__(restaurant_name,cuisine_type)
  143. self.flavors = []
  144. def describe_flavor(self):
  145. """显示冰淇淋口味列表"""
  146. print("We have the following flavors:")
  147. for flavor in self.flavors:
  148. print("-"+flavor)
  149. my_ice_cream = IceCreamStand("Ice Cream Palace","Ice Cream")
  150. my_ice_cream.flavors = ["Chocolate","Vanilla","Strawberry"]
  151. my_ice_cream.describe_flavor()
  152. #####9-7#####
  153. class User():
  154. def __init__(self,first_name,last_name,gender,birthday):
  155. """初始化属性"""
  156. self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
  157. self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
  158. self.gender = gender
  159. self.birthday = birthday
  160. def describe_user(self):
  161. """打印属性信息"""
  162. print("first_name: "+ self.first_name.title())
  163. print("last_name: "+ self.last_name.title())
  164. print("gender: "+ self.gender.title())
  165. print("birthday: "+ self.birthday.title())
  166. def greet_user(self):
  167. """发出个性化问候"""
  168. print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
  169. class Admin(User):
  170. """继承自User类的Admin类"""
  171. def __init__(self,first_name,last_name,gender,birthday):
  172. super().__init__(first_name,last_name,gender,birthday)
  173. self.privileges = []
  174. def show_privileges(self):
  175. print("An admin can:")
  176. for privilege in self.privileges:
  177. print("-"+privilege)
  178. admin = Admin('Jack','White','m','3.4')
  179. admin.privileges = ['can add post','can delete post','can ban user']
  180. admin.show_privileges()
  181. #####9-8#####
  182. class User():
  183. def __init__(self,first_name,last_name,gender,birthday):
  184. """初始化属性"""
  185. self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
  186. self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
  187. self.gender = gender
  188. self.birthday = birthday
  189. def describe_user(self):
  190. """打印属性信息"""
  191. print("first_name: "+ self.first_name.title())
  192. print("last_name: "+ self.last_name.title())
  193. print("gender: "+ self.gender.title())
  194. print("birthday: "+ self.birthday.title())
  195. def greet_user(self):
  196. """发出个性化问候"""
  197. print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
  198. class Privileges():
  199. def __init__(self):
  200. self.privileges = ["can add post", "can delete post", "can ban user"]
  201. def show_privileges(self):
  202. print("An admin can:")
  203. for privilege in self.privileges:
  204. print("-"+privilege)
  205. class Admin(User):
  206. """继承自User类的Admin类"""
  207. def __init__(self,first_name,last_name,gender,birthday):
  208. super().__init__(first_name,last_name,gender,birthday)
  209. self.privileges = Privileges()#创建一个Privileges实例
  210. #在这里,使用self.privileges 属性来存储一个 Privileges 类的实例对象。
  211. # Admin 类需要使用 Privileges 类中的属性和方法,而 Privileges 类的实例可以作为 Admin 类的属性来实现这一点
  212. #将 self.privileges 初始化为 Privileges()
  213. # 会在 Admin 类的每个实例创建时创建一个新的 Privileges 实例。
  214. # 这样,每个 Admin 实例都会拥有自己的 Privileges 实例,而不是共享同一个实例。
  215. # 这有助于防止多个 Admin 实例之间相互干扰,并使代码更加模块化和易于维护。
  216. #因此,在这里使用实例来创建 self.privileges 属性
  217. # 是为了创建一个独立的 Privileges 实例,而不是仅仅将一个值分配给属性。
  218. #虽然在 self.privileges = Privileges() 这句话中没有传递任何参数,但是在 Privileges 类中的 #__init__ 方法中定义了一个默认的 privileges 属性
  219. #所以在创建 Privileges 实例时,会自动使用这个默认属性。
  220. #因此,self.privileges = Privileges() 这句话中实际上是创建了一个 Privileges 类的实例
  221. #并将其存储在 Admin 类的 self.privileges 属性中。
  222. def show_privileges(self):
  223. self.privileges.show_privileges()
  224. admin = Admin('Linda','Red','f','1990-01-01')
  225. admin.show_privileges()
  226. #####9-9#####
  227. class Car():
  228. """一次模拟汽车的简单尝试"""
  229. def __init__(self,make,model,year):
  230. """初始化属性"""
  231. self.make = make#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
  232. self.model = model#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
  233. self.year = year
  234. self.odometer_reading = 0#在_init_中对属性设置了初始值之后,就无需包含为他提供初始值的形参
  235. def get_describe_name(self):
  236. """返回整洁的描述性信息"""
  237. long_name = str(self.year)+" "+self.make+' '+self.model
  238. return long_name.title()
  239. def update_odometer(self,mileage):#修改属性值方法2:通过方法修改属性值
  240. """将里程表设置为固定的值
  241. 禁止将里程表往回调"""
  242. if mileage>self.odometer_reading:
  243. self.odometer_reading = mileage
  244. else:
  245. print("You can't roll back an odometer!")
  246. def increment_odometer(self,miles):#修改属性值方法3:通过方法对属性值进行递增
  247. """将里程表读数增加指定的量"""
  248. self.odometer_reading += miles
  249. def read_odometer(self):
  250. """打印一条指出汽车里程的信息"""
  251. print("This car has "+str(self.odometer_reading)+" miles on it.")
  252. class Battery():#这里Battery作为另一个实例
  253. """一次模拟电动汽车电瓶的简单尝试"""
  254. def __init__(self,battery_size = 70):
  255. """初始化电瓶属性"""
  256. self.battery_size = battery_size
  257. def describe_battery(self):
  258. """打印一条描述电瓶容量的信息"""
  259. print("This car has a "+str(self.battery_size)+"-kWh battery.")
  260. def get_range(self):
  261. """打印一条信息,指出电瓶的续航里程"""
  262. if self.battery_size == 70:
  263. range = 240
  264. elif self.battery_size==85:
  265. range = 270
  266. message = ("This car can go approximately "+str(range))
  267. message += " miles on a full charge"
  268. print(message)
  269. def upgrade_battery(self):
  270. if self.battery_size<=85:
  271. self.battery_size = 85
  272. class ElectriCar(Car):
  273. """电动汽车独特之处"""
  274. def __init__(self,make,model,year):
  275. """初始化父类特征,再初始化电动汽车特有属性"""
  276. super().__init__(make,model,year)
  277. self.battery = Battery()#注意缩进
  278. my_electric_car = ElectriCar('Tesla', 'Model S', 2022)
  279. my_electric_car.get_describe_name()
  280. my_electric_car.battery.get_range()
  281. my_electric_car.battery.upgrade_battery()
  282. my_electric_car.battery.get_range()
  283. #这里使用battery而不是Battery是因为:battery 是 ElectricCar 类的一个属性
  284. # 这个属性引用了 Battery 类的一个实例。因为在 ElectricCar 的 __init__ 方法中
  285. # 我们创建了一个名为 battery 的 Battery 实例并将其赋值给了 self.battery 属性。
  286. # 所以 my_electric_car.battery 表示 my_electric_car 实例中的 battery 属性
  287. # 这个属性引用了一个 Battery 类的实例。
  288. #####9-10#####
  289. #创建实例,Exer.py
  290. from restaurant import Restaurant
  291. info = Restaurant('SO hot','hot pot')
  292. info.describe_reataurant()
  293. info.open_restaurant()
  294. #类,restaurant.py
  295. class Restaurant():
  296. def __init__(self,restaurant_name,cuisine_type):
  297. """初始化属性restaurant_name和cuisine_type"""
  298. self.restaurant_name = restaurant_name#获取存储在形参name中的值,并将其存储到变量name中,然后该变量被关联到当前创建的实例
  299. self.cuisine_type = cuisine_type
  300. def describe_reataurant(self):
  301. """打印属性信息"""
  302. print("Our reataurant's name is "+ self.restaurant_name.title() + ' .')
  303. print("Our restaurant's type is "+ self.cuisine_type.upper() + ' .')
  304. def open_restaurant(self):
  305. """指出餐厅正常营业"""
  306. print("We are opening now! Welcome~")
  307. #####9-11#####
  308. #创建实例,Exer.py
  309. from Admin_info import Admin
  310. admin = Admin('Linda','White','f','1990-01-01')
  311. admin.show_privileges()
  312. #类,Admin_info.py
  313. class User():
  314. def __init__(self,first_name,last_name,gender,birthday):
  315. """初始化属性"""
  316. self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
  317. self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
  318. self.gender = gender
  319. self.birthday = birthday
  320. def describe_user(self):
  321. """打印属性信息"""
  322. print("first_name: "+ self.first_name.title())
  323. print("last_name: "+ self.last_name.title())
  324. print("gender: "+ self.gender.title())
  325. print("birthday: "+ self.birthday.title())
  326. def greet_user(self):
  327. """发出个性化问候"""
  328. print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
  329. class Privileges():
  330. def __init__(self):
  331. self.privileges = ["can add post", "can delete post", "can ban user"]
  332. def show_privileges(self):
  333. print("An admin can:")
  334. for privilege in self.privileges:
  335. print("-"+privilege)
  336. class Admin(User):
  337. """继承自User类的Admin类"""
  338. def __init__(self,first_name,last_name,gender,birthday):
  339. super().__init__(first_name,last_name,gender,birthday)
  340. self.privileges = Privileges()#创建一个Privileges实例
  341. def show_privileges(self):
  342. self.privileges.show_privileges()
  343. #####9-12#####
  344. #创建实例,Exercise.py
  345. from User_b import Admin
  346. admin = Admin('Linda','White','f','1990-01-01')
  347. admin.show_privileges()
  348. #存放User类的模块 User_a.py
  349. class User():
  350. def __init__(self,first_name,last_name,gender,birthday):
  351. """初始化属性"""
  352. self.first_name = first_name#获取存储在形参中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例
  353. self.last_name = last_name#以self为前缀的变量可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量
  354. self.gender = gender
  355. self.birthday = birthday
  356. def describe_user(self):
  357. """打印属性信息"""
  358. print("first_name: "+ self.first_name.title())
  359. print("last_name: "+ self.last_name.title())
  360. print("gender: "+ self.gender.title())
  361. print("birthday: "+ self.birthday.title())
  362. def greet_user(self):
  363. """发出个性化问候"""
  364. print("Dear "+self.first_name+" "+self.last_name+" Nice to meet you~")
  365. #存放Privileges和Admin类的模块,User_b.py
  366. from User_a import User
  367. class Privileges():
  368. def __init__(self):
  369. self.privileges = ["can add post", "can delete post", "can ban user"]
  370. def show_privileges(self):
  371. print("An admin can:")
  372. for privilege in self.privileges:
  373. print("-"+privilege)
  374. class Admin(User):
  375. """继承自User类的Admin类"""
  376. def __init__(self,first_name,last_name,gender,birthday):
  377. super().__init__(first_name,last_name,gender,birthday)
  378. self.privileges = Privileges()#创建一个Privileges实例
  379. def show_privileges(self):
  380. self.privileges.show_privileges()
  381. #####9-13#####
  382. from collections import OrderedDict
  383. code = OrderedDict()
  384. code['for'] = '一种循环'
  385. code['if'] = '条件假设'
  386. code['and'] = '与运算'
  387. code['or'] = '或运算'
  388. code['=='] = '判断是否相等'
  389. for n,w in code.items():
  390. print('\nName:'+ n)
  391. print('\nWork:'+ w)
  392. #####9-14#####
  393. from random import randint
  394. class Die():
  395. def __init__(self,sides = 6):#后期对属性值需要进行更改,这里使用通过方法修改
  396. # 属性值的措施,所以会在初始化中加上sides,这样也有利于后期实例化的时候直接存放数值
  397. self.sides = sides
  398. def roll_die(self):
  399. x = randint(1,self.sides)
  400. print(x)
  401. #创建一个6面的骰子,并掷10次
  402. die6 = Die()
  403. for i in range(10):
  404. die6.roll_die()
  405. # 创建一个 10 面的骰子,并掷 10 次
  406. die10 = Die(10)
  407. for i in range(10):
  408. die10.roll_die()
  409. # 创建一个 20 面的骰子,并掷 10 次
  410. die20 = Die(20)
  411. for i in range(20):
  412. die20.roll_die()

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

闽ICP备14008679号