笨办法学Python(learn python the hard way)--练习程序39-40
下面是练习39-练习40,基于python3
#ex39.py
1 ten_things = "Apples Oranges Crows Telephone Light Sugar" 2 3 print("Wait there's not 10 things in that list,let's fix that.") 4 5 stuff = ten_things.split(' ') 6 7 more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] 8 9 while len(stuff) != 10: 10 next_one = more_stuff.pop() 11 print("Adding: ", next_one) 12 stuff.append(next_one) 13 print("There's %d items now." % len(stuff)) 14 15 print("There we go: ", stuff) 16 17 print("Let's do some things with stuff.") 18 19 print(stuff[1]) 20 print(stuff[-1]) # whoa! fancy 21 print(stuff.pop()) 22 print(' '.join(stuff)) # what? cool! 23 print('#'.join(stuff[3:5])) # super stellar!
#ex40.py
1 # list 2 3 things = ['a', 'b', 'c', 'd'] 4 print(things[1]) 5 6 things[1] = 'z' 7 print(things[1]) 8 9 print(things) 10 11 # dict 12 13 stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2} 14 print(stuff['name']) 15 print(stuff['age']) 16 print(stuff['height']) 17 18 stuff['city'] = "San Francisco" 19 print(stuff['city']) 20 21 stuff[1] = "Wow" 22 stuff[2] = "Neato" 23 print(stuff[1]) 24 print(stuff[2]) 25 print(stuff) 26 27 del stuff['city'] 28 del stuff[1] 29 del stuff[2] 30 print(stuff)
#ex40+.py
1 # 练习 2 3 cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} 4 5 cities['NY'] = 'New York' 6 cities['OR'] = 'Portland' 7 8 print(cities) 9 print(cities.values()) 10 print(cities.keys()) 11 print(cities.items()) 12 13 def find_city(themap, state): 14 if state in themap: 15 return themap[state] 16 else: 17 return "Not found." 18 19 # ok pay attention! 20 cities['_find'] = find_city 21 22 j = cities.keys() 23 for i in j: 24 city_found = cities[i] 25 print(city_found) 26 27 28 while True: 29 print("State?(ENTER to quit)",end = '') 30 state = input("> ") 31 32 if not state: break 33 34 # this line is the most important ever! study! 35 city_found = cities['_find'](cities,state) 36 print(city_found)