三门问题

import random

num_change_win = 0
num_change_lose = 0
num_stay_win = 0
num_stay_lose = 0

def game():
    global num_change_win, num_change_lose, num_stay_win, num_stay_lose
    doors = ['羊', '羊', '车']
    random.shuffle(doors)              # 打乱3扇门
    choice = random.randint(0, 2)      # 第1次随机选择
    # 从剩下的2个里去掉一个羊
    others = list(range(3))
    others.remove(choice)
    if doors[others[0]] == '羊':
        other = others[1]
    else:
        other = others[0]
    # 随机选择 换 或者 不换,并记录
    is_changed = random.choice([True, False])
    if is_changed:      # 如果换了,选择变成剩下的另一扇门
        choice = other
    # 核对结果
    if doors[choice] == '车':    # 赢了
        if is_changed:           # 更换之后赢的
            num_change_win += 1
        else:                    # 不换之后赢的
            num_stay_win += 1
    else:                        # 输了
        if is_changed:           # 更换之后输的
            num_change_lose += 1
        else:                    # 不换之后输的
            num_stay_lose += 1

count = int(input('输入游戏次数:'))

UP = "\x1B[2A"
CLR = "\x1B[0K"
print("\n")  # set up blank lines so cursor moves work

for i in range(count):
    game()
    if num_change_win+num_change_lose > 0 and num_stay_win+num_stay_lose > 0:
        # print(f'{UP}【 换 】赢 {num_change_win:<7} 输 {num_change_lose:<7} 胜率 {num_change_win/(num_change_win+num_change_lose):.5f} {CLR}\n【不换】赢 {num_stay_win:<7} 输 {num_stay_lose:<7} 胜率 {num_stay_win/(num_stay_win+num_stay_lose):.5f}{CLR}\n', end='', flush=True)
        print(f'{UP}【 换 】赢 {num_change_win:<7} 输 {num_change_lose:<7}{CLR}\n【不换】赢 {num_stay_win:<7} 输 {num_stay_lose:<7}{CLR}\n', end='', flush=True)

批量download

import urllib.request
import time

for i in range(1, 66):
    url = f'http://crossincode.com/static/{i:03d}.mp3'  
    urllib.request.urlretrieve(url, f'{i:03d}.mp3')
    print(i)
    time.sleep(0.2)

压缩图片

from PIL import Image
import os

path = 'photos/'
for file in os.listdir(path):
    im = Image.open(path+file)
    x, y = im.size
    small_size = int(x * 0.5), int(y * 0.5)
    out = im.resize(small_size)
    out.save(path+'new_'+file)
    print(file)

文件合并

import pandas

df = pandas.read_excel('excels/小测验1.xlsx', index_col=0)
df1 = pandas.read_excel('excels/小测验2.xlsx', index_col=0)
df = pandas.concat([df, df1], axis=1)
print(df)

df.to_excel('汇总成绩.xlsx')

# import pandas

# dfs = []
# for i in range(1, 9):
#     df = pandas.read_excel(f'excels/小测验{i}.xlsx', index_col=0)
#     dfs.append(df)
# df = pandas.concat(dfs, axis=1)
# df.to_excel('汇总成绩.xlsx')

画爱心

import turtle
turtle.color('pink')
turtle.setheading(50)
turtle.begin_fill()
turtle.circle(-100, 170)
turtle.circle(-300, 40)
turtle.right(38)
turtle.circle(-300, 40)
turtle.circle(-100, 170)
turtle.end_fill()
turtle.done()

变量命名

a = 7
b = 8
c = 9

d = a + b + c
print(d)

e = d / 2
f = (e * (e - a) * (e - b) * (e - c)) ** 0.5
print(f)
d1tb = 7
d2tb = 8
d3tb = 9

sjxzc = d1tb + d2tb + d3tb
print(sjxzc)

sjxbzc = sjxzc / 2
sjxmj = (sjxbzc * (sjxbzc - d1tb) * (sjxbzc - d2tb) * (sjxbzc - d3tb)) ** 0.5
print(sjxmj)
第1条边长 = 7
第2条边长 = 8
第3条边长 = 9

三角形周长 = 第1条边长 + 第2条边长 + 第3条边长
print(三角形周长)

三角形半周长 = 三角形周长 / 2
三角形面积 = (三角形半周长 * (三角形半周长 - 第1条边长) * (三角形半周长 - 第2条边长) * (三角形半周长 - 第3条边长)) ** 0.5
print(三角形面积)
ಠ_ಠ = 7
ಥ_ಥ = 8
ದ_ದ = 9

อินอื = ಠ_ಠ + ಥ_ಥ + ದ_ದ
print(อินอื)

눈_눈 = อินอื / 2
งᐖoᐛง = (눈_눈 * (눈_눈 - ಠ_ಠ) * (눈_눈 - ಥ_ಥ) * (눈_눈 - ದ_ದ)) ** 0.5
print(งᐖoᐛง)
a1,a2,a3=7,8,9;a4=a1+a2+a3;print(a4);a5=a4/2;a6=(a5*(a5-a1)*(a5-a2)*(a5-a3))**0.5;print(a6)
_=print
__,___,____=7,8,9
_____=__+___+____
_(_____)
______=_____/2
_______=(
______*(
______-__)*(
______-___)*(
______-____)
)**0.5
_(_______)

