1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > python基础学习[python编程从入门到实践读书笔记(连载一)]

python基础学习[python编程从入门到实践读书笔记(连载一)]

时间:2019-11-17 03:33:39

相关推荐

python基础学习[python编程从入门到实践读书笔记(连载一)]

写在前面:本文来自笔者关于《python编程从入门到实践》的读书笔记与动手实践记录。

程序员之禅

文章目录

02变量和简单数据类型03 列表简介04 操作列表05 if语句06 字典07 用户输入和while循环08 函数09 类10 文件和异常11 测试代码参考

02变量和简单数据类型

字符串

使用方法修改字符串的大小写

方法title():字符串首字母大写

方法lower():字符串全部变成小写

方法upper():字符串全部变成大写

name ='li shizheng'print(name.title())

字符串删除空白

要确保字符串末尾没有空白,可使用方法rstrip()

消除字符串开头的空白,使用lstrip();

消除字符串两端的空白,使用strip()

03 列表简介

列表通常包含多个元素,给列表指定一个表示复数的名称是个不错的主意,比如letters,digits或者names。

列表索引为-1表示最后一个元素,-2表示倒数第二个元素,以此类推。

第三章练习代码

practice01.py

# coding :GBKnames = ['lishizheng','liulei','zhangdanni','huangzhe']print(names[0])print(names[1])print(names[2])print(names[-1])print()message = ' welcome to Shanghai 'print(names[0] + message)print(names[1] + message)print(names[2] + message)print(names[-1] + message)print()cars = ['Toyoto','BWM','Bentz','Xiaopeng']for car in cars :print( "I would like to own a " +car + ' car')

practice02.py

persons = ["马云","达里欧","张艺谋"]print(persons)print(persons[0] + " 先生cannot attend the meeting,他对此深表歉意\n")persons[0] = "李安"print(persons)print("现在找到一张更大的餐桌,可以容纳六个人,请再邀请三个人")persons.insert(0,"马化腾")persons.insert(2,"李永乐")persons.append("教父")print("现在参加宴会的人有:")print(persons)print('现在共邀请了' + str(len(persons)) + "位朋友")print()print("由于出现特殊情况,现在只能留下两位嘉宾:\n")guest = persons.pop()print("尊敬的 " + guest+" 先生,很抱歉通知您无法与您共度晚餐")guest = persons.pop()print("尊敬的 " + guest+" 先生,很抱歉通知您无法与您共度晚餐")guest = persons.pop()print("尊敬的 " + guest+" 先生,很抱歉通知您无法与您共度晚餐")guest = persons.pop()print("尊敬的 " + guest+" 先生,很抱歉通知您无法与您共度晚餐")for person in persons:print("尊敬的 " + person+" 先生,您今晚仍然可以参加典礼,祝您用餐愉快")print()del persons[1]del persons[0]print("下面将输出空列表")print(persons)

practice03.py

places = ['beijing','shanghai','shenzhen','rizhao','hangzhou','chengdu']print(places)print(sorted(places))print(places)print(sorted(places,reverse = True))print(places)places.reverse()print(places)places.reverse()print(places)places.sort()print(places)places.sort(reverse = True)print(places)

04 操作列表

列表解析

列表解析将for循环和创建新元素的代码合并在一行,并自动附加新元素

语法规则是:

列表名 = [计算表达式 for循环]

比如生成1~10个元素平方的列表,可以使用列表解析

squares = [value**2 for value in range(1,11)]print(squares)

列表非常适合用于存储再程序运行期间可能变化的数据集。

而元组中的元素是不能修改的。如果需要存储的一组值再程序的整个生命周期内都不变,可使用元组。

第四章练习代码

practice01.py

# 4-1pizzas = ['pizza hut' ,'pizza express','pizza kfc']for pizza in pizzas:print("I like " + pizza)print('I really love pizza\n')# 4-2animals = ['dog','cat','tiger','bear']for animal in animals:print('A ' + animal +' would make a great pet')print('Any of these animals would make a great pet')

practice02.py

# 4-3for digit in range(1,21):print(digit)print()# 4-4digits = list(range(1,1000001))# print(digits)# 4-5print(min(digits))print(max(digits))print(sum(digits))print()# 4-6digits_20 = range(1,21,2)for digit in digits_20:print(digit)print()# 4-7digits_30 =[]for value in range(3,31):if value % 3 == 0:digits_30.append(value)for digit in digits_30 :print(digit)print()# 4-8cubes = [value**3 for value in range(1,11)]for digit in cubes:print(digit)print()# 4-9 上一题中就是用的列表解析

practice03.py

