Exercise 24:更多的練習

原文鏈接: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 來接收這個函數的返回值。

你說的從後往前閱讀代碼是什麼意思?
答:從代碼的最後一行開始。將你代碼文件的某一行與我文件代碼中的同一行進行比較。一旦確認和我的完全相同,就向上移一行繼續比較,這樣一直比較到文件的第一行爲止。

誰寫的這首詩?
答:我寫的。我寫的詩不是都是這麼糟糕的。

發佈了23 篇原創文章 · 獲贊 7 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章