笨辦法學python第六天,python第六天
練習21
# --coding:utf-8--def add(a,b): print "ADDING %d + %d" %(a,b) return a+bdef substract(a,b): print "SUBTRACTING %d - %d" %(a,b) return a - bdef multiply(a,b): print "MULTIPLYING %d * %d" %(a,b) return a * bdef divide(a,b): print "DIVIDING %d / %d" %(a,b) return a/bprint "Let's do some math with just functions!"age = add(30,5)height = substract(78,4)weight = multiply(90,2)iq = divide(100,2)print "Age:%d,Height:%d,Weight:%d,IQ:%d" %(age,height,weight,iq)# A puzzle for the extra credit,type it in anyway.print "Here is a puzzle."what = add(age,substract(height,multiply(weight,divide(iq,2))))print "That becomes:",what,"Can you do it by hand?"
練習24
# --coding:utf-8--print "Let's practice everything." #普通的列印print 'You\'d need to know \'bout escapes with \\ that do \nnewlines and \t tabs.' #使用逸出字元\的列印poem = """\tThe lovely worldwith logic so firmly plantedcannot discern \ the needs of lovenor comprehend passion from intuitionand requires an explanation\n\t\twhere there is none.""" #使用三引號進行文本處理print "------------------------"print poem #列印變數print "------------------------"five = 10 - 2 + 3 - 6print "This should be five:%s" %five #列印運算式def secret_formula(stared): #定義一個函數,進行計算和列印操作 jelly_beans = stared * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans,jars,cratesstart_point = 10000beans,jars,crates = secret_formula(start_point)print "With a starting point of : %d" % start_pointprint "We'd have %d beans,%d jars,and %d crates." %(beans,jars,crates)start_point /= 10print "We can also do that this way:"print "We'd have %d beans,%d jars,and %d crates." %secret_formula(start_point)
練習25
def break_words(stuff): words = stuff.split(' ') return wordsdef sort_words(words): return sorted(words)def print_first_word(words): word = words.pop(0) print worddef print_last_word(words): word = words.pop(-1) print worddef sort_sentence(sentence): words = break_words(sentence) return sort_words(words)def print_first_and_last(sentence): words = break_words(sentence) print_first_word(words) print_last_word(words)def print_first_and_last_sorted(sentence): words = sort_sentence(sentence) print_first_word(words) print_last_word(words)
查看評論