# --coding:utf-8--
def add(a,b):
print "ADDING %d + %d" %(a,b)
return a+b
def substract(a,b):
print "SUBTRACTING %d - %d" %(a,b)
return a - b
def multiply(a,b):
print "MULTIPLYING %d * %d" %(a,b)
return a * b
def divide(a,b):
print "DIVIDING %d / %d" %(a,b)
return a/b
print "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 world
with logic so firmly planted
cannot discern \ 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(stared): #定义一个函数,进行计算和打印操作
jelly_beans = stared * 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 /= 10
print "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 words
def sort_words(words):
return sorted(words)
def print_first_word(words):
word = words.pop(0)
print word
def print_last_word(words):
word = words.pop(-1)
print word
def 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)