Learn Python The Hard Way学习(5) - 更多的变量和打印


现在我们输入更多的变量并打印他们,通常我们用""引住的叫字符串。

字符串是相当方便的,在练习中我们将学习怎么创建包含变量的字符串。有专门的方法将变量插入到字符串中,相当于告诉Python:“嘿,这是一个格式化字符串,把变量放进来吧。”

输入下面的程序:

1. # -- coding: utf-8 -- 
2. my_name = 'Zed A. Shaw' 
3. my_age = 35 # 没撒谎哦 
4. my_height = 74 # 英寸 
5. my_weight = 180 # 磅 
6. my_eyes = 'Blue' 
7. my_teeth = 'White' 
8. my_hair = 'Brown' 
9.  
10.  
11. print "let's talk about %s." % my_name 
12. print "He's %d inches tall." % my_height 
13. print "He's %d pounds heavy." % my_weight 
14. print "Actually that's not too heavy." 
15. print "He's got %s eyes and %s hair." % (my_eyes, my_hair) 
16. print "His teeth are usually %s depending on the coffee." % my_teeth 
17.  
18.  
19. # 下面这行比较复杂,尝试写对它。 
20. print "If I add %d, %d, and %d I get %d." % ( 
21.     my_age, my_height, my_weight, my_age + my_height + my_weight) 

提示:如果有编码问题,记得输入第一句。

运行结果:
root@he-desktop:~/mystuff# python ex5.py
let's talk about Zed A. Shaw.
He's 74 inches tall.
He's 180 pounds heavy.
Actually that's not too heavy.
He's got Blue eyes and Brown hair.
His teeth are usually White depending on the coffee.
If I add 35, 74, and 180 I get 289.
root@he-desktop:~/mystuff#

加分练习:
1. 把所有变量名前面的my_去掉。

2. 试试其他格式符,%r是很有用的一个,就像是说:”什么都可以打印“。

3. 搜索所有的python格式符。
%d 格式化整数
%i 格式化整数
%u 格式化无符号整数(废弃,不赞成使用)
%o 格式化无符号八进制数
%X 格式化无符号十六进制数(小写字母)
%X 格式化无符号十六进制数(大写字母)
%e 用科学计数法格式化浮点数
%E 作用和%e一样
%f 格式化浮点数,可以指定小数点后的精度,默认显示6位小数,例如%.2f显示2位小数。
%F 和%f一样
%g 根据值的大小决定使用%f还是%e
%G 和%g一样
%c 格式化字符及ASCII码;
%s 格式化字符串 www.2cto.com
%r 大字符串

4. 用数学计算把英寸和磅转化为厘米和千克。
1英寸 = 2.54厘米,1磅 = 0.4536千克
1. my_height_centimeter = my_height * 2.54 
2. my_weight_kilo = my_weight * 0.4536 
3. print "He's %d centimeters tall." % my_height_centimeter 
4. print "He's %d kilos heavy." % my_weight_kilo 
 

 作者:lixiang0522

相关内容

    暂无相关文章

评论关闭