换行


s = r'''
        ,]@@@@\]]*                                                                                 
    ,@@@/`      ,[@@@`                                                                             
  *@@`*.            *@@                                                                            
.,@`                  \@*                                                                          
,@^                    \@                                                ,]]`*..                   
@@                      @^                                         *,/@@[\]],[[[[\@\`              
@^                      @^                                    @@*  @@`,@@[ =@      ,@@`            
@^                      @^                                    @@@\@//@/*   =@*       ,@\           
@@                     ,@^                                    @@@@@@[*      @\         @\          
=@*                   ,@/.   @@\  =@@                         =@@@*          \@\       =@^         
 \@                  /@`,@]  \@@^ @@@*                        =@@@*.           \@..     =@         
  \@`  .*...***.* ]@@`  \@=@`=@@@ @@@^                    ]@@@/@@@              \@@@`    @^        
   .\@@]*.**.*]@@@`.  ,@`\@/@^=@@\@@@^                    \@`,@@@@@^            ..  @^   =@        
       ,[[\[[[*       =@/@@@@@@@^@/*@^      ,`             ,@@@/[@\@          ,`   /@`   =@        
       .*. ..*        .*\@@@@^      @@` *]/@@@`            =@     *@@@@@@@@@@@@[ @@`    ,@^        
                          \@\*        [[[[*/@*             *@^     =@*]@@@/`     \\   ,/@^         
                            =@`         ,@@`.               \@      @/`           @@@@[*           
                             \@        /@..                 =@`..   =@*           \@@\].           
                             ,@^     @@@^                    @^      @^               ,[@@`        
                             =@[@\]@@/ @^                    @\      =@`                  \@`      
                             ,@` **    \@*                ,]@@@       @\                   ,@^     
                              ,@^       ,@@*           ,@/[` =@`      =@      .]]]@\*       ,@^    
                               ,@^        =@`         =@`     @^      *@^. ,@@[`*...         \@    
                                ,@^        =@*       /@`      @@       ,@@@[                 *@^   
                                 =@*        @\     ,@^        =@                              @\   
                                  \@        =@`,@@/@^         *@^                             @@   
                                  *@^        \@@@  ..          @\                             @@   
                                   =@*                         =@                             @^   
                                    @@                         *@^                            @^   
                                    *@^                         @@                           =@^   
                                     =@^                        ,@\.             .*]]@@@^    =@.   
                                      =@`                         ,\@@@@@@@@@[[[[[[[         =@    
                                       =@` ...     .,]]]]@@@`                                @@    
                                        ,\@@@@@@@[[[[`*    @/                                @^    
                                                          /@                                .@^    
                                                         =@`                                ,@^    
                                                         @/                                 .@^    
                                                         @^                                  =@`   
                                                        *@^                                    \@\ 
                                                         @@                                      @\
                                                          \@                                     ,@
                                                           @^                                     @
                                                           =@                                     @
                                                           =@.                                   =@
                                                           =@*                  ]]@@@@@@@@@@@@@@@/ 
                                                           =@^            ,]@@@/[*             =@^ 
                                                            *\@]]]]]]/@@@/[.                    @^ 
                                                              @@                                =@ 
                                                              =@.                               =@ 
'''
print(s)

字符串格式化

name = '小白'
age = 18
place = 'python'

print('我叫'+name+',今年'+str(age)+'岁,来自'+place+',很高兴认识你!')
print('我叫',name,',今年',age,'岁,来自',place,',很高兴认识你!')
print(f'我叫{name},今年{age}岁,来自{place},很高兴认识你!')
print('我叫{},今年{}岁,来自{},很高兴认识你!'.format(name,age,place))
print('我叫%s,今年%d岁,来自%s,很高兴认识你!' %(name,age,place))

画图

