您的位置:首页 > 编程语言 > Python开发

第三讲 基本输入输出语句

2015-03-15 21:12 281 查看
一、输出语句print函数
print()函数基本使用
打印整形、浮点型、字符型、字符串型数据
eg1:
>>> print(12) 整形
12
>>> print(12.5) 浮点型
12.5
>>> print('H') 字符型
H
>>> print('www.baidu.com') 字符串型
www.baidu.com
>>> x=12
>>> print (x) 打印变量指向的值
12
>>> y=12.58
>>> print (y)
12.58
>>> s='www.baidu.com'
>>> print (s)
www.baidu.com
>>> print x,y,z 一次输出多个值,占用一行
12 12.58 25
>>> print (x,y,z)-----------了解即可
(12, 12.58, 25)
备注:
1,以上这些括号都可以省略不写

print() 格式化输出
print(format(value,format_modifier))-------format为关键字,不可以省略
value:值(原始的)
format_modifier:格式字符
c语言中显示格式化字符 + value值
eg1:
>>> print (format(12.345,'6.3f')) 输出小数点后3位
12.345
'm.nf' m:输出占位数 n:小数点后的精度

>>> print (format(12.345678,'6.2f')) 输出小数点后2位
12.35 ------四舍五入的结果-------截取指定的小数位,多余的位数会进行四舍五入

>>> print (format(12.34567,'6.3f')) 输出小数点后3位
12.346
'm.nf'
m:输出占的位数
n:小数点后有多少位
如果n大于数据小数点的位数时----补0占位
eg:
>>> print (format(12.34567,'6.9f'))
12.345670000
如果不想输出小数点后的位数,令n=0
eg:
>>> print (format(12.34567,'6.0f'))
____12 ----前面占用了4个空格( _ 代表一个空格)
当m大于输出有效字符的个数是,会右对齐,左补空位
eg:
>>> print (format(12.34567,'9.2f'))
____12.35 ----前面占用了4个空格( _ 代表一个空格)
当m小于输出有效字符的个数是,会左对齐,忽略m
eg:
>>> print (format(12.34567,'3.2f'))
12.35

百分号格式化输出
>>> print (format(0.3456,'.2%'))------输出小数点后2位
34.56%
>> print (format(0.3456,'3.1%'))
34.6%------------占5个打印位,5>3(当m小于输出有效字符的个数是,会左对齐)所以忽略了m
>>> print (format(0.3456,'6.1%'))
_34.6%-----------5<6,右对齐,左补空位(当m大于输出有效字符的个数是,会右对齐,左补空位)
####输出的时候,优先看n,满足n后再满足m

二、输入语句
re=raw_input(prompt)
-prompt:提示字符(可忽略)
-re:为返回值(字符串型),无论输入什么,读取的都是字符串string型的
查帮助方法
>> help(raw_input)
eg1:
>>> str1=raw_input()
www.baidu.com
>>> print str1
www.baidu.com
>>> type(str1)
<type 'str'>
>>>
>>>
>>> age=raw_input("plz input your age:")
plz input your age:26
>>> type(age)
<type 'str'>
>>> age=age+1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects--因为age是str而不是整形
>>> age=int(age)------------int函数将字符串转化成整形
>>> age
26
>>> age=age+1
>>> age
27

eg2:
>>> age=raw_input('plz input your age:')
plz input your age:26
>>> print age
26
>>> type(age)
<type 'str'>

eg3:
>>> f1=float('12.35')
>>> type(f1)
<type 'float'>
>>> weight=float(raw_input('plz input your weight:'))
plz input your weight:65.6
>>> print weight
65.6
>>> type(weight)
<type 'float'>

print x
print y---------两行输出

print x,y -------一行输出

print x,
print y----------一行输出
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  学习 python