为什么要设置变量?用书中一段话来解释最为恰当
在编程中,变量只不过是用来指代某个东西的名字,程序员通过使用变量名可以让他们的程序读起来更像英文,而且因为程序员的记性都 不怎么,变量名可以让他们更容易记住程序的内容,如果他们在写程序时没有使用好的变量名,在下次读到原来写的代码时他们会大为头疼
举个例子,变量my_name你一看就知道这个变量的含义及大概的用途,所以说用一个恰当的变量名对整个程序的可读性有很大的作用。
格式化字符串(format string),这个会在我们以后的程序中经常用到,字符串是我们与机器沟通的主要方式,不像数字,字符串更加易读,这就和ex4中的变量结合起来了,比如这样一个字符串"my age is %d" % my_age ,在这个字符串中,所谓的格式,我是这样理解的,就是我想把某个变量放到字符串的某个位置上,就是%d,但我只在要引号外面把变量引用起来就好,如my_age,按照%d格式输出,这样做方便我在其他位置来更改my_age 的值,常用的字符串格式可以看下面截图:
![](https://img.haomeiwen.com/i1155167/7f019d41651466d5.png)
![](https://img.haomeiwen.com/i1155167/8168da5c296a6ebf.png)
![](https://img.haomeiwen.com/i1155167/732056eb9a7d5c18.png)
把ex5的代码贴到下面:
my_name = 'Zed A. Shaw'
my_age = 35
my_height = 74
my_weight = 180
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print "Let's talk about %s" % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes,my_hair)
print "His teeth are usually %s depending on the cooffee." % my_teeth
print "If I add %d, %d, and %d I get %d" % (my_age, my_height, my_weight, my_age + my_height + my_weight)
print "%3s" % 16
这里有个小问题,就是没弄明的%s与%r的区别,不急以后再说
网友评论