import turtle as t
t.speed(10)
# t.tracer(False)
t.setup(1024, 768)
t.bgcolor('white') 
t.title("Happy Teacher's Day(代码来源:Crossin的编程教室)")
# 友情提醒:在公共平台发布此代码衍生作品时需保留标题上的来源,或在其他明显位置注明
t.pensize(3)
t.fillcolor('DarkOliveGreen4')
t.pu()
t.goto(81, -383)
t.pd()
t.begin_fill()
t.goto(75, -360)
t.goto(60, -332)
t.goto(56, -299)
t.goto(-5, -234)
t.goto(-74, -177)
t.goto(-139, -184)
t.goto(-119, -170)
t.goto(-110, -160)
t.goto(-89, -164)
t.goto(-119, -143)
t.goto(-153, -150)
t.goto(-177, -130)
t.goto(-169, -130)
t.goto(-170, -104)
t.goto(-148, -107)
t.goto(-143, -92)
t.goto(-133, -105)
t.goto(-125, -125)
t.goto(-91, -152)
t.goto(-99, -135)
t.goto(-99, -114)
t.goto(-110, -84)
t.goto(-84, -122)
t.goto(-75, -150)
t.goto(-61, -164)
t.goto(-63, -168)
t.goto(-43, -177)
t.goto(1, -222)
t.goto(55, -275)
t.goto(56, -248)
t.goto(67, -236)
t.goto(70, -288)
t.goto(79, -316)
t.goto(90, -192)
t.goto(92, -139)
t.goto(82, -128)
t.goto(75, -86)
t.goto(51, -57)
t.goto(37, -11)
t.goto(63, -62)
t.goto(86, -84)
t.goto(50, -4)
t.goto(22, 1)
t.goto(46, 22)
t.goto(53, 57)
t.goto(64, 52)
t.goto(65, 49)
t.goto(69, 48)
t.goto(69, 31)
t.goto(60, -2)
t.goto(76, -21)
t.goto(91, -64)
t.goto(111, -44)
t.goto(121, -36)
t.goto(131, 8)
t.goto(130, -42)
t.goto(110, -71)
t.goto(110, -129)
t.goto(104, -135)
t.goto(107, -198)
t.goto(118, -223)
t.goto(118, -285)
t.goto(94, -336)
t.goto(95, -362)
t.goto(100, -380)
t.end_fill()
t.fillcolor('IndianRed3')
t.pu()
t.goto(-170, -129)
t.pd()
t.begin_fill()
t.goto(-229, -122)
t.goto(-278, -83)
t.goto(-303, -59)
t.goto(-299, -43)
t.goto(-304, -33)
t.goto(-298, -32)
t.goto(-298, -21)
t.goto(-278, -25)
t.goto(-269, -20)
t.goto(-253, -39)
t.goto(-231, -36)
t.goto(-197, -66)
t.goto(-147, -106)
t.goto(-170, -106)
t.goto(-170, -129)
t.end_fill()
t.pu()
t.goto(52, 56)
t.pd()
t.begin_fill()
t.goto(47, 19)
t.goto(14, -9)
t.goto(-33, -12)
t.goto(-50, -3)
t.goto(-69, -3)
t.goto(-87, 22)
t.goto(-109, 2)
t.goto(-130, 1)
t.goto(-134, 7)
t.goto(-151, 8)
t.goto(-182, 46)
t.goto(-202, 66)
t.goto(-188, 82)
t.goto(-207, 87)
t.goto(-207, 100)
t.goto(-226, 126)
t.goto(-220, 146)
t.goto(-230, 166)
t.goto(-225, 174)
t.goto(-233, 194)
t.goto(-228, 204)
t.goto(-215, 206)
t.goto(-215, 222)
t.goto(-206, 229)
t.goto(-196, 225)
t.goto(-182, 271)
t.goto(-174, 280)
t.goto(-160, 279)
t.goto(-150, 287)
t.goto(-147, 298)
t.goto(-139, 305)
t.goto(-135, 314)
t.goto(-124, 312)
t.goto(-112, 319)
t.goto(-109, 305)
t.goto(-100, 303)
t.goto(-96, 321)
t.goto(-82, 327)
t.goto(-73, 335)
t.goto(-59, 332)
t.goto(-32, 330)
t.goto(-28, 318)
t.goto(-43, 303)
t.goto(-34, 298)
t.goto(-18, 300)
t.goto(-20, 324)
t.goto(-12, 331)
t.goto(-4, 323)
t.goto(6, 327)
t.goto(15, 322)
t.goto(34, 318)
t.goto(35, 307)
t.goto(46, 307)
t.goto(56, 319)
t.goto(59, 314)
t.goto(75, 311)
t.goto(88, 288)
t.goto(104, 277)
t.goto(117, 277)
t.goto(128, 256)
t.goto(144, 245)
t.goto(145, 225)
t.goto(165, 218)
t.goto(172, 191)
t.goto(161, 176)
t.goto(150, 170)
t.goto(148, 159)
t.goto(132, 157)
t.goto(150, 141)
t.goto(150, 118)
t.goto(156, 106)
t.goto(151, 98)
t.goto(138, 88)
t.goto(136, 75)
t.goto(123, 62)
t.goto(87, 53)
t.goto(68, 50)
t.goto(54, 54)
t.end_fill()
t.pu()
t.goto(79, -361)
t.pd()
t.goto(93, -361)
t.pu()
t.goto(86, -360)
t.pd()
t.goto(80, -335)
t.goto(62, -305)
t.goto(56, -285)
t.goto(54, -273)
t.pu()
t.goto(80, -335)
t.pd()
t.goto(76, -311)
t.pu()
t.goto(84, -289)
t.pd()
t.goto(90, -271)
t.goto(101, -255)
t.goto(109, -226)
t.goto(107, -198)
t.pu()
t.goto(-76, -179)
t.pd()
t.goto(-66, -173)
t.goto(-62, -166)
t.pu()
t.goto(-176, -132)
t.pd()
t.goto(-144, -128)
t.goto(-146, -100)
t.pu()
t.goto(-92, -164)
t.pd()
t.goto(-81, -168)
t.goto(-91, -149)
t.pu()
t.goto(89, -135)
t.pd()
t.goto(95, -137)
t.goto(105, -132)
t.pu()
t.goto(102, -131)
t.pd()
t.goto(102, -109)
t.goto(78, -76)
t.pu()
t.goto(102, -102)
t.pd()
t.goto(101, -84)
t.goto(92, -63)
t.pu()
t.goto(46, 18)
t.pd()
t.goto(48, -1)
t.goto(57, 32)
t.goto(67, 45)
t.pu()
t.goto(-298, -34)
t.pd()
t.goto(-262, -37)
t.goto(-241, -53)
t.pu()
t.goto(-281, -79)
t.pd()
t.goto(-259, -79)
t.goto(-263, -58)
t.goto(-209, -73)
t.goto(-161, -106)
t.pu()
t.goto(-235, -44)
t.pd()
t.goto(-224, -68)
t.pu()
t.goto(-65, 23)
t.pd()
t.goto(-49, 9)
t.goto(-47, -3)
t.pu()
t.goto(115, 61)
t.pd()
t.goto(127, 93)
t.goto(140, 104)
t.goto(135, 120)
t.goto(117, 141)
t.pu()
t.goto(54, 52)
t.pd()
t.goto(52, 81)
t.pu()
t.goto(-17, 68)
t.pd()
t.goto(-7, 61)
t.goto(11, 63)
t.goto(21, 56)
t.goto(41, 64)
t.goto(49, 80)
t.goto(63, 83)
t.goto(86, 102)
t.goto(56, 102)
t.goto(50, 122)
t.goto(79, 113)
t.goto(96, 121)
t.goto(105, 141)
t.goto(122, 141)
t.goto(128, 157)
t.goto(134, 157)
t.pu()
t.goto(-17, 97)
t.pd()
t.goto(-28, 52)
t.goto(-55, 32)
t.goto(-74, 34)
t.goto(-89, 21)
t.goto(-132, 28)
t.goto(-144, 44)
t.goto(-142, 76)
t.pu()
t.goto(-155, 15)
t.pd()
t.goto(-134, 11)
t.goto(-105, 24)
t.goto(-98, 24)
t.goto(-91, 48)
t.goto(-52, 48)
t.goto(-31, 61)
t.goto(-22, 75)
t.pu()
t.goto(126, 256)
t.pd()
t.goto(129, 230)
t.goto(153, 205)
t.goto(154, 178)
t.goto(142, 170)
t.goto(129, 172)
t.goto(126, 188)
t.goto(111, 183)
t.goto(98, 184)
t.goto(88, 191)
t.goto(64, 193)
t.pu()
t.goto(-110, 93)
t.pd()
t.goto(-133, 75)
t.goto(-146, 78)
t.goto(-157, 70)
t.goto(-168, 70)
t.goto(-175, 85)
t.goto(-195, 92)
t.goto(-205, 105)
t.goto(-196, 119)
t.goto(-205, 127)
t.goto(-205, 139)
t.goto(-192, 155)
t.goto(-200, 171)
t.goto(-191, 186)
t.goto(-179, 189)
t.goto(-179, 201)
t.goto(-169, 213)
t.pu()
t.goto(-190, 81)
t.pd()
t.goto(-178, 86)
t.pu()
t.goto(-220, 148)
t.pd()
t.goto(-206, 137)
t.pu()
t.goto(-225, 161)
t.pd()
t.goto(-206, 158)
t.goto(-198, 150)
t.pu()
t.goto(-201, 224)
t.pd()
t.goto(-201, 212)
t.goto(-196, 200)
t.goto(-180, 193)
t.pu()
t.goto(-124, 175)
t.pd()
t.goto(-145, 174)
t.goto(-168, 154)
t.goto(-168, 142)
t.goto(-160, 130)
t.goto(-165, 109)
t.goto(-154, 102)
t.goto(-137, 104)
t.goto(-136, 97)
t.goto(-121, 98)
t.goto(-115, 108)
t.goto(-106, 92)
t.goto(-96, 93)
t.goto(-88, 105)
t.goto(-85, 116)
t.goto(-80, 107)
t.goto(-70, 101)
t.goto(-63, 108)
t.goto(-59, 119)
t.goto(-47, 114)
t.goto(-42, 116)
t.pu()
t.goto(-61, 105)
t.pd()
t.goto(-51, 107)
t.goto(-45, 113)
t.pu()
t.goto(-42, 141)
t.pd()
t.goto(-42, 115)
t.goto(-26, 104)
t.goto(-14, 96)
t.goto(8, 97)
t.goto(25, 109)
t.goto(36, 132)
t.pu()
t.goto(-45, 153)
t.pd()
t.goto(-34, 122)
t.goto(-20, 118)
t.goto(-4, 121)
t.goto(0, 117)
t.goto(9, 118)
t.goto(11, 127)
t.goto(17, 131)
t.goto(20, 127)
t.goto(28, 129)
t.goto(29, 133)
t.goto(38, 133)
t.goto(45, 140)
t.goto(40, 145)
t.goto(26, 148)
t.goto(18, 158)
t.pu()
t.goto(-84, 234)
t.pd()
t.goto(-102, 239)
t.goto(-116, 222)
t.goto(-111, 207)
t.goto(-125, 194)
t.goto(-122, 171)
t.goto(-101, 146)
t.goto(-89, 147)
t.goto(-77, 158)
t.pu()
t.goto(-57, 224)
t.pd()
t.goto(-81, 201)
t.goto(-92, 185)
t.goto(-90, 176)
t.goto(-75, 159)
t.goto(-32, 156)
t.goto(-21, 163)
t.goto(-13, 165)
t.goto(-2, 182)
t.goto(-6, 211)
t.goto(-28, 229)
t.goto(-41, 201)
t.goto(-40, 163)
t.goto(-55, 199)
t.goto(-55, 223)
t.pu()
t.goto(-70, 165)
t.pd()
t.goto(-81, 173)
t.goto(-76, 196)
t.goto(-78, 203)
t.pu()
t.goto(-74, 207)
t.pd()
t.goto(-84, 220)
t.goto(-83, 231)
t.goto(-71, 238)
t.goto(-64, 226)
t.goto(-55, 224)
t.pu()
t.goto(-62, 229)
t.pd()
t.goto(-49, 238)
t.goto(-37, 230)
t.goto(-28, 231)
t.goto(-18, 238)
t.goto(4, 236)
t.goto(15, 215)
t.goto(14, 207)
t.goto(23, 198)
t.goto(19, 180)
t.goto(7, 168)
t.goto(0, 168)
t.goto(16, 159)
t.goto(36, 170)
t.goto(38, 195)
t.goto(48, 210)
t.goto(40, 213)
t.goto(29, 210)
t.goto(35, 230)
t.goto(25, 250)
t.goto(8, 245)
t.goto(-6, 255)
t.goto(-15, 255)
t.goto(-25, 234)
t.pu()
t.goto(-17, 238)
t.pd()
t.goto(-7, 246)
t.pu()
t.goto(40, 185)
t.pd()
t.goto(53, 185)
t.goto(74, 204)
t.goto(69, 208)
t.goto(46, 205)
t.pu()
t.goto(73, 210)
t.pd()
t.goto(79, 210)
t.goto(84, 220)
t.goto(94, 221)
t.goto(94, 239)
t.goto(106, 253)
t.goto(105, 275)
t.pu()
t.goto(7, 252)
t.pd()
t.goto(32, 264)
t.goto(46, 281)
t.goto(50, 268)
t.goto(46, 256)
t.goto(63, 252)
t.goto(65, 231)
t.goto(51, 219)
t.goto(34, 217)
t.pu()
t.goto(50, 273)
t.pd()
t.goto(61, 253)
t.pu()
t.goto(5, 245)
t.pd()
t.goto(8, 272)
t.goto(-3, 277)
t.goto(-16, 268)
t.goto(-25, 268)
t.goto(-29, 273)
t.goto(-40, 273)
t.goto(-49, 280)
t.goto(-32, 297)
t.goto(-13, 297)
t.goto(14, 279)
t.goto(13, 266)
t.goto(9, 255)
t.pu()
t.goto(14, 259)
t.pd()
t.goto(20, 289)
t.goto(15, 299)
t.goto(30, 303)
t.goto(33, 313)
t.goto(36, 295)
t.goto(18, 256)
t.pu()
t.goto(-34, 329)
t.pd()
t.goto(-38, 320)
t.goto(-49, 314)
t.goto(-49, 302)
t.pu()
t.goto(-42, 302)
t.pd()
t.goto(-59, 297)
t.goto(-69, 291)
t.goto(-87, 293)
t.goto(-94, 275)
t.goto(-86, 253)
t.goto(-62, 241)
t.pu()
t.goto(-60, 229)
t.pd()
t.goto(-58, 243)
t.goto(-64, 254)
t.goto(-51, 262)
t.goto(-25, 259)
t.goto(-16, 253)
t.pu()
t.goto(-155, 170)
t.pd()
t.goto(-161, 184)
t.goto(-154, 191)
t.goto(-161, 208)
t.goto(-156, 224)
t.goto(-141, 228)
t.goto(-140, 233)
t.goto(-123, 235)
t.pu()
t.goto(-117, 223)
t.pd()
t.goto(-122, 227)
t.goto(-122, 238)
t.goto(-132, 251)
t.goto(-124, 288)
t.goto(-137, 298)
t.goto(-139, 305)
t.pu()
t.goto(-128, 271)
t.pd()
t.goto(-110, 286)
t.goto(-103, 284)
t.goto(-95, 272)
t.goto(-98, 258)
t.goto(-96, 238)
t.pu()
t.goto(-148, 288)
t.pd()
t.goto(-143, 266)
t.goto(-148, 244)
t.goto(-138, 236)
t.pu()
t.hideturtle()
t.done()
from math import sin, cos, pi
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Wedge

