Python interesting case sharing (continuous update and improvement)

Everything is based on the principle of the simplest code and the highest performance, preferring space for time

1. In the top 100, sum the numbers of "multiples of 3"

print(sum(i for i in range(0,101,3)))#对“3的倍数”的数求和
print(sum(i for i in range(0,101,2)))#对“2的倍数”的数求和

1683
2550

PS: If it is not required to be the simplest, you can draw conclusions using while loop and for loop

2. After adding the string text "¥12345.6789 yuan" to a random amount within thousand yuan, it becomes a string text with 2 decimal places

import random#导入随机模块
s='¥12345.6789元'
s1,s2,s3=s[0],s[1:-1],s[-1]#一次多赋值几个
s2=f'{float(s2)+random.uniform(0,1000):.2f}'#转类型相加再转回来
s22='{float(s2)+random.uniform(0,1000):.2f}'#没加f
print(s1+s2+s3)#字符串文本拼接
print(s1,s2,s3,s22,sep='-')#看看各元素

¥12754.67 yuan
¥-12754.67-yuan-{float(s2)+random.uniform(0,1000):.2f}

PS: string slicing, conversion type, splicing

3. Print the 99 multiplication table

for i in range(1,10):
    for j in range(1,i+1):
        print(f'{j}×{i}={j*i}',end=' ')
        # print("%d*%d=%2d"%(j,i,j*i),end=' ')#老版本等价写法
    print('')

1×1=1
1×2=2 2×2=4
1×3=3 2×3=6 3×3=9
1×4=4 2×4=8 3×4=12 4×4=16
1×5=5 2×5=10 3×5=15 4×5=20 5×5=25
1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81

PS: If you want to deal with the alignment details, you have to write the old version

4. Print the nine-nine-nine multiplication table (perfectly aligned version)

for i in range(1,10):
    for j in range(1,i+1):
        # print(f'{j}×{i}={j*i}',end=' ')#新版本写法
        print("%d*%d=%2d"%(j,i,j*i),end=' ')#老版本等价写法
    print('')

11= 1
1
2= 2 22= 4
1
3= 3 23= 6 33= 9
14= 4 24= 8 34=12 44=16
15= 5 25=10 35=15 45=20 55=25
1
6= 6 26=12 36=18 46=24 56=30 66=36
1
7= 7 27=14 37=21 47=28 57=35 67=42 77=49
18= 8 28=16 38=24 48=32 58=40 68=48 78=56 88=64
19= 9 29=18 39=27 49=36 5 9=45 6 9=54 7 9=63 8 9=72 9*9=81
Insert picture description here
%d #Number ordinary output;
%2d #The number is output according to the width of 2, right-justified output, with spaces on the left;
% 02d# The number is output according to the width of 2, right-justified, and 0 is added to the left;
%.2d# When outputting shaping, at least 2 digits are output, not enough to occupy a position of 0, if the decimal number is only the integer part (100→100, 2→02, 3.777) →03);
Insert picture description here

5.XXX

To be continued

Guess you like

Origin blog.csdn.net/Tiandao60/article/details/108565819