《笨办法学python》加分习题5——我的答案

时间:2021-07-05 14:38:08

新人自娱自乐,欢迎大家批评指正,在此不胜感激!

先贴上章节所打的代码:

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
print "If I add %d,%d,and%d I get %d."%(my_age,my_height,my_weight,my_age+my_height+my_weight)

正文:

1、我用的是PyCharm,所以我用了replace

name = 'Zed A. shaw'
age = 35 # not a lie
height = 74 # inches
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'

print "Let's talk about %s." % name
print "He's %d inches tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair."%( eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
print "If I add %d,%d,and%d I get %d."%( age, height, weight, age+ height+ weight)

2、这里先说明下%s 是string类型,%d是digital,这是我的理解,如有错误,欢迎批评指正!

print "Print string and digital:%r,%r" % (name,age)


3、摘抄于:http://www.cnblogs.com/vamei/archive/2013/03/12/2954938.html 非常感谢作者的无私奉献!

%s     字符串(采用str()的显示)

%r  字符串(采用repr()的显示)

%c 单个字符

%b 二进制整数

%d 十进制整数

%i 十进制整数

%o 八进制整数

%x 十六进制整数

%e 指数(基底写为e)

%E 指数(基地写为E)

%f 浮点数

%F 同上

%g 指数(e)或者浮点数(根据显示长度)

%G 指数(E)或者浮点数(根据显示长度)

%% 字符“%”


4、

height = 74 # inches
weight = 180 # lbs
cm = 0.254
kg = 0.454

height_cm = cm*height
weight_kg = kg*weight
print "He's %r inches tall." % height_cm
print "He's %r pounds heavy." % weight_kg

这里在写的过程中,直接在print后相乘赋值,出现  TypeError: can't multiply sequence by non-int of type 'float 的报错,看字面意思是不支持float的类型。我想应该是python不支持 print内出现类型转换吧(猜测),于是就有了上面的代码,现在外部转换后再进行print。