# coding:gbk# 4-10digits = list(range(1,21))print('The first three items in the list are:')for digit in digits[:3]:print(digit)print()print('Three items from the middle of the list are:')for digit in digits[9:12]:print(digit)print()print('The last three items in the list are:')for digit in digits[-3:]:print(digit)print()# 4-11my_pizzas = ['pizza hut' ,'pizza express','pizza kfc']friend_pizzas = my_pizzas[:]my_pizzas.append('pizza what')friend_pizzas.append('pizza friend')print('My favorate pizzas are:')for pizza in my_pizzas:print(pizza)print()print("My friend's favorite pizzas are:")for pizza in friend_pizzas:print(pizza)print()# 4-12 参见课本# 4-13foods = ('banana','hamburger','mice','noodles','chicken')for food in foods:print(food)print()foods = ('apple','hamburger','mice','noodles','steak')for food in foods:print(food)

05 if语句

本章练习题

# 5-1car = 'subaru'print("Is car == 'subaru'? I predict True")print(car =='subaru')print("\nIs car =='audi'? I predict False")print(car == 'audi')print()books = ['C','c','c++','C++','python','java','Java','JAVA','Python','PYTHON','pyThon','pYTHON']for book in books:if book.lower() =='python':print('this is a book about python language')if book.lower() != 'python':print('not python')# 5-2 undone # 5-3alien_color ='green'if alien_color == 'green':print('您获得了5个点')# 5-4if alien_color =='green':print("您获得了5个点")else:print("您获得了10个点")# 5-5if alien_color =='green':print("您获得了5个点")elif alien_color == 'yellow':print("您获得了10个点")elif alien_color == 'red':print("您获得了15个点")# 5-6age =60if age <2 :print("This is a baby")elif age <4:print("He is learning to walk")elif age <13:print('This is a child')elif age <20:print('This is a teenager')elif age <65:print("This is an adult")elif age >= 65:print("This is an old man")# 5-7favorate_fruits =['bluebarry','banana','apple']if 'bluebarry' in favorate_fruits:print('You really like bluebarries')if 'strawbarry' not in favorate_fruits:print('You donnot like strawbarries')if 'apple' in favorate_fruits:print('You really like apples')# 5-8users = ['admin','lishizheng','azheng','hello','data']for user in users:if user == 'admin':print('Hello ' + user +',would you like to see a status report?')else:print('Hello ' + user + ',thank you for logging in again')# 5-9if users:users = []else:print('We need to find some users!')# 5-10current_users = ['lishizheng','liulei','dog','lover','azheng']new_users = ['cat','miaomiao','dog','lishizheng','hello']for user in new_users:if user.lower() in current_users:print('this name has been used, please try another name')else:print('this name has not been used, you can use it')# 5-11digits = list(range(1,10))for digit in digits:if digit == 1:print('\n1st')elif digit == 2:print('2nd')elif digit == 3:print('3rd')else :print(str(digit) +'th')

06 字典

本章练习题

# 6-1person_01={'first_name': 'shizheng','last_name': 'Li','age' : 18,'city': 'Shanghai',}print(person_01['first_name'])print(person_01['last_name'])print(person_01['age'])print(person_01['city'])# 6-2favorate_number = {'lishizheng':199,'liulei': 200,'zhangli':12,'chengjie':20000,'wangjiangtao':56,}print('lishizheng' + "'s favorate number is: " + str(favorate_number['lishizheng']))print('wangjiangtao' + "'s favorate number is: " + str(favorate_number['wangjiangtao']))print()# 6-3words = {'python' : 'a new language for me','C++' : 'my second programming language,interesting for coding.','list' : 'list in python is like dynamic array in C++',}print('python is like this: ' + words['python'])print('C++ is like this: ' + words['C++'])print('list is like this: ' + words['list'])print()# 6-4for language, character in words.items():print(language + ' is like this: ' + character)words['print'] = 'display what you what on screen'print()for language, character in words.items():print(language + ' is like this: ' + character)print()# 6-5rivers = {'nile' : 'egypt','yangtze river' : 'china','amazon' : 'brazil',}for river_name , river_country in rivers.items():print('The '+ river_name.title() + ' runs throuth '+river_country.title())print()for river_name in rivers.keys():print(river_name.title())print()for country in rivers.values():print(country.title())print()# 6-6favorate_languages = {'lishizheng' : 'phthon','zhangyinuo' : 'C++','lixiaolai' : 'phthon','liulei': 'golang',}query_students = ['zhangyinuo','chengjie','liulei','wangjiangtao']for name in query_students:if name in favorate_languages.keys():print('Thank you for the convey!')else:print('Dear ' + name + ', please take our poll!')print()# 6-7person_02 = {'first_name': 'lei','last_name': 'Li','age' : 20,'city': 'Shanghai',}person_03 = {'first_name': 'anqi','last_name': 'wang','age' : 10,'city': 'shenzhen',}people = [person_01, person_02, person_03]for person in people:print(person)print()# 6-8tom = {'type' : 'cat','owner': 'mom',}jerry = {'type' : 'mouse','owner': 'folk',}pets = [tom ,jerry]for pet in pets:print(pet)print()# 6-9favorate_places ={'lishizheng' : ['Shanghai','dongguan','chongqing'],'chengjie' : ['chengdu','New York', 'hangzhou'],'wangjiangtao': ['wuxi','Paris'],}print('everybody loves someplace, here are some answers: ')for name,place in favorate_places.items():print('\n' + name.title() + ' likes: ')for p in place:print('\t' + p)print()# 6-10favorate_number = {'lishizheng':[199,200],'liulei': [1111,111,1],'zhangli':[12],'chengjie':[1,2,3,4,5,6],'wangjiangtao':[1000000000],}for name,numbers in favorate_number.items():print(name + ' likes numbers: ')for number in numbers:print('\t' + str(number))print()# 6-11cities = {'Shanghai' : {'country': 'China','population' : '26.32 million','fact' : 'Sound infrastructure',},'Paris' : {'country': 'France','population' : '2.15 million','fact' : 'Not as romantic as the legend',},}for city,city_info in cities.items():print('\n Cityname: ' + city)print( 'it belongs to : '+ city_info['country'] + ' population: ' + city_info['population'] + ' facts about this city: ' + city_info['fact'])