length = 20
R = 3**0.5*length/(3**0.5*cos(pi/12)-sin(pi/12))
r = 2*sin(pi/12)*R/3**0.5

fig, ax = plt.subplots(figsize=(8, 6))
ax.set_aspect('equal')

for i in range(12):
    ax.add_patch(Circle((length*cos(pi*i/6),length*sin(pi*i/6)), r, ec='orange', fc='khaki', linewidth=4))

ax.add_patch(Circle((0,0), R, ec='orange', fc='khaki', linewidth=4))

for i in range(4):
    pos = [2, 5]
    rr = [5, 12]
    for j in range(2):
        ax.add_patch(Wedge([(-1) ** (i // 2 + 1) * pos[j], (-1) ** ((i + 1) // 2) * pos[j]], R - rr[j], 90 * (i+1), 90 * (i + 2),
              ec='orange', fc=r'khaki', linewidth=4))

fig.canvas.set_window_title('Happy Mid-autumn Day')
plt.text(-19, -2.5, 'CROSSIN', bbox=dict(boxstyle='square', fc="khaki", ec='orange', linewidth=4),  fontsize=40, color='orange')
plt.axis('off')
plt.ylim([-35, 35])
plt.xlim([-35, 35])
plt.show()

Sheep

# 代码使用 pygame-zero 框架,会有很多未定义的方法和变量,编辑器里会报错,但其实是可以运行的,无需手动增加 import。
# pgzero有两种方式运行(https://pygame-zero.readthedocs.io/zh_CN/latest/ide-mode.html)
# 本代码用的是第二种直接运行的方式(需新版pgzero)。
# 把最后的pgzrun.go()去掉,然后直接在命令行该目录下运行: pgzrun sheep.py

import pgzrun
import pygame
import random
import math
import os

# 定义游戏相关属性
TITLE = '白了个白' 
WIDTH = 600
HEIGHT = 720

# 自定义游戏常量
T_WIDTH = 60
T_HEIGHT = 66

# 下方牌堆的位置
DOCK = Rect((90, 564), (T_WIDTH*7, T_HEIGHT))

# 上方的所有牌
tiles = []
# 牌堆里的牌
docks = []

# 初始化牌组,12*12张牌随机打乱
ts = list(range(1, 13))*12
random.shuffle(ts)
n = 0
for k in range(7):    # 7层
    for i in range(7-k):    #每层减1行
        for j in range(7-k):
            t = ts[n]        #获取排种类
            n += 1
            tile = Actor(f'tile{t}')       #使用tileX图片创建Actor对象
            tile.pos = 120 + (k * 0.5 + j) * tile.width, 100 + (k * 0.5 + i) * tile.height * 0.9    #设定位置
            tile.tag = t            #记录种类
            tile.layer = k          #记录层级
            tile.status = 1 if k == 6 else 0        #除了最顶层,状态都设置为0(不可点)这里是个简化实现
            tiles.append(tile)
for i in range(4):        #剩余的4张牌放下面(为了凑整能通关)
    t = ts[n]
    n += 1
    tile = Actor(f'tile{t}')
    tile.pos = 210 + i * tile.width, 516
    tile.tag = t
    tile.layer = 0
    tile.status = 1
    tiles.append(tile)


# 游戏帧绘制函数
def draw():
    screen.clear()
    screen.blit('back', (0, 0))      #背景图
    for tile in tiles:
        #绘制上方牌组
        tile.draw()
        if tile.status == 0:
            screen.blit('mask', tile.topleft)     #不可点的添加遮罩
    for i, tile in enumerate(docks):
        #绘制排队,先调整一下位置(因为可能有牌被消掉)
        tile.left = (DOCK.x + i * T_WIDTH)
        tile.top = DOCK.y
        tile.draw()

    # 超过7张,失败
    if len(docks) >= 7:
        screen.blit('end', (0, 0))
    # 没有剩牌,胜利
    if len(tiles) == 0:
        screen.blit('win', (0, 0))


# 鼠标点击响应
def on_mouse_down(pos):
    global docks
    if len(docks) >= 7 or len(tiles) == 0:      #游戏结束不响应
        return
    for tile in reversed(tiles):    #逆序循环是为了先判断上方的牌,如果点击了就直接跳出,避免重复判定
        if tile.status == 1 and tile.collidepoint(pos):
            # 状态1可点,并且鼠标在范围内
            tile.status = 2
            tiles.remove(tile)
            diff = [t for t in docks if t.tag != tile.tag]    #获取牌堆内不相同的牌
            if len(docks) - len(diff) < 2:    #如果相同的牌数量<2,就加进牌堆
                docks.append(tile)
            else:             #否则用不相同的牌替换牌堆(即消除相同的牌)
                docks = diff
            for down in tiles:      #遍历所有的牌
                if down.layer == tile.layer - 1 and down.colliderect(tile):   #如果在此牌的下一层,并且有重叠
                    for up in tiles:      #那就再反过来判断这种被覆盖的牌,是否还有其他牌覆盖它
                        if up.layer == down.layer + 1 and up.colliderect(down):     #如果有就跳出
                            break
                    else:      #如果全都没有,说明它变成了可点状态
                        down.status = 1
            return

music.play('bgm')

pgzrun.go()

爱心


import pgzrun
from math import pi, sin, cos
import random

# 粒子类,图像上每一个小点都是一个粒子对象
class Particle():
    def __init__(self, pos, size, f):
        self.pos = pos    # 粒子当前位置(后面会变动)
        self.pos0 = pos   # 粒子的原始位置
        self.size = size  # 粒子大小
        self.f = f        # 粒子的随机位移比例

    def draw(self):
        global L
        # 用矩形绘制粒子
        screen.draw.filled_rect(Rect((L*self.f*self.pos[0] + 400, -L*self.f*self.pos[1] + 300), self.size), 'hot pink')

    def update(self, t):
        # 根据程序运行时间计算一个正弦函数作为位移量
        # 如果要调整爱心跳动的频率、幅度等效果,可修改这里面的数字
        df = 1 + (4 - 3 * self.f) * sin(t * 3) / 12
        self.pos = self.pos0[0] * df, self.pos0[1] * df

tt = [105, 102, 98, 115, 117, 33, 112, 103, 33, 106, 108, 118, 111, 33, 46, 33, 68, 115, 112, 116, 116, 106, 111, 30341, 32535, 31244, 25946, 23461]
no_p = 20000
dt = 2*pi/no_p
particles = []
t = 0
c = 0
# 采用极坐标下的爱心曲线,计算出爱心图案上的基准点,创建粒子对象
# 每个点会有一个延轴向的随机位移,随机采用正态分布
while t < 2*pi:
    c += 1
    sigma = 0.15 if c % 5 else 0.3
    f = 1 - abs(random.gauss(1, sigma) - 1)
    x = 16*sin(t)**3
    y = 13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)
    size = (random.uniform(0.5,2.5), random.uniform(0.5,2.5))
    particles.append(Particle((x, y), size, f))
    t += dt

def draw():
    screen.clear()
    # 绘制爱心粒子
    for p in particles:
        p.draw()

    if L == 10:
        # 采用同样原理,绘制外层大爱心,但生成粒子,只是每帧随机绘制
        t = 0
        while t < 2*pi:
            f = random.gauss(1.1, 0.1)
            x = 16*sin(t)**3
            y = 13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)
            size = (random.uniform(0.5,2.5), random.uniform(0.5,2.5))
            screen.draw.filled_rect(Rect((10*f*x + 400, -10*f*y + 300), size), 'hot pink')
            t += dt * 3
    screen.draw.filled_rect(Rect((-10*11 + 400, 11*20 + 200), (2, 2)), 'hot pink')

