1. 程式人生 > >python3 _笨方法學Python_日記_DAY5

python3 _笨方法學Python_日記_DAY5

布爾表達式 last spl erro ant 導入 plan print trace

Day5

  • 習題 24: 更多練習

 1 print("Let‘s practice everything.")
 2 print(You\‘d need to know \‘bout escapes with \\ that do \n newlines and \t tabs.)
 3 
 4 poem = """
 5 \tThe lovely world
 6 with logic so firmly planted
 7 cannot discern \n the needs of love
 8 nor comprehend passion from intuition
9 and requires an explanation 10 \n\twhere there is none. 11 """ 12 13 print("-------------") 14 print(poem) 15 print("-------------") 16 17 five = 10 - 2 + 3 - 6 18 print("This should be five: %s" % five) 19 20 def secret_formula(started): 21 jelly_beans = started * 500 22 jars = jelly_beans / 1000 23
crates = jars / 100 24 return jelly_beans, jars, crates 25 26 start_point = 10000 27 beans,jars,crates = secret_formula(start_point) 28 29 print("With a starting point of: %d" % start_point) 30 print("We‘d have %d beans, %d jars, and %d crates." % (beans,jars,crates)) 31 32 start_point = start_point / 10 33
34 print("We can also do that this way:") 35 print("We‘d have %d beans, %d jars, and %d crates." % (secret_formula(start_point)))

Let‘s practice everything.
You‘d need to know ‘bout escapes with \ that do
newlines and tabs.
-------------

The lovely world
with logic so firmly planted
cannot discern
the needs of love
nor comprehend passion from intuition
and requires an explanation

where there is none.

-------------
This should be five: 5
With a starting point of: 10000
We‘d have 5000000 beans, 5000 jars, and 50 crates.
We can also do that this way:
We‘d have 500000 beans, 500 jars, and 5 crates.

  • 習題 25: 更多更多的練習

 1 def break_words(stuff):
 2     """This function will break up words for us"""
 3     words = stuff.split( )
 4     return words
 5 
 6 def sort_words(words):
 7     """Sorts the words."""
 8     return sorted(words)
 9 
10 def print_first_word(words):
11     """Prints the first word after popping it off."""
12     word = words.pop(0)
13     print(word)
14 
15 def print_last_word(words):
16     """Prints the last word after popping it off."""
17     word = words.pop(-1)
18     print(word)
19 
20 def sort_sentence(sentence):
21     """Takes in a full sentence and returns the sorted words."""
22     words = break_words(sentence)
23     return sort_words(words)
24 
25 def print_first_and_last(sentence):
26     """Prints the first and last words of the sentence."""
27     words = break_words(sentence)
28     print_first_word(words)
29     print_last_word(words)
30 
31 def print_first_and_last_sorted(sentence):
32     """Sorts the words then prints the first and last one."""
33     words = sort_sentence(sentence)
34     print_first_word(words)
35     print_last_word(words)
 1 Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
 2 Type "copyright", "credits" or "license()" for more information.
 3 >>> import day525
 4 >>> sentence = "All good things come to those who wait."
 5 >>> words = day525.break_words(sentence)
 6 >>> words
 7 [All, good, things, come, to, those, who, wait.]
 8 >>> sorted_words = day525.sort_words(words)
 9 >>> sorted_words
10 [All, come, good, things, those, to, wait., who]
11 >>> day525.print_first_word(words)
12 All
13 >>> day525.print_last_word(words)
14 wait.
15 >>> wrods
16 Traceback (most recent call last):
17   File "<pyshell#8>", line 1, in <module>
18     wrods
19 NameError: name wrods is not defined
20 >>> words
21 [good, things, come, to, those, who]
22 >>> day525.print_first_word(sorted_words)
23 All
24 >>> day525.print_last_word(sorted_words)
25 who
26 >>> sorted_words
27 [come, good, things, those, to, wait.]
28 >>> sorted_words = day525.sort_sentence(sentence)
29 >>> sorted_Words
30 Traceback (most recent call last):
31   File "<pyshell#14>", line 1, in <module>
32     sorted_Words
33 NameError: name sorted_Words is not defined
34 >>> sorted_words
35 [All, come, good, things, those, to, wait., who]
36 >>> day525.print_first_and_last(sentence)
37 All
38 wait.
39 >>> day525.print_first_and_last_sorted(sentence)
40 All
41 who

直接在pycharm中運行,導入自定義模塊day525

 1 import sys
 2 sys.path.append("E:\py\learnpythonthehardway\Day5")
 3 import day525
 4 sentence = "All good things come to those who wait."
 5 words = day525.break_words(sentence)
 6 print(words)
 7 sorted_words = day525.sort_words(words)
 8 print(sorted_words)
 9 