07 用户输入和while循环

本章练习代码

# 7-1car = input("please input what car you like: ")print('Let me see if I can find you a ' + car )# 7-2people_to_eat = input('Please enter a number'+'\nto indicate how many people are coming for dinner: ')if int(people_to_eat) > 8:print('There is no empty table at this time')else :print('There is a table available')# 7-3number = input('Please input a number: ')if int(number) % 10 == 0:print( number+ ' is a multiple of 10')else :print(number + 'is not a multiple of 10')# 7-4prompt = '\nPlease enter the name of topping of a pizza:'prompt += "\n(Enter 'quit' when you are finished.) "while True :topping = input(prompt)if topping == 'quit':breakelse :print('We will add ' + topping + ' into our pizza!')# 7-5prompt = "\nPlease enter your age ,we will tell the ticket price: "while True:age = input(prompt)if age == 'quit' :breakage = int(age)if age < 3:print('It is free!')elif age <= 12:print('The ticket price is 12 dollars!')elif age > 12:print('The ticket price is 15 dollars!')# 7-8sandwich_orders = ['egg sandwiches','grilled cheese sandwiches','potato sandwiches','pastrami','pastrami','pastrami','pastrami',]finished_sandwiches = []while sandwich_orders :current_sandwich = sandwich_orders.pop()print("I made your " + current_sandwich.title())finished_sandwiches.append(current_sandwich)print("\nThe following sandwiches have been made:")for finished_sandwich in finished_sandwiches:print(finished_sandwich.title())# 7-9print('\nWe have these sandwiches:')print(finished_sandwiches)print("\nWe sold out all the pastrami!")while 'pastrami' in finished_sandwiches :finished_sandwiches.remove('pastrami')print(finished_sandwiches)# 7-10responses ={}polling_active = Truemessage = "If you could visit one place in the world,"message += "where would you go? "while polling_active:name = input("\nWhat is your name? ")response = input(message)responses[name] = responserepeat = input("Would you like to let another person response?"+ "(yes/no) ")if repeat == 'no':polling_active = Falseprint("\n--- Polling Result ---")for name, response in responses.items():print(name + ' would like to go to' + response)

08 函数

8-1 消息:编写一个名为display_message()

的函数,它打印一个句子,指出你在本章学的是什么。调用这个函数,确认显示的消息正确无误。

# 8-1def display_message():"""显示信息"""print("I have learned some Python syntax!")display_message()

8-2 喜欢的图书:编写一个名为favorite_book()

的函数,其中包含一个名为title的形参。这个函数打印一条消息,如One ofmy favorite books is Alice in Wonderland。调用这个函数,并将一本图书的名称作为实参传递给它。

# 8-2def favorite_book(title):print("One of my favorite books is " + title.title())favorite_book("Alice in Wonderland")

8-3 T恤:编写一个名为make_shirt()

的函数,它接受一个尺码以及要印到T恤上的字样。这个函数应打印一个句子,概要地说明T恤的尺码和字样。

使用位置实参调用这个函数来制作一件T恤;再使用关键字实参来调用这个函数。

# 8-3def make_shirt(size, inscription):print("This T-shirt is " + size.title() +",and has a " + inscription + " on it")make_shirt('M','Hello,Wolrd')make_shirt(size='L', inscription='Loving Python!')

8-4 大号T恤:修改函数make_shirt(),使其在默认情况下制作一件印有字样“I love Python”的大号T恤。调用这个函数来制作如下T恤:一件印有默认字样的大号T恤、一件印有默认字样的中号T恤和一件印有其他字样的T恤(尺码无关紧要)。