TITLE = ''.join([chr(i-1) for i in tt])
status = 0
L = 100
elapsed = 0
def update(dt):
    global elapsed, L, status
    elapsed += dt
    if status == 0:
        # 为了初始的集聚效果,加了一个很大的倍数L,并不断缩小至正常值
        L -= dt * 200
        if L <= 10:
            status = 1
            L = 10
    elif status == 2:
        L += dt * 200
    # 根据时间更新粒子位置
    for p in particles:
        p.update(elapsed)

TITLE = 'heart'

pgzrun.go()

Python一些例子_CLR

from math import pi, sin, cos
import matplotlib.pyplot as plt
no_pieces = 100
dt = 2*pi/no_pieces
t = 0
vx = []
vy = []
while t <= 2*pi:
    vx.append(16*sin(t)**3)
    vy.append(13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t))
    t += dt
plt.plot(vx, vy)
plt.show()

Python一些例子_d3_02

size = 10
for x in range(size):
    for y in range(4*size+1):
        dist1 = ((x-size)**2 + (y-size)**2) ** 0.5
        dist2 = ((x-size)**2 + (y-3*size)**2) ** 0.5
        if dist1 < size + 0.5 or dist2 < size + 0.5:
            print('V', end=' ')
        else:
            print(' ', end=' ')
    print()

