笨办法学Python(十九)

习题 19: 函数和变量

    函数这个概念也许承载了太多的信息量,不过别担心。只要坚持做这些练习,对照上个练习中的检查点检查一遍这次的联系,你最终会明白这些内容的。

    有一个你可能没有注意到的细节,我们现在强调一下:函数里边的变量和脚本里边的变量之间是没有连接的。下面的这个练习可以让你对这一点有更多的思考:

 1 def cheese_and_crackers(cheese_count, boxes_of_crackers):
 2     print "You have %d cheeses!" % cheese_count
 3     print "You have %d boxes of crackers!" % boxes_of_crackers
 4     print "Man that's enough for a party!"
 5     print "Get a blanket.
"
 6 
 7 
 8 print "We can just give the function numbers directly:"
 9 cheese_and_crackers(20, 30)
10 
11 
12 print "OR, we can use variables from our script:"
13 amount_of_cheese = 10
14 amount_of_crackers = 50
15 
16 cheese_and_crackers(amount_of_cheese, amount_of_crackers)
17 
18 
19 print "We can even do math inside too:"
20 cheese_and_crackers(10 + 20, 5 + 6)
21 
22 
23 print "And we can combine the two, variables and math:"
24 cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
View Code

    通过这个练习,你看到我们给我们的函数 cheese_and_crackers 很多的参数,然后在函数里把它们打印出来。我们可以在函数里用变量名,我们可以在函数里做运算,我们甚至可以将变量和运算结合起来。

    从一方面来说,函数的参数和我们的生成变量时用的 = 赋值符类似。事实上,如果一个物件你可以用 = 将其命名,你通常也可以将其作为参数传递给一个函数。

你应该看到的结果

    你应该研究一下脚本的输出,和你想象的结果对比一下看有什么不同。

加分习题

  1. 倒着将脚本读完,在每一行上面添加一行注解,说明这行的作用。
  2. 从最后一行开始,倒着阅读每一行,读出所有的重要字符来。
  3. 自己编至少一个函数出来,然后用10种方法运行这个函数。

习题练习

1.

 1 def cheese_and_crackers(cheese_count, boxes_of_crackers):   #定义含两个形参的 cheese_and_crackers 函数
 2     print "You have %d cheeses!" % cheese_count   #缩进部分为函数主体部分
 3     print "You have %d boxes of crackers!" % boxes_of_crackers
 4     print "Man that's enough for a party!"
 5     print "Get a blanket.
"
 6 
 7 
 8 print "We can just give the function numbers directly:"
 9 cheese_and_crackers(20, 30)   #调用 cheese_and_crackers 函数,直接用数值作为实参
10 
11 
12 print "OR, we can use variables from our script:"
13 amount_of_cheese = 10   #将数值赋予变量
14 amount_of_crackers = 50
15 
16 cheese_and_crackers(amount_of_cheese, amount_of_crackers) #调用函数,变量作为函数实参
17 
18 
19 print "We can even do math inside too:"
20 cheese_and_crackers(10 + 20, 5 + 6)  #表达式作为函数实参,python优先计算表达式的值
21 
22 
23 print "And we can combine the two, variables and math:"
24 cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) #变量和表达式混合作为实参

2.

    函数调用时赋给实参的四种方式: 
  1.直接将数值作为函数实参。 
  2.数值赋值给变量,再让变量作为函数实参。 
  3.在调用函数时用表达式做函数实参。 
  4.变量和表达式的混合模式做函数实参。

    请仔细阅读常见问题回答,其中涉及的全局变量在这里不适合介绍,以后遇到实例再讲。 
    请注意,作者也提到,在你使用raw_input时要使用,int做类型转换,因为,raw_input函数处理的结果是字符而不是一个数值,字符和数值在计算机中的存储方式是不同的,参见ASⅡ码表。

原文地址:https://www.cnblogs.com/yllinux/p/7401702.html