欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

常见问题汇总

程序员文章站 2022-07-12 10:34:40
...

1、一行代码实现99乘法表

print('\n'.join(['\t'.join(["%s%s=%s"%(j,i,ij) for j in range(1,i+1)]) for i in range(1,10)]))

2、进度条

def progress(percent, width=50):
    if percent >= 1:
        percent = 1
    show_str = ("[%%-%ds]" %width)%(int(width*percent)*"#")
    print("\r%s %d%%" %(show_str,int(100*percent)),file=sys.stdout,flush=True,end=" ")


data_size = 10000000
recv_size = 0
while recv_size < data_size:
    time.sleep(0.001)
    recv_size += 1024
    percent = recv_size/data_size
    progress(percent,width=100)

3、完成99乘法表

1 * 1 = 1
2 * 1 = 2 2 * 2 = 4
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
......
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81

递归的方法:

def bar(n):
    for i in range(1,n+1):
        res = "{} * {} = {}".format(n, i, n * i)
        print(res,end="  ")
    if n < 9:
        n += 1
        print("\n")
        bar(n)
bar(1)

循环

n = 1
while n < 10:
    for i in range(1, n + 1):
        res = "{} * {} = {}".format(n, i, n * i)
        print(res,end="\t")
    n+=1
    print("\t")

4、验证码

import string
import random
def code(n):
    s = ""
    for i in range(n):
        s1 = chr(random.randint(65,90))
        s2 = str(random.randint(0,9))
        s += random.choice([s1,s2])
    return s

# print(string.ascii_letters) #大小写字母
# print(string.digits) #0-9数字

#####################

def code1(n):
    return "".join(random.sample(string.ascii_letters+string.digits,n)) 

print(code1(6))  #这种方式取的值没有重复的

#####################

def code2(n=5):
    s = ""
    for i in range(n):
        s1 = random.choice(string.ascii_letters+string.digits)
        s += s1
    return s
print(code2())