# 8-4def make_shirt(size, inscription='I love Python'):print("This T-shirt is " + size.title() +",and has a '" + inscription + "' on it")make_shirt('L')make_shirt('M')make_shirt('S','what if')

8-5 城市:编写一个名为describe_city()

的函数,它接受一座城市的名字以及该城市所属的国家。这个函数应打印一个简单的句子,如Reykjavik is in Iceland。给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。

# 8-5def describe_city(city_name, country='China'):print(city_name + " is in " + country)describe_city('Shanghai')describe_city(city_name='Chendu',country='China')describe_city('New York',country='USA')

8-6 城市名:编写一个名为city_country()

的函数,它接受城市的名称及其所属的国家。这个函数应返回一个格式类似于下面这样的字符串:

“Santiago, Chile”

至少使用三个城市-国家对调用这个函数,并打印它返回的值。

# 8-6def city_country(name, country):city_and_country =''city_and_country = name + ', ' + countryreturn city_and_countrycity1 = city_country('Shanghai', 'China')city2 = city_country('New York','USA')city3 = city_country('santiago','Chile')cities = [city1,city2,city3]for city in cities:print(city.title())

8-7 专辑:编写一个名为make_album()

的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。

给函数make_album()添加一个可选形参,以便能够存储专辑包含的歌曲数。如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。

# 8-7def make_album(singer, album, songs_number=''):album ={'singer' :singer,'album' :album}if songs_number:album['songs_number'] = songs_numberreturn albumalbum1 = make_album('Jay Jou','a song for you', 10)album2 = make_album('Jordan','what if')print(album1)print(album2)

8-8 用户的专辑:在为完成练习8-7编写的程序中,编写一个while循环,让用户输入一个专辑的歌手和名称。获取这些信息后,使用它们来调用函数make_album(),并将创建的字典打印出来。在这个while

循环中,务必要提供退出途径。

# 8-8while True:print("\nPlease tell me your favorate singer's name:")print("(enter 'q' at any time to quit)")singer = input("singer's name: ")if singer == 'q':breakalbum = input("singer's album name: ")if album == 'q':breakalbum1 = make_album(singer,album)print("There are the info: " )print(album1)

8-9 魔术师:创建一个包含魔术师名字的列表,并将其传递给一个名为show_magicians()

的函数,这个函数打印列表中每个魔术师的名字。

# 8-9def show_magicians(magicians):"""打印列表中的名字"""for magician in magicians:msg = "Hello, " + magician.title() + '!'print(msg)magicians =['li shizheng','cheng jie', 'wang jiangtao']show_magicians(magicians)

8-10 了不起的魔术师:在你为完成练习8-9而编写的程序中,编写一个名为make_great()

的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样“the Great”。调用函数show_magicians(),确认魔术师列表确实变了。

# 8-10def make_great(magicians):tmp =[]for magician in magicians:current_magician = 'the Great ' + magiciantmp.append(current_magician)return tmpmagicians = make_great(magicians)show_magicians(magicians )

8-11 不变的魔术师:修改你为完成练习8-10而编写的程序,在调用函数make_great()时,向它传递魔术师列表的副本。由于不想修改原始列表,请返回修改后的列表,并将其存储到另一个列表中。分别使用这两个列表来调用show_magicians(),确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字样“the Great”的魔术师名字。

# 8-11def show_magicians(magicians):"""打印列表中的名字"""for magician in magicians:msg = "Hello, " + magician.title() + '!'print(msg)magicians =['li shizheng','cheng jie', 'wang jiangtao']def make_great(magicians): tmp =[]for magician in magicians:current_magician = 'the Great ' + magiciantmp.append(current_magician)return tmpchanged_magicians = make_great(magicians[:])show_magicians(changed_magicians)show_magicians(magicians)

8-12 三明治:编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。

# 8-12def make_pizza(*toppings):print("\n Making a pizza with the following toppings:")for topping in toppings:print("- " + topping)make_pizza("pepperoni")make_pizza("mushrooms","green pepper","extra cheese")

8-13 用户简介:复制前面的程序user_profile.py,在其中调用build_profile()来创建有关你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键-值对。

# 8-13def build_profile(first, last, **user_info):profile = {}profile['first_name'] = firstprofile['last_name'] = lastfor key, value in user_info.items():profile[key] = valuereturn profileuser_profile = build_profile('shizheng','Lee',location = 'shanghai',field = 'Computer Science',hobby = 'Marathon')print(user_profile)

8-14 汽车:编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可少的信息,以及两个名称—值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用:

car = make_car(‘subaru’, ‘outback’, color=‘blue’, tow_package=True)

打印返回的字典,确认正确地处理了所有的信息。

来源:百度翻译

