python基础学习[python编程从入门到实践读书笔记(连载一)]
寫在前面:本文來自筆者關于《python編程從入門到實踐》的讀書筆記與動手實踐記錄。
程序員之禪
文章目錄
- 02變量和簡單數據類型
- 03 列表簡介
- 04 操作列表
- 05 if語句
- 06 字典
- 07 用戶輸入和while循環
- 08 函數
- 09 類
- 10 文件和異常
- 11 測試代碼
- 參考
02變量和簡單數據類型
字符串
使用方法修改字符串的大小寫
方法title():字符串首字母大寫
方法lower():字符串全部變成小寫
方法upper():字符串全部變成大寫
字符串刪除空白
要確保字符串末尾沒有空白,可使用方法rstrip()
消除字符串開頭的空白,使用lstrip();
消除字符串兩端的空白,使用strip()
03 列表簡介
列表通常包含多個元素,給列表指定一個表示復數的名稱是個不錯的主意,比如letters,digits或者names。
列表索引為-1表示最后一個元素,-2表示倒數第二個元素,以此類推。
第三章練習代碼
practice01.py
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-1 pizzas = ['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-3 for digit in range(1,21):print(digit) print()# 4-4 digits = list(range(1,1000001))# print(digits)# 4-5 print(min(digits)) print(max(digits)) print(sum(digits)) print()# 4-6 digits_20 = range(1,21,2)for digit in digits_20:print(digit)print()# 4-7 digits_30 =[] for value in range(3,31):if value % 3 == 0:digits_30.append(value)for digit in digits_30 :print(digit) print()# 4-8 cubes = [value**3 for value in range(1,11)] for digit in cubes:print(digit) print()# 4-9 上一題中就是用的列表解析practice03.py
# coding:gbk# 4-10 digits = 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-11 my_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-13 foods = ('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-1 car = '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-3 alien_color ='green' if alien_color == 'green':print('您獲得了5個點')# 5-4 if alien_color =='green':print("您獲得了5個點") else:print("您獲得了10個點") # 5-5 if alien_color =='green':print("您獲得了5個點") elif alien_color == 'yellow':print("您獲得了10個點") elif alien_color == 'red':print("您獲得了15個點")# 5-6 age =60 if 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-7 favorate_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-8 users = ['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-9 if users:users = [] else:print('We need to find some users!') # 5-10 current_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-11 digits = 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-1 person_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-2 favorate_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-3 words = {'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-6 favorate_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-8 tom = {'type' : 'cat','owner': 'mom',} jerry = {'type' : 'mouse','owner': 'folk',} pets = [tom ,jerry]for pet in pets:print(pet) print()# 6-9 favorate_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-1 car = input("please input what car you like: ") print('Let me see if I can find you a ' + car )# 7-2 people_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-3 number = 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-4 prompt = '\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-5 prompt = "\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-8 sandwich_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-9 print('\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-10 responses ={}polling_active = True message = "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-2 喜歡的圖書:編寫一個名為favorite_book()
的函數,其中包含一個名為title的形參。這個函數打印一條消息,如One ofmy favorite books is Alice in Wonderland。調用這個函數,并將一本圖書的名稱作為實參傳遞給它。
8-3 T恤:編寫一個名為make_shirt()
的函數,它接受一個尺碼以及要印到T恤上的字樣。這個函數應打印一個句子,概要地說明T恤的尺碼和字樣。
使用位置實參調用這個函數來制作一件T恤;再使用關鍵字實參來調用這個函數。
8-4 大號T恤:修改函數make_shirt(),使其在默認情況下制作一件印有字樣“I love Python”的大號T恤。調用這個函數來制作如下T恤:一件印有默認字樣的大號T恤、一件印有默認字樣的中號T恤和一件印有其他字樣的T恤(尺碼無關緊要)。
# 8-4 def 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-6 城市名:編寫一個名為city_country()
的函數,它接受城市的名稱及其所屬的國家。這個函數應返回一個格式類似于下面這樣的字符串:
“Santiago, Chile”
至少使用三個城市-國家對調用這個函數,并打印它返回的值。
8-7 專輯:編寫一個名為make_album()
的函數,它創建一個描述音樂專輯的字典。這個函數應接受歌手的名字和專輯名,并返回一個包含這兩項信息的字典。使用這個函數創建三個表示不同專輯的字典,并打印每個返回的值,以核實字典正確地存儲了專輯的信息。
給函數make_album()添加一個可選形參,以便能夠存儲專輯包含的歌曲數。如果調用這個函數時指定了歌曲數,就將這個值添加到表示專輯的字典中。調用這個函數,并至少在一次調用中指定專輯包含的歌曲數。
# 8-7 def 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-9 魔術師:創建一個包含魔術師名字的列表,并將其傳遞給一個名為show_magicians()
的函數,這個函數打印列表中每個魔術師的名字。
8-10 了不起的魔術師:在你為完成練習8-9而編寫的程序中,編寫一個名為make_great()
的函數,對魔術師列表進行修改,在每個魔術師的名字中都加入字樣“the Great”。調用函數show_magicians(),確認魔術師列表確實變了。
8-11 不變的魔術師:修改你為完成練習8-10而編寫的程序,在調用函數make_great()時,向它傳遞魔術師列表的副本。由于不想修改原始列表,請返回修改后的列表,并將其存儲到另一個列表中。分別使用這兩個列表來調用show_magicians(),確認一個列表包含的是原來的魔術師名字,而另一個列表包含的是添加了字樣“the Great”的魔術師名字。
# 8-11 def 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-12 def 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-13 def 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)
打印返回的字典,確認正確地處理了所有的信息。
來源:百度翻譯
09 類
9-1 餐館:創建一個名為Restaurant的類,其方法__init__()
設置兩個屬性:restaurant_name和cuisine_type。創建一個名為describe_restaurant()的方法和一個名為open_restaurant()的方法,其中前者打印前述兩項信息,而后者打印一條消息,指出餐館正在營業。
根據這個類創建一個名為restaurant的實例,分別打印其兩個屬性,再調用前述兩個方法。
9-2 三家餐館:根據你為完成練習9-1而編寫的類創建三個實例,并對每個實例調用方法describe_restaurant()。
# 9-2 my_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-3 class 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-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-6 冰淇淋小店:冰淇淋小店是一種特殊的餐館。編寫一個名為IceCreamStand的類,讓它繼承你為完成練習9-1或練習9-4而編寫的Restaurant類。這兩個版本的Restaurant類都可以,挑選你更喜歡的那個即可。添加一個名為flavors的屬性,用于存儲一個由各種口味的冰淇淋組成的列表。編寫一個顯示這些冰淇淋的方法。創建一個IceCreamStand實例,并調用這個方法。
# 9-6 class 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-8 權限:編寫一個名為Privileges
的類,它只有一個屬性——privileges,其中存儲了練習9-7
所說的字符串列表。將方法show_privileges()移到這個類中。在Admin類中,將一個Privileges實例用作其屬性。創建一個Admin實例,并使用方法show_privileges()來顯示其權限。
10 文件和異常
圓周率前100萬位
pi_string.py
10-1 Python學習筆記:在文本編輯器中新建一個文件,寫幾句話來總結一下你至此學到的Python知識,其中每一行都以“In Python you can”打頭。將這個文件命名為learning_python.txt,并將其存儲到為完成本章練習而編寫的程序所在的目錄中。編寫一個程序,它讀取這個文件,并將你所寫的內容打印三次:第一次打印時讀取整個文件;第二次打印時遍歷文件對象;第三次打印時將各行存儲在一個列表中,再在with代碼塊外打印它們。
# 10-1 file_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 += line print(learning_python_string + "\n")10-2 C語言學習筆記:可使用方法replace()將字符串中的特定單詞都替換為另一個單詞。下面是一個簡單的示例,演示了如何將句子中的’dog’
替換為’cat’:
讀取你剛創建的文件learning_python.txt中的每一行,將其中的Python都替換為另一門語言的名稱,如C。將修改后的各行都打印到屏幕上。
# 10-2 learning_java_string = learning_python_string.replace('Python','Java') print(learning_java_string + '\n')10-3 訪客:編寫一個程序,提示用戶輸入其名字;用戶作出響應后,將其名字寫入到文件guest.txt中。
# 10-3 file_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-4 file_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-5 file_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-6 while 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-7 while 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-8 file_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-9 file_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(http://gutenberg.org/),并找一些你想分析的圖書。下載這些作品的文本文件或將瀏覽器中的原始文本復制到文本文件中。
你可以使用方法count()來確定特定的單詞或短語在字符串中出現了多少次。例如,下面的代碼計算’row’在一個字符串中出現了多少次:
請注意,通過使用lower()將字符串轉換為小寫,可捕捉要查找的單詞出現的所有次數,而不管其大小寫格式如何。
編寫一個程序,它讀取你在項目Gutenberg中獲取的文件,并計算單詞’the’在每個文件中分別出現了多少次。
存儲數據
使用json.dump()將數據存入到.json文件中
使用json.load()加載信息
10-11 喜歡的數字:編寫一個程序,提示用戶輸入他喜歡的數字,并使用json.dump()將這個數字存儲到文件中。再編寫一個程序,從文件中讀取這個值,并打印消息“I know your favoritenumber! It’s _____.”。
#10-11 import json filename = '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-12 import 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-13 import 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-1 def concat_city_country(city, country, population):res = city.title() + ", " + country.title()res += " - population " + str(population)return restest_cities.py
import unittest from 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
test_cities.py
import unittest from 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編程從入門到實踐讀書筆記,人民郵電出版社·圖靈社區,2016年7月
總結
以上是生活随笔為你收集整理的python基础学习[python编程从入门到实践读书笔记(连载一)]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python报错UnicodeDecod
- 下一篇: win10如何下载适合自己python版