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

第3课 Python基本输入输出语句

2017-01-07 13:46 441 查看
1.Python输出语句print函数

Print()函数的基本使用

打印整形数据

打印浮点型数据

打印字符串数据

例如一下代码

>>> print(12)

12

>>> print(12.5)

12.5

>>> print('H')

H

>>> print('www.xiongpanjava.com')

www.xiongpanjava.com

>>> x=12

>>> print(x)

12

>>> y=12.58

>>> print(y)

12.58

>>> z='www.xiongpanjava.com'

>>> print(z)

www.xiongpanjava.com

其中print()中括号可以省略,例如

>>> print z

www.xiongpanjava.com

一次输出两个值或多个值

>>> print x,y,z

12 12.58 www.xiongpanjava.com

>>> print(x,y,z)

(12, 12.58, 'www.xiongpanjava.com')

2.print格式化输出

print(format(val,format_modifier))
var :值
format_modifier格式字

print(format(12.34567,'m.nf'))

其中m代表输出占位,n代表小数点后面的精度

>>> print(format(12.34567,'6.2f'))

 12.35

>>> print(format(12.34567,'6.3f'))

12.346

小数点后面的精度大于该数的位数后面用0补齐

>>> print(format(12.34567,'6.9f'))

12.345670000

不想输出小数,用0代替

>>> print(format(12.34567,'6.0f'))

12

>>> print(format(12.3456,'9.2f'))

12.35

如果占位小于输出有效输出位数,会左对齐并保留数据的有效输出

>>> print(format(12.34567,'3.2f'))

12.35

统计百分率

print(format(val,format_modifier))

>>> print(format(0.3456,'.2%'))

34.56%

>>> print(format(0.3456,'3.1%'))

34.6%

Python输入函数

re=raw_input(prompt)
prompt:提示字符
re为返回值

>>> help(raw_input)

Help on built-in function raw_input in module __builtin__:

raw_input(...)

    raw_input([prompt]) -> string

    

    Read a string from standard input.  The trailing newline is stripped.

    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.

    On Unix, GNU readline is used if enabled.  The prompt string, if given,

is printed without a trailing newline before reading.

>>> str1=raw_input()

www.xiongpanjava.com     用户随便输入的字符串

>>> print str1 

www.xiongpanjava.com

>>> type(str1)         通过type查看输入的类型

<type 'str'>

>>> age=raw_input('your age:')

your age:27

>>> type(age)

<type 'str'>

>>> age=age+1

Traceback (most recent call last):

  File "<pyshell#34>", line 1, in <module>

    age=age+1

TypeError: cannot concatenate 'str' and 'int' objects

>>> age=int(age)   可以直接通过数据类型(变量)进行强转

>>> age=age+1

>>> print age

28

直接输入整型数据

>>> age=int(raw_input('please tell me your age'))

please tell me your age 26

>>> type age

>>> type(age)

<type 'int'>

例如将字符串强制转换成浮点型数据

>>> fl=float('12.35')

>>> type(fl)

<type 'float'>

>>> print fl

12.35

>>> weight=float(raw_input('please input your weight:'))

please input your weight: 65

>>> type(weight)

<type 'float'>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python print raw_input