1. 程式人生 > >《笨辦法學python》加分習題5——我的答案

《笨辦法學python》加分習題5——我的答案

新人自娛自樂,歡迎大家批評指正,在此不勝感激!

先貼上章節所打的程式碼:

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。