for x in range(1, 2*size):
    for y in range(x):
        print(' ', end=' ')
    for y in range(4*size+1-2*x):
        print('V', end=' ')
    print()

Python一些例子_d3_03

for y in range(9, -6, -1):
    for x in range(-8, 9):
        print('*##*'[(x+10)%4] if (x*x+y*y-25)**3 < 25*x*x*y*y*y else '-', end=' ')
    print()


# for y in range(9, -6, -1):
#     for x in range(-8, 9):
#         print('1' if (x*x+y*y-25)**3 < 25*x*x*y*y*y else ' ', end=' ')
#     print()

Python一些例子_d3_04

import turtle as t
t.color('red')
t.setheading(50)
t.begin_fill()
t.circle(-100, 170)
t.circle(-300, 40)
t.right(38)
t.circle(-300, 40)
t.circle(-100, 170)
t.end_fill()
t.done()

Python一些例子_CLR_05

电费计算器

import tkinter as tk
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei', 'Songti SC']

root = tk.Tk()
root.title('电费计算器')
root.geometry("510x800")

tk.Label(root, text='电器').grid(row=0, column=0)
tk.Label(root, text='功率(千瓦)').grid(row=0, column=1)
tk.Label(root, text='每天用时(小时)').grid(row=0, column=2)
tk.Label(root, text='每月天数').grid(row=0, column=3)
tk.Label(root, text='电费(元)').grid(row=0, column=4)

