学习「“笨方法”学Python 3」第四篇

习题31 做出决定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
print("""You enter a dark room with two doors,
Do you go through door #1 or door #2?""")

door = input("> ")

if door == "1":
print("There's a giant bear here eating a cheese cake. ")
print("What do you do? ")
print("1. Take the cake. ")
print("2. Scream at the bear. ")

bear = input("> ")

if bear == "1":
print("The bear eats your face off. Good job! ")
elif bear == "2":
print("The bear eats your leggs off. Good job! ")
else:
print(f"Well, doing {bear} is probably better. ")
print("Bear runs away. ")

elif door == "2":
print(" You stare into the endless abyss at Cthulhu's retina.")
print("1. Blueberries. ")
print("2. Yellow jacket clothespins. ")
print("3. Understanding revolves yelling melodies. ")

insantity = input("> ")

if insantity == "1" or insantity == 2:
print("Your body survives powered by a mind of jello. ")
print("Good job! ")
else:
print("The insantity rots your eyes into a pool of muck. ")
print("Good job! ")

else:
print("You stumblr around and fall on a knife and die. Good job! ")

习题32 循环和列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
the_count = [1,2,3,4,5]
fruits = ['apple', 'oranges', 'pears', 'apricots']
change = [1,'pennies', 2, 'dimes', 3 , 'quarters']

for number in the_count:
print(f"This is count {number}")

for fruit in fruits:
print(f"A fruit of type : {fruit}")

for i in change:
print(f"I got {i}")


elements = []

for i in range(0, 6):
print(f"Adding {i} to the list. ")
elements.append(i)

for i in elements:
print(f"Element was : {i}")

习题33 while循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
i = 0
numbers = []

while i < 6 :
print(f"At the top i is {i} ")
numbers.append(i)

i += 1
print("Numbers now : ", numbers)
print(f"At the bottom i is {i} ")

print("The numbers: ")

for num in numbers:
print(num)

习题34 访问列表的元素

1
2
3
#animals = ['bear','tiger','penguine','zebra']
#bear = animals[0]
#访问列表里的第一个元素

习题35 分支和函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from sys import exit

def gold_room():
print("This room is full of gold. How much do you take? ")

choice = input("> ")
if "0" in choice or "1" in choices:
how_much = int(choice)
else:
dead("Man, learn to type a number. ")

if how_much < 50:
print("Nice, you're not greedy, you win! ")
exit(0)
else:
dead("You greedy bastard!")

def bear_room():
print("There is a bear here. ")
print("The bear has a bunch of another door. ")
print("The fat bear is in front of another door. ")
print("How are you going to move the bear? ")
bear_moved = False

while True:
choice = input("> ")

if choice == "take money":
dead("The bear looks at you then slaps your face off. ")
elif choice == "taunt bear" and not bear_moved:
print("The bear has moved from the door. ")
print("You can go through it now. ")
bear_moved = True
elif choice == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leggs off. ")
elif choice == "open door" and bear_moved:
gold_room()
else :
print("I got no idea what that means. ")



def cthulhu_room():
print("Here you see the great evil Cthulhu. ")
print("He, it , whatever stares at you and you go insane. ")
print("Do you flee for your life or eat your head? ")

choice = input("> ")

if "flee" in choice:
start()
elif "head" in choice:
dead("Well that was tasty! ")
else:
cthulhu_room()


def dead(why):
print(why, "Good job! ")
exit(0)


def start():
print("You are in a dark room. ")
print("There is a door to your right and left. ")
print("Which one do you take? ")

choice = input("> ")

if choice == "left":
bear_room()
elif choice == "right":
cthulhu_room()
else:
dead("You stumble around the room until you starve. ")

start()

习题36 设计和调试

1
2


习题37 复习各种符号

1
2


习题38 列表的操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ten_things = "Apples Oranges Crows Telephone Light Sugar"

print("Wait there are not 10 things in that list. Let's fix that. ")

stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song" ,"Frisbee", "Corn", "Banana", "Girl", "Boy"]

while len(stuff) != 10:
next_one = more_stuff.pop(0)
print("Adding: ",next_one)
stuff.append(next_one)
print(f"There are {len(stuff)} items now. ")

print("There we go: ", stuff)

print("Let's do some things with stuff. ")

print(stuff[1])
print(stuff[-1])
print(stuff.pop())
print(' '.join(stuff))
print('#'.join(stuff[3:5]))

习题39 字典,可爱的字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
states = {
'Oregon':'OR',
'Florida':'FL',
'California':'CA',
'New York':'NY',
'Michigan':'MI'
}

cities = {
'CA': 'San Francisco',
'MI':'Detroit',
'FL':'Jacksonville'
}

cities['NY'] = 'New York'
cities['OR'] = 'Fortland'

print('-' * 10)
print('NY State has:', cities['NY'])
print("OR State has:", cities['OR'])

print('-' * 10)
print("Michigan's abbrevition is: ", states['Michigan'] )
print("Florida's abbrevition is: ", states['Florida'])

print('-' * 10)
print("Michigan's has: ", cities[states['Michigan']] )
print("Florida's has: ", cities[states['Florida']])

print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} is abbrevited {abbrev}")

print('-' * 10)
for abbrev, city in list(cities.items()):
print(f"{abbrev} has the city {city}")

print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} state is abbrevited {abbrev}")
print(f"and has city {cities[abbrev]}")

print('-' * 10)
state = states.get('Texas')

if not state:
print("Sorry, no Texas.")


city = cities.get('Tx','Does Not Exist')
print(f"The city for the state 'TX' is: {city}")

习题40 模块、类和对象

class Song(object):

def __init__(self, lyrics):
self.lyrics = lyrics

def sing_me_a_song(self):
for line in self.lryics:
print(line)


happy_bday = Song(["Happy birthday to you",
"I don't want to get sued",
"So I'll stop right there"])

bulls_on_parade = Song(["They rally aroud the family",
"With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()
# __init__ 左右下划线是两个