# 8-14def make_car(maker, car_type, **car_info):car_profile = {}car_profile['maker'] = makercar_profile['car_type'] = car_typefor key,value in car_info.items():car_profile[key] = valuereturn car_profilemy_car = make_car('subaru', 'outback', color='blue', tow_pachage=True)print(my_car)

09 类

9-1 餐馆:创建一个名为Restaurant的类,其方法__init__()

设置两个属性:restaurant_name和cuisine_type。创建一个名为describe_restaurant()的方法和一个名为open_restaurant()的方法,其中前者打印前述两项信息,而后者打印一条消息,指出餐馆正在营业。

根据这个类创建一个名为restaurant的实例,分别打印其两个属性,再调用前述两个方法。

# 9-1class Restaurant():def __init__(self, restaurant_name, cuisine_type):self.restaurant_name = restaurant_nameself.cuisine_type = cuisine_typedef describe_restaurant(self):print("Name is: " + self.restaurant_name.title())print("Type is: " + self.cuisine_type.title())def open_restaurant(self):print("The restaurant is open!")restaurant = Restaurant("Azheng's hotel", 'Youth Hostel')print("My hotel's name is: " + restaurant.restaurant_name.title())print("My hotel's cuisine_type is: " + restaurant.cuisine_type.title())restaurant.describe_restaurant()restaurant.open_restaurant()print()

9-2 三家餐馆:根据你为完成练习9-1而编写的类创建三个实例,并对每个实例调用方法describe_restaurant()。

# 9-2my_hotel = Restaurant('What if' ,'inn')my_hotel.describe_restaurant()your_hotel = Restaurant("seven days" ,'youth hostel')your_hotel.describe_restaurant()tom_hotel = Restaurant("hotel" ,'youth hostel')tom_hotel.describe_restaurant()

9-3 用户:创建一个名为User的类,其中包含属性first_name和last_name,还有用户简介通常会存储的其他几个属性。在类User中定义一个名为describe_user()的方法,它打印用户信息摘要;再定义一个名为greet_user()的方法,它向用户发出个性化的问候。

创建多个表示不同用户的实例,并对每个实例都调用上述两个方法。

# 9-3class User():def __init__(self, first_name, last_name, location, hobby):self.first_name =first_nameself.last_name =last_nameself.location = locationself.hobby = hobbydef describe_user(self):full_name = self.first_name + " " + self.last_nameprint( full_name +" lives in " + self.location + ' who likes ' + self.hobby)def greet_user(self):print("Have a nice day! " + self.first_name)print()friend_01 = User('Wang', 'jiangtao','Shanghai','travel')friend_01.describe_user()friend_01.greet_user()

9-4 就餐人数:在为完成练习9-1而编写的程序中,添加一个名为number_served的属性,并将其默认值设置为0。根据这个类创建一个名为restaurant的实例;打印有多少人在这家餐馆就餐过,然后修改这个值并再次打印它。

添加一个名为set_number_served()的方法,它让你能够设置就餐人数。调用这个方法并向它传递一个值,然后再次打印这个值。

添加一个名为increment_number_served()的方法,它让你能够将就餐人数递增。调用这个方法并向它传递一个这样的值:你认为这家餐馆每天可能接待的就餐人数。

# 9-4class Restaurant():def __init__(self, restaurant_name, cuisine_type):self.restaurant_name = restaurant_nameself.cuisine_type = cuisine_typeself.number_served = 0def describe_restaurant(self):print("Name is: " + self.restaurant_name.title())print("Type is: " + self.cuisine_type.title())def open_restaurant(self):print("The restaurant is open!")def set_number_served(self,number):self.number_served = numberdef increment_number_served(self,number):self.number_served += numberrestaurant = Restaurant("Azheng's hotel", 'Youth Hostel')print("restaurant can accommodate " +str(restaurant.number_served )+ ' people.')restaurant.number_served = 23print("restaurant can accommodate " +str(restaurant.number_served )+ ' people.')restaurant.set_number_served(10)print("restaurant can accommodate " +str(restaurant.number_served )+ ' people.')restaurant.increment_number_served(100)print("restaurant can accommodate " +str(restaurant.number_served )+ ' people.')print()

9-5 尝试登录次数:在为完成练习9-3而编写的User

类中,添加一个名为login_attempts 的属性。编写一个名为increment_login_attempts()的方法,它将属性login_attempts的值加1。再编写一个名为reset_login_attempts()的方法,它将属login_attempts

的值重置为0。

根据User类创建一个实例,再调用方法increment_login_attempts()

多次。打印属性login_attempts的值,确认它被正确地递增;然后,调用方法reset_login_attempts(),并再次打印属性login_attempts的值,确认它被重置为0。

