笨辦法學Python)(二十四)
阿新 • • 發佈:2017-08-26
love pla ide nor simple open start close sce
習題 24: 更多練習
你離這本書第一部分的結尾已經不遠了,你應該已經具備了足夠的 Python 基礎知識,可以繼續學習一些編程的原理了,但你應該做更多的練習。這個練習的內容比較長,它的目的是鍛煉你的毅力,下一個習題也差不多是這樣的,好好完成它們,做到完全正確,記得仔細檢查。
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 worldView Code6 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\t\twhere there is none. 11 """ 12 13 print "--------------" 14 print poem 15 print "--------------" 16 17 18 five = 10 - 2 + 3 - 6 19 print "This should be five: %s" % five 20 21 def secret_formula(started): 22 jelly_beans = started * 500 23 jars = jelly_beans / 1000 24 crates = jars / 100 25 return jelly_beans, jars, crates 26 27 28 start_point = 10000 29 beans, jars, crates = secret_formula(start_point) 30 31 print "With a starting point of: %d" % start_point32 print "We‘d have %d beans, %d jars, and %d crates." % (beans, jars, crates) 33 34 start_point = start_point / 10 35 36 print "We can also do that this way:" 37 print "We‘d have %d beans, %d jars, and %d crates." % secret_formula(start_point)
你應該看到的結果
加分習題
- 記得仔細檢查結果,從後往前倒著檢查,把代碼朗讀出來,在不清楚的位置加上註釋。
- 故意把代碼改錯,運行並檢查會發生什麽樣的錯誤,並且確認你有能力改正這些錯誤。
習題練習
1.
請留意最後一行,出現了新的用法,那就是不經過變量,直接以 %+函數 的形式格式化輸出函數的結果,請記住這種用法,可以簡化你的代碼。
2.
函數內部變量的作用於僅僅是函數內,對函數外或者其他函數內部則沒有影響,因此可以有相同的變量名。請根據實際情況取舍,有時候相同的變量名會更簡便,有時候則會引起混淆。
笨辦法學Python)(二十四)