测试题
1. 使用 def
关键字来创建一个函数。
2. 调用函数时要使用函数名和一对小括号。
3. 调用函数时把参数放在小括号里,就可以向这个函数传入参数。
4. 一个函数可以有任意多个参数,对此没有任何限制。
5. 函数使用 return
关键字向调用者发回信息。
6. 函数完成运行后,所有局部变量都会撤销。
动手试一试
1. 这个函数只需要一组 print
语句:
def printMyNameBig: print " CCCC A RRRRR TTTTTTT EEEEEE RRRRR " print " C C A A R R T E R R " print "C A A R R T EEEE R R " print "C AAAAAAA RRRRR T E RRRRR " print " C C A A R R T E R R " print " CCCC A A R R T EEEEEE R R"
调用这个函数的程序如下所示:
for i in range(5): printMyNameBig
2. 下面给出我的做法,这里利用 7 个参数打印地址:
# define a function with seven argumentsdef printAddr(name, num, street, city, prov, pcode, country): print name print num, print street print city, if prov !="":print ", "+prov else:print "" print pcode print country print#call the function and pass seven arguments to itprintAddr("Sam", "45", "Main St.", "Ottawa", "ON", "K2M 2E9", "Canada")printAddr("Jian", "64", "2nd Ave.", "Hong Kong", "", "235643", "China")
3. 没有具体答案,可以动手试一试。
4. 合计零钱的函数应当如下所示:
def addUpChange(quarters, dimes, nickels, pennies): total = 0.25 * quarters + 0.10 * dimes + 0.05 * nickels + 0.01 *pennies return total
调用它的程序可能如下所示:
quarters = int(raw_input("quarters: "))dimes = int(raw_input("dimes: "))nickels = int(raw_input("nickels: "))pennies = int(raw_input("pennies: "))total = addUpChange(quarters, dimes, nickels, pennies)print "You have a total of: ", total