# 9-5class User():def __init__(self, first_name, last_name, location, hobby):self.first_name =first_nameself.last_name =last_nameself.location = locationself.hobby = hobbyself.login_attempts = 0def increment_login_attempts(self):self.login_attempts += 1def reset_login_attempts(self):self.login_attempts = 0def describe_user(self):full_name = self.first_name + " " + self.last_nameprint( full_name +" lives in " + self.location + ' who likes ' + self.hobby)def greet_user(self):print("Have a nice day! " + self.first_name)print()friend_01 = User('Wang', 'jiangtao','Shanghai','travel')friend_01.describe_user()friend_01.greet_user()for i in range(1,5):friend_01.increment_login_attempts()print("user "+ friend_01.first_name + " has " + str(friend_01.login_attempts) + " attempts! ")friend_01.reset_login_attempts()print("user "+ friend_01.first_name + " has reset attempt to: " +str(friend_01.login_attempts))

9-6 冰淇淋小店:冰淇淋小店是一种特殊的餐馆。编写一个名为IceCreamStand的类,让它继承你为完成练习9-1或练习9-4而编写的Restaurant类。这两个版本的Restaurant类都可以,挑选你更喜欢的那个即可。添加一个名为flavors的属性,用于存储一个由各种口味的冰淇淋组成的列表。编写一个显示这些冰淇淋的方法。创建一个IceCreamStand实例,并调用这个方法。

# 9-6class IceCreamStand(Restaurant):def __init__(self, restaurant_name, cuisine_type):super().__init__(restaurant_name,cuisine_type)self.flavors = []def set_flavors(self, * ice_creams):for ice_cream in ice_creams:self.flavors.append(ice_cream)def get_flavors(self):print("We have icecreams of different flavors:")if self.flavors:for ice_cream in self.flavors:print("- " + ice_cream)else:print("We have sold out!")icecream_stand = IceCreamStand('what if', 'icecream')icecream_stand.describe_restaurant()icecream_stand.set_flavors('straybarry','bluebarry','apple')icecream_stand.get_flavors()

9-7 管理员:管理员是一种特殊的用户。编写一个名为Admin

的类,让它继承你为完成练习9-3或练习9-5而编写的User

类。添加一个名为privileges的属性,用于存储一个由字符串(如"canadd post"、“can delete post”、“can ban user”

等)组成的列表。编写一个名为show_privileges()的方法,它显示管理员的权限。创建一个Admin实例,并调用这个方法。

# 9-7class Admin(User):def __init__(self, first_name, last_name, location, hobby):super().__init__(first_name, last_name, location, hobby)self.privileges = ["can add post", "can delete post","can ban user"]def show_privileges(self):print("The Admin user has many privileges: ")for privilege in self.privileges:print("- " + privilege)admin = Admin("shizheng","Lee",'Shanghai','Marathon')admin.show_privileges()

9-8 权限:编写一个名为Privileges

的类,它只有一个属性——privileges,其中存储了练习9-7

所说的字符串列表。将方法show_privileges()移到这个类中。在Admin类中,将一个Privileges实例用作其属性。创建一个Admin实例,并使用方法show_privileges()来显示其权限。

# 9-8class User():def __init__(self, first_name, last_name, location, hobby):self.first_name =first_nameself.last_name =last_nameself.location = locationself.hobby = hobbyself.login_attempts = 0def increment_login_attempts(self):self.login_attempts += 1def reset_login_attempts(self):self.login_attempts = 0def describe_user(self):full_name = self.first_name + " " + self.last_nameprint( full_name +" lives in " + self.location + ' who likes ' + self.hobby)def greet_user(self):print("Have a nice day! " + self.first_name)print()class Admin(User):def __init__(self, first_name, last_name, location, hobby):super().__init__(first_name, last_name, location, hobby)self.privileges = ["can add post", "can delete post","can ban user"]def show_privileges(self):print("The Admin user has many privileges: ")for privilege in self.privileges:print("- " + privilege)admin = Admin("shizheng","Lee",'Shanghai','Marathon')admin.show_privileges()

10 文件和异常

圆周率前100万位

pi_string.py

file_name = r'D:\user\文档\python\python_work\pcc-master\pcc-master\chapter_10\pi_million_digits.txt'with open(file_name) as file_object:lines = file_object.readlines()pi_string =""for line in lines:pi_string += line.strip()print(pi_string[:52] +'...')print(len(pi_string))birthday = input("Enter your birthday, in the form mmddyy: ")if birthday in pi_string:print("Your birthday appears in the first million digits of pi!")else:print("Your birthday does not appear in the first million digits of pi.")

10-1 Python学习笔记:在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In Python you can”打头。将这个文件命名为learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with代码块外打印它们。

# 10-1file_name = "learning_python.txt"with open(file_name) as file_object:contents = file_object.read()print(contents+'\n')with open(file_name) as file_object:for line in file_object:print(line.rstrip())print()with open(file_name) as file_object:lines = file_object.readlines()learning_python_string = ''for line in lines:learning_python_string += lineprint(learning_python_string + "\n")

