与用户交互
一、与用户交互
input 输入
python2与python3的区别
'''python3'''
# 将获取到的用户输入赋值给变量名res
res = input('please input your username>>>:')
print(res, type(res)) # 变量值的两大特征:id返回一串数字,反映内存地址,type返回变量值的数据类型
...
out
please input your username>>> richer
richer <class 'str'>
please input your username>>> [1,2,3,4,5]
[1,2,3,4,5] <class 'str'>
'''input获取到用户输入都会存成字符串形式'''
'''python2'''
# input需要用户自己人为的指定输入数据类型
res = input('please input your username>>>:')
print(res, type(res))
...
out
please input your username>>> "richer"
richer <class 'str'>
please input your username>>> [1,2,3,4,5]
[1,2,3,4,5] <class 'list'>
python2中的raw_input等价于python3里面的input。
print 输出
两种编写方式
1.先写print后写内容
print('richer')
2.先写待打印的内容,然后按TAB键
'richer'.print
二、格式化输出
要求:my name is 用户输入的用户名 my age is 用户输入的年龄
# 1.获取用户的用户名和年龄
name = input('username>>>:')
age = input('age>>:')
# 2.打印规定的文本内容
print('my name is ', name, 'my age is ', age) # 出打印内容编写较长,解决这样的问题采用格式化输出
提前定义文本模板
tmp = 'my name is %s my age is %s'
"""
%s是一个占位符,后续传值代替即可
"""
name = input('username>>>:')
age = input('age>>:')
print(tmp % (name, age)) # 与%s按照先后顺序一一传值替换
...
out
username>>>:richer
age>>:20
my name is richer my age is 20
print('my name is %s my age is %s' % ('richer')) # 少了不行
print('my name is %s my age is %s' % ('richer','jack','jeson')) # 多了也不行
"""
%d也是一个占位符,只能给数字占位
"""
# print('my name is %s my age is %s' % ('richer','123')) # %s 可以占任何数据类型
# print('my name is %s my age is %d' % ('richer', 123)) # %d 只能占数字类型,而且输出的是整型
print('%06d' % 123) # 表示固定位数,此处固定6位
out
# 000123 # 不够6位,少的则用0填充
# print('%06d' % 123456789)
out
# 123456798 # 多的是什么打印什么

浙公网安备 33010602011771号