python之输入输出
1.python解释器
[[email protected] ~]$ python
>>> import getpass # 导入getpass模块
>>> num=getpass.getpass('请输入密码:') # 输入密码前提示输入密码,如果什么都不写,那么就默认提示Passqord:
请输入密码:
>>> num # 获取变量的值
'redhat'
>>> age=raw_input('请输入年龄:') # 定义age变量
请输入年龄:16
>>> age # 获取age的值
'16'
>>> int(age) > 19 # 注意:条件前不能有空格
File "<stdin>", line 1
int(age) > 19
^
>>> int(age) > 19 # 判断年龄是否大于19
False
>>> type(age) # 查看age的类型,是str(字符串类型)
<type 'str'>
2.格式化输出(ipython)
In [1]: name='westos'
In [2]: name
Out[2]: 'westos'
In [3]: age = 16
In [4]: age
Out[4]: 16
In [5]: print('%s的年龄为%d' %(name,age))
westos的年龄为16
In [6]: name = 'redhat'
In [7]: print('%s的年龄为%d' %(name,age))
redhat的年龄为16
In [8]: money = 8576.123123
In [9]: print('%s本月的工资为%f' %(name,money))
redhat本月的工资为8576.123123
In [10]: money = 7000
In [11]: print('%s本月的工资为%f' %(name,money))
redhat本月的工资为7000.000000
In [12]: sid = 1
In [13]: print('%s的学号为%d' %(name,sid))
redhat的学号为1
In [14]: print('%s的学号为130%d' %(name,sid))
redhat的学号为1301
In [15]: print('%s的学号为130%.3d' %(name,sid))
redhat的学号为130001
In [16]: scale = 0.1
In [17]: print('数据比例是 %.2f' %(scale * 100))
数据比例是 10.00
In [18]: print('数据比例是 %.2f%%' %(scale * 100))
数据比例是 10.00%
3.拓展(getpass的了解)
getpass模块提供了可移植的密码输入,一共包括下面两个函数:
1. getpass.getpass()
2. getpass.getuser()
(1)getpass.getpass([prompt[, stream]])
提示用户输入一段密码,参数 prompt 用于提示用户开始输入,默认为'Password: '。
在 Unix 上,该提示符被写入到类文件对象流中。参数 stream 默认为控制终端 (/dev/tty) 或
入过前者不可用时为 sys.stderr (该参数在 Windows 上无效)。
如果无回显输入不可用,getpass() 回退并向流 stream 中输出一个警告消息,从 sys.stdin
中读取并抛出异常 GetPassWarning。适用于: Macintosh, Unix, Windows.
[[email protected] Desktop]# python3.6
>>> num=getpass.getpass()
Password:
>>> num
'123'
(2)exception getpass.GetPassWarning
Python内置异常 UserWarning 的子类,当密码输入可能被回显时抛出。
(3)getpass.getuser()
返回用户的登录名,适用于:Unix, Windows
该函数依次检测环境变量 LOGNAME、USER、LNAME 和 USERNAME,返回其中第一个非空的值。
如果这些变量都没有被设置,支持 pwd 模块的系统会返回密码数据库中的登录名,否则抛出异常。
注:此模块在pycharm中无法使用。