10 day525.print_first_word(words)
11 day525.print_last_word(words)
12 
13 print(words)

要先加一個路徑 sys.path.append(" ")

結果:

[‘All‘, ‘good‘, ‘things‘, ‘come‘, ‘to‘, ‘those‘, ‘who‘, ‘wait.‘]
[‘All‘, ‘come‘, ‘good‘, ‘things‘, ‘those‘, ‘to‘, ‘wait.‘, ‘who‘]
All
wait.
[‘good‘, ‘things‘, ‘come‘, ‘to‘, ‘those‘, ‘who‘]

  • 習題 26: 恭喜你,現在可以考試了!

http://learnpythonthehardway.org/exercise26.txt

  • 習題 27: 記住邏輯關系

and 與
or 或
not 非

!= (not equal) 不等於
== (equal) 等於
>= (greater-than-equal) 大於等於
<= (less-than-equal) 小於等於
True 真
False 假

  • 習題 28: 布爾表達式練習

 1 a=True and True
 2 b=False and True
 3 c=1 == 1 and 2 == 1
 4 d="test" == "test"
 5 e=1 == 1 or 2 != 1
 6 f=True and 1 == 1
 7 g=False and 0 != 0
 8 h=True or 1 == 1
 9 i="test" == "testing"
10 j= 1 != 0 and 2 == 1
11 
12 print(a,b,c,d,e,f,g,h,i,j)

True False False True True True False True False False

  • 習題 29: 如果(if)

 1 people = 20
 2 cats = 30
 3 dogs = 15
 4 
 5 if people < cats:
 6     print("Too many cats! The world is doomed!")
 7 
 8 if people > cats:
 9     print("Not many cats! The world is saved!")
10 
11 if people < dogs:
12     print("The world is dry!")
13 
14 dogs +=5
15 
16 if people >= dogs:
17     print("People are greater than or equal to dogs.")
18 
19 if people <= dogs:
20     print("People are less than or equal to dogs.")
21 
22 if people == dogs:
23     print("People are dogs.")

結果:

1 Too many cats! The world is doomed!
2 People are greater than or equal to dogs.
3 People are less than or equal to dogs.
4 People are dogs.
  • 習題 30: Else 和 If

 1 people = 20
 2 cars = 30
 3 buses = 30
 4 
 5 if cars > people:
 6     print("We should take the cars.")
 7 elif cars < people:
 8     print("We should not take the cars.")
 9 else:
10     print("We can‘t decide.")
11 
12 if buses > cars:
13     print("That‘s too many buses.")
14 elif buses < cars:
15     print("Maybe we could take the buses.")
16 else:
17     print("We still can‘t decide.")
18 
19 if people > buses:
20     print("Alright, let‘s just take the buses.")
21 else:
22     print("Fine, let‘s stay home then.")

結果:

We should take the cars.
We still can‘t decide.
Fine, let‘s stay home then.

  • 習題 31: 作出決定

 1 print("You enter a dark room with two doors. Do you go through door #1 or door #2?")
 2 
 3 door = input("> ")
 4 
 5 if door == "1":
 6     print("There‘s a giant bear here eating a cheese cake. What do you do?")
 7     print("1. Take the cake.")
 8     print("2. Scream at the bear.")
 9 
10     bear = input("> ")
11 
12     if bear == "1":
13         print("The bear eats your face off. Good job!")
14     elif bear == "2":
15         print("The bear eats your legs off. Good job!")
16     else:
17         print("Well, doing %s is probably better.Bear runs away." % bear)
18 elif door == "2":
19     print("You stare into the endless abyss at Cthulhu‘s retina.")
20     print("1.Blueberries.")
21     print("2.Yellow jacket clothespins.")
22     print("3.Understanding revolvers yelling melodies.")
23 
24     insanity = input("> ")
25 
26     if insanity == "1" or insanity == "2":
27         print("Your body survives powered by a mind of jello. Good job!")
28     else:
29         print("The insanity rots your eyes into a pool of muck. Good job!")
30 
31 else:
32     print("You stumble around and fall on a knife and die. Good job!")

結果:

You enter a dark room with two doors. Do you go through door #1 or door #2?
> 1
There‘s a giant bear here eating a cheese cake. What do you do?
1. Take the cake.
2. Scream at the bear.
> 3
Well, doing 3 is probably better.Bear runs away.

  • 習題 32: 循環和列表

 1 the_count = [ 1, 2, 3, 4 , 5]
 2 fruits = [apples, oranges, pears, apricots]
 3 change = [1, pennies, 2, dimes, 3, quarters]
 4 
 5 #this first kind of for-loop goes through a list
 6 for number in the_count:
 7     print("This is count %d" % number)
 8 
 9 #same as above
