Python 3 输入
eval()可以把字符串转化为代码进行运行。
content = input('请输入: ')
result = eval(content)
print(type(result))
print(result)
请输入: 1 + 1
<class ‘int’>
2
输出
print(values, sep, end, file, flush)
values: 需要输出多个值,使用 “,”进行分割
sep: 分割符,多个值,被输出出来之后,值与值之间,会添加指定的分隔符。
end: 输出完毕后,以指定的字符结束。默认是换行’\n’
file: 表示输出的目标,默认是标准输出(控制台),还可以是一个可写入的文件句柄。
flush: 表示立即输出,值为Bool类型。
输出多个变量
num1 = 55
num2 = 44
print(num1, num2)
格式化输出
name = 'sz'
age = 18
print('my name is %s, age is %d'%(name, age))
print('my name is {0}, age is {1}'.format(name, age))
my name is sz, age is 18
my name is sz, age is 18
输出到文件中
f = open('test.txt','w')
print('xxx',file=f)
默认情况:
import sys
print('xxx',file=sys.stdout)
输出结尾
print('xxx',end='*')
print('xxx',end='')
xxx*xxx
输出各个数据,使用分隔符分割
print('1', '2', '3', sep='=')
1=2=3
flush 参数的说明
from time import sleep
print('请输入', end="")
# 休眠5s
sleep(5)
print('请输入', end="",flush=True)
# 休眠5s
sleep(10)
然并软,并没有像视频中的 等5s才起作用
格式化输出,占位格式符
%[(name)][flags][width][.precision]typecode
[]:可以省略
(name)
表示根据制定的(key),查找对应的值,格式化到字符串当中
math = 59
english = 58
print('math score is %d, english score is %d' % (math, english))
print('math score is %(ms)d, english score is %(es)d' % ({'es':english, 'ms':math}))
math score is 59, english score is 58
math score is 59, english score is 58
(width)
表示占用宽度
math = 59
english = 58
print('%10d' % math)
59
(flags)
表示对齐
空表示右对齐
- 表示左对齐
空格 表示在正数的左侧填充一个空格,从而与负数对齐
0表示使用0填充
math = 59
print('%10d' % math)
print('%-10d' % math)
print('% d' % math)
math = -59
print('% d' % math)
59
59
59
-59
min = 5
sec = 18
print('%02d:%02d' % (min, sec))
05:18
.precision
表示小数点后精度
score = 59.9
print('%.2f' % score)
59.90
typeCode
print('%d' % 0b10)
print('%d' % 0o10)
print('%d' % 0x10)
2
8
16
print('%o' % 10)
print('%x' % 10)
print('%e' % 10)
12
a
1.000000e+01
%g 自动调整
print('%g' % 101.1)
print('%g' % 101)
print('%g' % 10111111)
101.1
101
1.01111e+07
c 讲数字转换为unicode对应的值
print('%c' % 97)
a
score = 65
print('%d%%' % score)
65%