class Item:
    count = 0

    def __init__(self):
        Item.count += 1
        self.name = tk.StringVar()
        self.power = tk.DoubleVar(value="")
        self.hours = tk.DoubleVar(value="")
        self.days = tk.IntVar(value="")
        self.charge = tk.DoubleVar(value="")
        r = Item.count
        tk.Entry(root, textvariable=self.name, width=10).grid(row=r, column=0)
        tk.Entry(root, textvariable=self.power, width=10).grid(row=r, column=1)
        tk.Entry(root, textvariable=self.hours, width=10).grid(row=r, column=2)
        tk.Entry(root, textvariable=self.days, width=10).grid(row=r, column=3)
        tk.Entry(root, textvariable=self.charge, width=10, state=tk.DISABLED).grid(row=r, column=4)

    def cal_charge(self):
        c = self.power.get() * self.hours.get() * self.days.get() * price.get()
        self.charge.set(c)
        return c

items = []
for i in range(10):
    items.append(Item())

tk.Label(root, text='', width=5).grid(row=11, column=0)

tk.Label(root, text='电价(元/度)').grid(row=12, column=0)
price = tk.DoubleVar(value=1)
tk.Entry(root, textvariable=price, width=10).grid(row=12, column=1)

names = []
charges = []
def cal():
    names.clear()
    charges.clear()
    total = 0
    for i in items:
        n = i.name.get()
        if n:
            names.append(n)
            charges.append(i.cal_charge())
    total = sum(charges)
    charge.set(total)
    # 绘图
    fig.clear()
    fig.add_subplot().pie([int(c) for c in charges], labels=names)

    canvas.draw()
    canvas.get_tk_widget().grid(row=14, columnspan=5)