10-2 C语言学习笔记:可使用方法replace()将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的’dog’

替换为’cat’:

>>>message = "I really like dogs.">>>message.replace('dog', 'cat')'I really like cats.'

读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,如C。将修改后的各行都打印到屏幕上。

# 10-2learning_java_string = learning_python_string.replace('Python','Java')print(learning_java_string + '\n')

10-3 访客:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。

# 10-3file_name = 'guest.txt'name = input("\nPlease enter your name: ")with open(file_name,'a') as file_object:file_object.write(name)

10-4 访客名单:编写一个while循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。

# 10-4file_name1 = 'guest_book.txt'while True:msg ="\nPlease enter your name(enter 'q' to quit): "name = input(msg)if name == 'q':breakelse:print("Dear " + name + ",have a nice day!")with open(file_name1,'a') as file_object:file_object.write(name +"\n")

10-5 关于编程的调查:编写一个while循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。

# 10-5file_name2 = 'reason_for_coding.txt'while True:msg ="\nPlease enter your reason for coding(enter 'q' to quit): "reason = input(msg)if reason == 'q':breakelse:with open(file_name2,'a') as file_object:file_object.write(reason + '\n')print("Thank you for response!")

10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发ValueError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获ValueError异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。

注意:这里用的是ValueError不是TypeError,很多书上用错了!

# 10-6while True:print("\nPlease enter two numbers,and I'll add them.")print("Enter 'q' to quit.")try:first_number = input("\nFirst Number: ")if first_number == 'q':breaksecond_number = input("\nSecond Number: ")if second_number == 'q':breaksum = int(first_number) + int(second_number)except ValueError:print("you did not enter a interger number,please check!")else:print("Sum of two numbers is: " + str(sum))

10-7 加法计算器:将你为完成练习10-6而编写的代码放在一个while循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。

# 10-7while True:print("\nPlease enter two numbers,and I'll add them.")print("Enter 'q' to quit.")try:first_number = input("\nFirst Number: ")if first_number == 'q':breaksecond_number = input("\nSecond Number: ")if second_number == 'q':breaksum = int(first_number) + int(second_number)except ValueError:print("you did not enter a interger number,please check!")else:print("Sum of two numbers is: " + str(sum))

10-8 猫和狗:创建两个文件cats.txt和dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个try-except代码块中,以便在文件不存在时捕获FileNotFound错误,并打印一条友好的消息。将其中一个文件移到另一个地方,并确认except代码块中的代码将正确地执行。

# 10-8file_name1 = 'cats.txt'file_name2 = 'dogs.txt'def display_file_contents(filename):try:with open(filename) as f_obj:contents = f_obj.read()except FileNotFoundError:msg = "Sorry,the file " + file_name1 + " does not exist."print(msg)else:# 输出文件内容print("\nFile "+ filename +" includes the following contents: ")print(contents)display_file_contents(file_name1)display_file_contents(file_name2)

10-9 沉默的猫和狗:修改你在练习10-8中编写的except代码块,让程序在文件不存在时一言不发。

# 10-9file_name1 = 'cats.txt'file_name2 = 'dogs.txt'def display_file_contents(filename):try:with open(filename) as f_obj:contents = f_obj.read()except FileNotFoundError:passelse:# 输出文件内容print("\nFile "+ filename +" includes the following contents: ")print(contents)display_file_contents(file_name1)display_file_contents(file_name2)

10-10 常见单词:访问项目Gutenberg(/),并找一些你想分析的图书。下载这些作品的文本文件或将浏览器中的原始文本复制到文本文件中。

你可以使用方法count()来确定特定的单词或短语在字符串中出现了多少次。例如,下面的代码计算’row’在一个字符串中出现了多少次:

>> line = "Row, row, row your boat">> line.count('row')2>> line.lower().count('row')3

请注意,通过使用lower()将字符串转换为小写,可捕捉要查找的单词出现的所有次数,而不管其大小写格式如何。

编写一个程序,它读取你在项目Gutenberg中获取的文件,并计算单词’the’在每个文件中分别出现了多少次。

def count_words(filename,target):"""计算一个文件大致包含了多少个单词’target‘"""try:with open(filename,encoding='utf-8') as f_obj:lines = f_obj.readlines()text = ""except FileNotFoundError:msg = "Sorry,the file " + file_name1 + " does not exist."print(msg)else:for line in lines:text += linenum =text.lower().count(target)print("How many '"+ target +"' in "+ filename +"?\nThe answer is " + str(num) + ".")file_name = "the_spanish_influenza.txt"count_words(file_name,'the')

存储数据

使用json.dump()将数据存入到.json文件中

使用json.load()加载信息

