Python 脚本碎片

  • 基本输入输出 用户名/密码
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Liu Lei
import  getpass

username = input("username:")
password = getpass.getpass("password:")

print(username,password)
View Code

备注:

  getpass 在pycharm里边不好使哈,自己用别的方式测试

格式化输出

  • 三中格式化输出
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# User xxxx

username = input("username:")
age = int(input("age:"))   #integer
print(type(age),type(str(age)))
password = input("password:")
print(type(password))

info1 = '''
---- info of '''+ username +'''----
Name:'''+username+'''
Pawd:'''+ password

info2 = '''
---- info of  %s----
Name:%s
Age:%d
Pawd:%s
'''%(username,username,age,password)

info3 = '''
---- info of {Name}----
Name:{Name}
age:{Age}
Pawd:{Password}
'''.format(Name=username,
           Age=age,
           Password=password)

print(info1)
print(info2)
print(info3)
View Code

备注:格式化输出,字符类型种类参考

格式 描述
%% 百分号标记 #就是输出一个%
%c 字符及其ASCII码
%s 字符串
%d 有符号整数(十进制)
%u 无符号整数(十进制)
%o 无符号整数(八进制)
%x 无符号整数(十六进制)
%X 无符号整数(十六进制大写字符)
%e 浮点数字(科学计数法)
%E 浮点数字(科学计数法,用E代替e)
%f 浮点数字(用小数点符号)
%g 浮点数字(根据值的大小采用%e或%f)
%G 浮点数字(类似于%g)
%p 指针(用十六进制打印值的内存地址)
%n 存储输出字符的数量放进参数列表的下一个变量中
View Code
  •  非常用格式化,小节
info3 = '''
---- info of {0}----
Name:{1}
age:{2}
Pawd:{3}
'''.format(username,username,age,password)
View Code

简单while 循环 

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# xxxx
num = 33

count = 0
while count < 3:
    guess_num = int(input("input num:"))
    if guess_num == num:
        print("yes,you got it.")
        break
    elif guess_num  > num:
        print("think smaller...")
    else:
        print("think bigger!")
    count +=1
else:
    print("you have tried too many times...fuck off")
View Code

 简单for循环

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# xxxx

for i in range(0,10,2):
    print("loop",i)
View Code
原文地址:https://www.cnblogs.com/Star-Haitian/p/8351412.html