Python输入输出

101 阅读2分钟

输入输出

输出

直接输出字符串和数值类型

 >>> print(1)
 1
 >>> print('hello world')
 hello world
 #无论什么类型,数值,布尔,列表,字典..这些变量都可以直接输出

格式化输出,类似于c语言的 print 

 >>> s= 'hello'
 >>> x = len(s)
 >>> print( 'the length of %s is %d' % ( s, x ) )
 The length of Hello is 5

转义输出类型

转义类型解释
d,i十进制
o八进制
u十进制
x十六进制(小写)
X十六进制(小写)
e科学计数法浮点数(小写)
E科学计数法浮点数(大写)
f,F十进制浮点数
C接收整数(会转换为对应ascii码字符)、 单字符)
s字符串
 >>> print('%d  %i' % (20,-10)) #d,i
 20  -10
 >>> print('%o'%-10) #o
 -12
 >>> print('%u' % 20) #u
 20
 >>> print('%x'%12) #x
 c
 >>> print('%e'%2.56) #e
 2.560000e+00
 >>> print('%f'%2.56) #f
 2.560000
 >>> print('%c'% 65) #C
 A
 >>> print('%s'% 'abc') #s
 abc

输入

  • Python2: raw_input() 、 input() 

    •  input 会默认用户输入的是合法的Python表达式
    •  raw_input 会把所有的输入当做字符串进行处理
 #python2.x raw_input
 >>> var = raw_input('pls type a num you want:')
 pls type a num you want:20
 >>> var
 '20'
 >>> var = raw_input('pls type a num you want:')
 pls type a num you want:abc
 >>> var
 'abc'

 #python2.x input
 >>> var = input('pls type a num you want:')
 pls type a num you want:20
 >>> var
 20
 >>> var = input('pls type a num you want:')
 pls type a num you want:abc
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<string>", line 1, in <module>
 NameError: name 'abc' is not defined
 #2中的input函数会严格检查输入的类型,abc此时没有指明字符串类型,被当成了变量名,所以引发了 NameError
 >>> var = input('pls type a num you want:')
 pls type a num you want:'abc' #改变输入值的类型
 >>> var
 'abc'

  • Python3: input() 

    • input 会把所有的输入当做字符串进行处理
 #python3.x
 >>> var = input('pls type a num you want:')
 pls type a num you want:20
 >>> var
 '20'
 >>> var = input('pls type a num you want:')
 pls type a num you want:abc
 >>> var
 'abc'
 #input保存的均为字符串类型