import jsonnumbers = [2, 3, 5, 7, 11, 13]filename = 'numbers.json'with open(filename,'w') as f_obj:json.dump(numbers,f_obj)with open(filename) as f_obj:numbers = json.load(f_obj)print(numbers)

10-11 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用json.dump()将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息“I know your favoritenumber! It’s _____.”。

#10-11import jsonfilename = 'favorite_number.json'number = input("\nPlease enter your favorite number : ")with open(filename,'w') as f_obj:json.dump(number,f_obj)with open(filename) as f_obj:result = json.load(f_obj)print("I know your favorite number! It's " + result + ".")

10-12 记住喜欢的数字:将练习10-11中的两个程序合而为一。如果存储了用户喜欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作。

# 10-12import jsondef get_stored_number():"""如果存储了用户最喜欢的数字,就获取它"""filename = 'favorite_number.json'try:with open(filename) as f_obj:number = json.load(f_obj)except FileNotFoundError:return Noneelse:return numberdef display_number():"""展示用户最喜欢的数字"""number = get_stored_number()if number:print("Your favorite number is " + number + ".")else:number = input("What is your favorite number? ")filename = 'favorite_number.json'with open(filename, 'w') as f_obj:json.dump(number, f_obj)print("We'll remember your favorite number.")display_number()

10-13 验证用户:最后一个remember_me.py版本假设用户要么已输入其用户名,要么是首次运行该程序。我们应修改这个程序,以应对这样的情形:当前和最后一次运行该程序的用户并非同一个人。

为此,在greet_user()中打印欢迎用户回来的消息前,先询问他用户名是否是对的。如果不对,就调用get_new_username()让用户输入正确的用户名。

# 10-13import jsondef get_stored_username():"""如果存储了用户名,就获取它"""filename = "username.json"try:with open(filename) as f_obj:username = json.load(f_obj)except FileNotFoundError:return Noneelse:return usernamedef get_new_username():"""提示用户输入用户名"""username = input("What is your name? ")filename = "username.json"with open(filename, 'w') as f_obj:json.dump(username, f_obj)return usernamedef greet_user():"""问候用户,并指出其名字"""username = get_stored_username()if username: # 库存有用户名if check_name() == True:print("Welcome back, " + username + "!")else:print("Wo don't have your name." +"Please repeat your name.")username = get_new_username()print("We'll remember you when you come back," + username + "!")else:# 库存没有用户名username = get_new_username()print("We'll remember you when you come back," + username + "!")def check_name():"""检查用户名是否存在"""checkname = input("Please enter your name to verify: ")if checkname == get_stored_username():return Trueelse:return Falsegreet_user()

11 测试代码

11-1 城市和国家:编写一个函数,它接受两个形参:一个城市名和一个国家名。这个函数返回一个格式为City, Country的字符串,如Santiago, Chile。将这个函数存储在一个名为city_functions.py的模块中。

创建一个名为test_cities.py的程序,对刚编写的函数进行测试(别忘了,你需要导入模块unittest以及要测试的函数)。编写一个名为test_city_country()的方法,核实使用类似于’santiago’和’chile’这样的值来调用前述函数时,得到的字符串是正确的。运行test_cities.py,确认测试test_city_country()通过了。

city_functions.py

# 11-1def concat_city_country(city, country, population):res = city.title() + ", " + country.title()res += " - population " + str(population)return res

test_cities.py

import unittestfrom city_functions import concat_city_countryclass CityTestCase(unittest.TestCase):"""测试city_function.py"""def test_city_country(self):result = concat_city_country('santiago','chile')self.assertEqual(result, 'Santiago, Chile')unittest.main()

11-2 人口数量:修改前面的函数,使其包含第三个必不可少的形参population,并返回一个格式为City, Country -population xxx的字符串,如Santiago, Chile - population5000000。运行test_cities.py,确认测试test_city_country()未通过。

修改上述函数,将形参population设置为可选的。再次运行test_cities.py,确认测试test_city_country()又通过了。

再编写一个名为test_city_country_population()的测试,核实可以使用类似于’santiago’、'chile’和’population=5000000’这样的值来调用这个函数。再次运行test_cities.py,确认测试test_city_country_population()通过了

city_functions.py

# 11-2def concat_city_country(city, country, population=''):res = city.title() + ", " + country.title()if population:res += " - population " + str(population)return res

test_cities.py

import unittestfrom city_functions import concat_city_countryclass CityTestCase(unittest.TestCase):"""测试city_function.py"""def test_city_country(self):result = concat_city_country('santiago','chile')self.assertEqual(result, 'Santiago, Chile')def test_city_country_populaton(self):result = concat_city_country('santiago', 'chile', population=5000000)self.assertEqual(result,'Santiago, Chile - population 5000000')unittest.main()

参考

[1]Eric Matthes, python编程从入门到实践读书笔记,人民邮电出版社·图灵社区,7月

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。