原文链接:http://learnpythonthehardway.org/book/ex24.html
这一部分很快就要告一段落了。你在转向开始学习如何编写正真有用的程序之前你应该在你“指下”积累了足够的Python代码,所有你应该做更多的练习。这次的练习比较长你需要足够的耐心去学习它。下一次的练习将和这次的类似。做完它们,做到完全正确,仔细做好检查。
print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlies and \t tabs.'
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \r the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print "----------------"
print poem
print "----------------"
five = 10 - 2 + 3 - 6
print "This should be five: %s" % five
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans ,jars ,crates
start_point = 10000
beans ,jars ,crates = secret_formula(start_point)
print "With a starting point of: %d" % start_point
print "We'd have %d beans ,%d jars ,and %d crates." % (beans ,jars ,crates)
start_point = start_point / 10
print "We can also do that this way:"
print "We'd have %d beans ,%d jars ,and %d crates." % secret_formula(start_point)
输出结果如下:
c:\>python ex24.py
Let's practice everything.
You'd need to know 'bout escapes with \ that do
newlies and tabs.
----------------
The lovely world
with logic so firmly planted
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.
研究训练:
1、做好代码检查:从后往前阅览对照,将代码大声的读出来,在迷惑的地方做好注释。
2、故意把代码改错,然后运行看看你得到了什么样的错误。确保你可以自己解决这个错误。
学生遇见的常见问题:
你怎么调用到 jelly_beans 变量的值之后又将该值传给了 beans 变量?
答:这部分体现的就是一个函数的功能。记住你传入函数的变量是一个临时变量,并且当函数返回得到值时可以将这些值之后再赋给一个变量。我在这里只是新建了一个变量 beans 来接收这个函数的返回值。
你说的从后往前阅读代码是什么意思?
答:从代码的最后一行开始。将你代码文件的某一行与我文件代码中的同一行进行比较。一旦确认和我的完全相同,就向上移一行继续比较,这样一直比较到文件的第一行为止。
谁写的这首诗?
答:我写的。我写的诗不是都是这么糟糕的。