python3 _笨方法学Python_日记_DAY5

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, you‘re not greedy, you win!

原文地址:https://www.cnblogs.com/mrfri/p/8452927.html

时间: 2024-08-05 04:07:55

python3 _笨方法学Python_日记_DAY5的相关文章

python3 _笨方法学Python_日记_DAY4

Day4 习题  19:  函数和变量 1 def cheese_and_crackers(cheese_count, boxes_of_crackers): 2 print("You have %d cheeses!" % cheese_count) 3 print("You have %d boxes of crackers!" % boxes_of_crackers) 4 print("Man that's enough for a party!&q

python3 _笨方法学Python_日记_DAY6

Day6 习题  36:  设计和调试 If 语句的规则1. 每一个"if 语句"必须包含一个 else.2. 如果这个 else 永远都不应该被执行到,因为它本身没有任何意义,那你必须在else 语句后面使用一个叫做 die 的函数,让它打印出错误信息并且死给你看,这和上一节的习题类似,这样你可以找到很多的错误.3. "if 语句"的嵌套不要超过 2 层,最好尽量保持只有 1 层. 这意味着如果你在 if 里边又有了一个 if,那你就需要把第二个 if 移到另一个

python3 _笨方法学Python_日记_DAY7

习题 40: 字典, 可爱的字典 回顾一下列表: 列表可以通过数字,从0开始的数字来索引列表中的元素 而字典dict,可以通过任何东西找到元素,可以将一个东西和另一个相关联 还可以通过字符串向字典中添加 stuff = {'name': 'Zed', 'age': 18, 'height': 6**6} stuff['city'] = 'San Francisco' print(stuff['city']) stuff[1] = 'Wow' stuff[2] = 'Neato' print(st

笨方法学python3

阅读<笨方法学python3>,归纳的知识点 习题1:安装环境+练习  print函数使用  主要区别双引号和单引号的区别 习题2:注释符号# 习题3:运算符优先级,跟C/C++, Java类似 以下运算符优先级:从下往下以此递增,同行为相同优先级 Lambda #运算优先级最低 逻辑运算符: or 逻辑运算符: and 逻辑运算符:not 成员测试: in, not in 同一性测试: is, is not 比较: <,<=,>,>=,!=,== 按位或: | 按位异

Day 2 笨方法学Python

手打第25个练习,出错的地方有: def 定义后indent 4个空格,第一行空了以后,直接换行是跟上面对其的,但是运行时是错误的,我的解决方法是,重新手动空格4个: 还发现一个问题就是,中文解释,以前老是出错 # -*- coding : utf-8 -*- 网上看到的加上这个就可以了,但是我的还是出错.今天偶然在削微寒的博客http://www.cnblogs.com/xueweihan/的GIthub上找到了答案 #coding:utf-8 换成这个语句就可以了.以后,尽量每句都加上注释,

笨方法学python(5)加分题

这篇对应的是习题17,更多文件操作 # -*- coding: utf-8 -*- #对文件更多操作复制A文件的内容到B文件 #from sys import argv from os.path import exists prompt = "> " from_file = raw_input("please input the filename where you want to copy from: >") #in_file = open(from_

笨方法学python(6)加分题--列表与字典的区别

he string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIG

笨方法学python(4)加分题

自己在看笨方法学python这本书,把自己觉得有学到东西的记下来,并不是每个习题都有记录 这次对应的是:习题 6: 字符串(string)和文本 这次只要是想说明一下,在print语句中,只要带有格式化字符的,会当作格式化来处理 脚本1: 结果1: 打出的结果没有%r,那是因为当作格式化处理了 脚本2: 结果2: 会报错,因为print joke_evaluation %hilarious 是格式化的标识 脚本3: 结果3:

笨方法学Python3(21-44)

接着前天的总结 习题21:函数可以返回某些东西 定义函数的加减乘除,以及嵌套使用 习题22:回顾以前学的知识 习题23:字符串.字节串和字符编码 综合运用字符串.函数.文件读取等知识.详情如下: from sys import argv script, encoding, error = argv # 命令行参数处理 def main(language_file, encoding,errors): line = language_file.readline() # 就是用readline()处