一:代码
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 #inches
my_weight = 180 # lbs
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 coffee." % my_teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (
my_age, my_height, my_weight, my_age + my_height + my_weight)
二:附加练习
1:修改所有的变量名,把前面的my_去掉。
2:试着使用更多的格式化字符。
例如:%r 含义:不管什么都打印出来。
3:在网上搜索Python格式化字符。
4:试着使用变量将英寸和磅转换成厘米和千克。
1寸 = 2.54cm
1b = 0.453592kg
错误1:
TypeError: can't multiply sequence by non-int of type 'float'
错误2:TypeError: not enough arguments for format string
解决办法:% S, SS系统误认为只有一个参数,添加括号即可:%(S,SS)
问题2解决,问题3-4出现。
注:
1:raw_input()
接受用户输入的时候使用raw_input()
详见习题11。
2:round()函数
可以将浮点数四舍五入。