笨办法学Python - 习题5: More Variables and Printing

 

1、习题 5: 更多的变量和打印

学习目标:了解用户输入方法,明白pthon2和Python3之间的用户输入的区别。了解格式化字符串(format string)的概念,学会如何创建包含变量内容的字符串。使用专门的格式和语法把变量的内容放到字符串里,然后进行格式化的打印输出。

1.1、用户输入

在Python3中通常使用的input() 函数直接和用户进行交互,用于等待用户的输入。

在Python2中通常使用raw_input() 函数来和用户进行交互,基本上raw_input() = input() (python3中),python2中的input() 函数基本上不用,因为在Python2中input() 函数会检查用户输入的是字符还是变量,举个栗子:如果之前定义了name的值,那么name为变量,则当我们输入name的时候,会返回变量name的值,如果之前没有定义name的值则会直接报错。

1547562594689

1547562682169

所以:对于用户输入,在Python2 中使用raw_input() ,在Python3中使用 input() 即可

1.2、格式化输出

python格式化输出有两种方式:百分号和format
format的功能要比百分号方式强大,其中format独有的可以自定义字符填充空白、字符串居中显示、转换二进制、整数自动分割、百分比显示 等功能是百分号方式不能相比的

习题五中的练习代码是:

#! -*-coding=utf-8 -*-  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 teech 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)

上述代码的运行结果为:

C:\Python27\python.exe D:/pythoncode/stupid_way_study/demo5/Exer5-1.py Let,s talk about Zed A. shaw. He
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信