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 explanation10 \n\twhere there is none.11 """12 13 print("-------------")14 print(poem)15 print("-------------")16 17 five = 10 - 2 + 3 - 618 print("This should be five: %s" % five)19 20 def secret_formula(started):21 jelly_beans = started * 50022 jars = jelly_beans / 100023 crates = jars / 10024 return jelly_beans, jars, crates25 26 start_point = 1000027 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 / 1033 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 plantedcannot discern the needs of lovenor comprehend passion from intuitionand requires an explanationwhere there is none.
-------------
This should be five: 5With a starting point of: 10000We'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_words10 ['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']11 >>> day525.print_first_word(words)12 All13 >>> day525.print_last_word(words)14 wait.15 >>> wrods16 Traceback (most recent call last):17 File "", line 1, in 18 wrods19 NameError: name 'wrods' is not defined20 >>> words21 ['good', 'things', 'come', 'to', 'those', 'who']22 >>> day525.print_first_word(sorted_words)23 All24 >>> day525.print_last_word(sorted_words)25 who26 >>> sorted_words27 ['come', 'good', 'things', 'those', 'to', 'wait.']28 >>> sorted_words = day525.sort_sentence(sentence)29 >>> sorted_Words30 Traceback (most recent call last):31 File " ", line 1, in 32 sorted_Words33 NameError: name 'sorted_Words' is not defined34 >>> sorted_words35 ['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']36 >>> day525.print_first_and_last(sentence)37 All38 wait.39 >>> day525.print_first_and_last_sorted(sentence)40 All41 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']Allwait.['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 == 111 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 +=515 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?
> 1There's a giant bear here eating a cheese cake. What do you do?1. Take the cake.2. Scream at the bear.> 3Well, 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 above10 for fruit in fruits:11 print("A fruit of type: %s" % fruit)12 13 #also we can go through mixed lists too14 #notice we have to use %r since we don't know what's in it15 for i in change:16 print("I got %r" % i)17 18 #we can also build lists, first start with an empty one19 elements = []20 21 #then use the range function to do 0 to 5 counts22 for i in range(0,6):23 print("Adding %d to the list." % i)24 #append is a function tha lists understand25 elements.append(i)26 27 #now we can print them out too28 for i in elements:29 print("Element was: %d" % i)
结果
This is count 1
This is count 2This is count 3This is count 4This is count 5A fruit of type: applesA fruit of type: orangesA fruit of type: pearsA fruit of type: apricotsI got 1I got 'pennies'I got 2I got 'dimes'I got 3I 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: 0Element was: 1Element was: 2Element was: 3Element was: 4Element was: 5python3 注意:
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 0Numbers now: [0]At the bottom i is 1At the top i is 1Numbers now: [0, 1]At the bottom i is 2At the top i is 2Numbers now: [0, 1, 2]At the bottom i is 3At the top i is 3Numbers now: [0, 1, 2, 3]At the bottom i is 4At the top i is 4Numbers now: [0, 1, 2, 3, 4]At the bottom i is 5At the top i is 5Numbers now: [0, 1, 2, 3, 4, 5]At the bottom i is 6The numbers:012345
加分题:
先定义
1 def kl(b):2 """创建一个从零到 b-1 的列表 间隔为 1 """3 i = 04 numbers = list()5 6 while i < b:7 numbers.append(i)8 i += 19 return numbers
执行:
1 import sys2 sys.path.append("E:\py\learnpythonthehardway\Day5")3 import d533extra4 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)
-
习题 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 dead215 else:16 dead17 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 = False24 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=True33 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?> leftThere 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 bearThe bear has moved from the door.You can go through it now.> open the doorThis room is full of gold. How much do you take?Man, learn to type a number.> 0Nice, you're not greedy, you win!