tk.Button(root, text='计算', command=cal, width=10).grid(row=12, column=2)

tk.Label(root, text='电费(元)').grid(row=12, column=3)
charge = tk.DoubleVar()
tk.Entry(root, textvariable=charge, width=10, state=tk.DISABLED).grid(row=12, column=4)

fig = Figure(figsize=(5, 4), dpi=100)
canvas = FigureCanvasTkAgg(fig, master=root)

root.mainloop()
items = []
while True:
    name = input('电器:')
    if not name:
        break
    power = float(input('功率(千瓦):'))
    hours = float(input('每天用时(小时):'))
    days = int(input('每月天数:'))
    print('----------')

    items.append((name, power * hours * days))

print('==========')
price = float(input('电价(元/度):'))

items.sort(key=lambda i: i[1], reverse=True)

for i in items:
    print(f'{i[0]}:{i[1] * price}元')
import tkinter as tk

root = tk.Tk()
root.title('电费计算器')
root.geometry("510x370")

tk.Label(root, text='电器').grid(row=0, column=0)
tk.Label(root, text='功率(千瓦)').grid(row=0, column=1)
tk.Label(root, text='每天用时(小时)').grid(row=0, column=2)
tk.Label(root, text='每月天数').grid(row=0, column=3)
tk.Label(root, text='电费(元)').grid(row=0, column=4)

class Item:
    count = 0

    def __init__(self):
        Item.count += 1
        self.name = tk.StringVar()
        self.power = tk.DoubleVar(value="")
        self.hours = tk.DoubleVar(value="")
        self.days = tk.IntVar(value="")
        self.charge = tk.DoubleVar(value="")
        r = Item.count
        tk.Entry(root, textvariable=self.name, width=10).grid(row=r, column=0)
        tk.Entry(root, textvariable=self.power, width=10).grid(row=r, column=1)
        tk.Entry(root, textvariable=self.hours, width=10).grid(row=r, column=2)
        tk.Entry(root, textvariable=self.days, width=10).grid(row=r, column=3)
        tk.Entry(root, textvariable=self.charge, width=10, state=tk.DISABLED).grid(row=r, column=4)

    def cal_charge(self):
        c = self.power.get() * self.hours.get() * self.days.get() * price.get()
        self.charge.set(c)
        return c

items = []
for i in range(10):
    items.append(Item())

tk.Label(root, text='', width=5).grid(row=11, column=0)

tk.Label(root, text='电价(元/度)').grid(row=12, column=0)
price = tk.DoubleVar(value=1)
tk.Entry(root, textvariable=price, width=10).grid(row=12, column=1)

def cal():
    total = 0
    for i in items:
        n = i.name.get()
        if n:
            total += i.cal_charge()
    charge.set(total)

tk.Button(root, text='计算', command=cal, width=10).grid(row=12, column=2)

tk.Label(root, text='电费(元)').grid(row=12, column=3)
charge = tk.DoubleVar()
tk.Entry(root, textvariable=charge, width=10, state=tk.DISABLED).grid(row=12, column=4)

root.mainloop()