Day1:用户交互与格式化输出

一、用户交互

  1.input()方法

  

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan username = input("Username:")
password = input("Password:")
print(username,password)

  raw_input()   python 2.x 与input()  python 3.x是一样的

  2.密码密文问题

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
import getpass #导入getpass模块
username = input("username:")
password = getpass.getpass("password:")
print(username,password)

  引入getpass模块

  注:getpass在pycharm中有问题,可以在命令提示行中查看

C:\Users\wenxh\PycharmProjects\S14\day1>dir
驱动器 C 中的卷没有标签。
卷的序列号是 0008-AAC0 C:\Users\wenxh\PycharmProjects\S14\day1 的目录 2017/10/15 15:55 <DIR> .
2017/10/15 15:55 <DIR> ..
2017/10/15 14:04 109 coding.py
2017/09/28 20:53 241 guess.py
2017/09/26 21:42 199 interaction.py
2017/10/15 15:16 667 interaction2.py
2017/10/15 15:55 206 passwd.py
2017/09/28 20:47 294 password.py
2017/10/06 06:56 14 var.py
2017/09/26 21:33 235 var2.py
2017/10/15 14:18 204 var3.py
2017/09/28 22:03 367 while.py
2017/10/06 06:56 <DIR> __pycache__
10 个文件 2,536 字节
3 个目录 21,243,637,760 可用字节 C:\Users\wenxh\PycharmProjects\S14\day1>python passwd.py

  

username:Wenxh
password:
Wenxh 123456

  

二、格式化输出

  1.字符串拼接,使用加号“+”(不推荐使用)

  

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
name = input("name:")
age = input("age:")
job = input("job:")
salary = input("salary:")
info = '''
--------- info of '''+ name + ''' ----------
Name:'''+ name +'''
Age:'''+ age + '''
Job:'''+ job + '''
Salary:'''+salary
print(info)

  2.用$占位符

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
name = input("name:")
age = input("age:")
job = input("job:")
salary = input("salary:")
info = '''
--------- info of %s ----------
Name:%s
Age:%s
Job:%s
Salary:%s
'''%(name,name,age,job,salary)
print(info)

  其中%s的s代表的是string,还有$d,$f

  python中,默认的所有输入当作字符串

  如果age改成$d,需要将用户的输入转格式,如int(),或str()

  3.format方法一

  

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
name = input("name:")
age = int(input("age:")) #integer
#print(type(age),type(str(age)))
job = input("job:")
salary = input("salary:")
info2 = '''
--------- info of {_name} ----------
Name:{_name}
Age:{_age}
Job:{_job}
Salary:{_salary}
'''.format(_name = name , _age = age, _job = job,_salary = salary)
print(info2)

  4.format方法二

  

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Hiuhung Wan
name = input("name:")
age = int(input("age:")) #integer
#print(type(age),type(str(age)))
job = input("job:")
salary = input("salary:")
info3 = '''
--------- info of {0} ----------
Name:{0}
Age:{1}
Job:{2}
Salary:{3}
'''.format(name,age,job,salary)
print(info3)

如果参数多,使用此方法容易弄错

 
上一篇:python之while循环/格式化输出/运算符/初始编码/成员变量


下一篇:Atitit.软件gui按钮and面板---os区-----linux windows搜索文件 文件夹