10 for fruit in fruits:
11     print("A fruit of type: %s" % fruit)
12 
13 #also we can go through mixed lists too
14 #notice we have to use %r since we don‘t know what‘s in it
15 for i in change:
16     print("I got %r" % i)
17 
18 #we can also build lists, first start with an empty one
19 elements = []
20 
21 #then use the range function to do 0 to 5 counts
22 for i in range(0,6):
23     print("Adding %d to the list." % i)
24     #append is a function tha lists understand
25     elements.append(i)
26 
27 #now we can print them out too
28 for i in elements:
29     print("Element was: %d" % i)

結果

This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got ‘pennies‘
I got 2
I got ‘dimes‘
I got 3
I got ‘quarters‘
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5

python3 註意:

elements=list(range(0,6,2))
print(elements)
print(range(0,6,2))


[0, 2, 4]
range(0, 6, 2)

python3使用range是一個生成器,
python2使用range是一個列表,
python2使用xrange是一個生成器。

要得到列表應該 list(range(x,y,z))

  • 習題 33: While 循環

 1 i = 0
 2 numbers = list()
 3 
 4 while i < 6:
 5     print("At the top i is %d" % i)
 6     numbers.append(i)
 7     i+=1
 8     print("Numbers now:",numbers)
 9     print("At the bottom i is %d" % i)
10 
11 print("The numbers:")
12 
13 for num in numbers:
14     print(num)

結果:

At the top i is 0
Numbers now: [0]
At the bottom i is 1
At the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5

加分題:

先定義

1 def kl(b):
2     """創建一個從零到 b-1 的列表 間隔為 1 """
3     i = 0
4     numbers = list()
5 
6     while i < b:
7         numbers.append(i)
8         i += 1
9     return numbers

執行:

1 import sys
2 sys.path.append("E:\py\learnpythonthehardway\Day5")
3 import d533extra
4 x=d533extra.kl(6)
5 print(x)

結果:

[0, 1, 2, 3, 4, 5]

  • 習題 34: 訪問列表的元素

1 animals = [bear, tiger, penguin, zebra]
2 bear = animals[0]
3 tiger = animals[1]
4 penguin = animals[2]
5 zebra = animals[3]
6 
7 print("\n",bear,"\n",tiger,"\n",penguin,"\n",zebra)


bear
tiger
penguin
zebra

  • 習題 35: 分支和函數

 1 from sys import exit
 2 
 3 def gold_room():
 4     print("This room is full of gold. How much do you take?")
 5     dead=print("Man, learn to type a number.")
 6     dead2=print()
 7     next1=input("> ")
 8     if "0" in next1 or "1" in next1:
 9         how_much = int(next1)
10         if how_much < 50:
11             print("Nice, you‘re not greedy, you win!")
12             exit(0)
13         else:
14             dead2
15     else:
16         dead
17 
18 def bear_room():
19     print("There is a bear here.")
20     print("The bear has a bunch of honey.")
21     print("The fat bear is in front of another door.")
22     print("How are you going to move the bear?")
23     bear_moved = False
24 
25     while True:
26         next1 = input("> ")
27 
28         if next1 == "take honey":
29             print("The bear looks at you then slaps your face off.")
30         elif next1 == "taunt bear" and not bear_moved:
31             print("The bear has moved from the door.You can go through it now.")
32             bear_moved=True
33         elif next1 == "taunt bear" and bear_moved:
34             print("The bear gets pissed off and chews your leg off.")
35         elif next1 == "open the door" and bear_moved:
36             gold_room()
37         else:
38             print("I got no idea what that means.")
39 
40 def cthulhu_room():
41     print("Here you see the great evil Cthulhu.")
42     print("He, it, whatever stares at you and you go insane.")
43     print("Do you flee for your life or eat your head.")
44 
45     next1=input("> ")
46 
47     if "flee" in next1:
48         start()
49     elif"head"in next1:
50         print("Well that was tasty!")
51     else:
52         cthulhu_room()
53 
54 def start():
55     print("You are in a dark room.")
56     print("There is a door to your right and left.")
57     print("Which one do you take?")
58 
59     next1=input("> ")
60 
61     if next1 == "left":
62         bear_room()
63     elif next1 =="right":
64         cthulhu_room()
65     else:
66         print("You stumble around the room until you strave.")
67 
68 start()

結果

You are in a dark room.
There is a door to your right and left.
Which one do you take?
> left
There is a bear here.
The bear has a bunch of honey.
The fat bear is in front of another door.
How are you going to move the bear?
> taunt bear
The bear has moved from the door.You can go through it now.
> open the door
This room is full of gold. How much do you take?
Man, learn to type a number.

> 0
Nice, youre not greedy, you win!

python3 _笨方法學Python_日記_DAY5