🐍 Python基础

32个趣味项目 | 从零开始学Python | 适合中小学生

📚 课程目录

1-Hello,World! 2-小蟒蛇学计算 3-计算年龄 4-几何图形的面积 5-猜密码 6-猜大小 7-偶数 8-质数 9-加法表 10-闰年 11-星座查询器 12-汉译英 13-属相查询器 14-六十花甲 15-排序 16-口算训练器 17-随机出题器 18-点和直线 19-点和直线的组合 20-奥运五环 21-图章和克隆 22-光标键绘图 23-鼠标绘图 24-多边形的绘制和填充 25-互动多边形 26-词频分析 27-音乐 28-二维码 29-安全密码 30-猜拳 31-T恤选择器 32-查询成绩

📘 1-Hello,World!

📊 程序流程图
开始 → 输出"Hello,World!" → 结束
print("Hello,World!")
📖 知识点: print()输出函数、字符串、转义字符。命令行模式标志为">>>"。
语句功能
print("Yes!Python")输出字符串
print(99)输出数字
print('我的电话是:',tel,'我的邮编是:',code)合并输出

📘 2-小蟒蛇学计算

📊 程序流程图
开始 → a=6,b=9 → 输出a+"+"+b+"="+(a+b) → 结束
a = 6
b = 9
print(a, '+', b, '=', a + b)
📖 算术运算符: +加、-减、*乘、/除、%取余、**幂、//取商整
运算符示例结果
+20+525
%21%51
**2**532
//24//54

📘 3-计算年龄

📊 程序流程图
开始 → 输入出生年份year → age=2020-int(year) → 输出age → 结束
a = input("请输入你的出生年份(如:2012):")
b = 2020 - int(a)
print("你2020年的岁数是:", b, '岁')
📖 数据类型转换: str()转字符串、int()转整型、float()转浮点数

📘 4-几何图形的面积

📊 程序流程图
开始 → 输入边长a,b → 面积s=a*b → 输出面积 → 结束
a = int(input('请输入矩形的第一条边长a(cm):'))
b = int(input('请输入矩形的第二条边长b(cm):'))
s = a * b
print("矩形的面积是:", s, '平方厘米')

📘 5-猜密码

📊 程序流程图
开始 → 预设密码pw="999" → 输入密码a → a==pw? → 是:输出正确并退出 / 否:输出错误并重新输入
pw = "999"
while 1:
a = input("请输入密码(三位数):")
if (a == pw):
print("密码正确!")
break
else:
print("密码错误!")
📖 比较运算符: ==等于、!=不等于、>大于、<小于、>=大于等于、<=小于等于

📘 6-猜大小

📊 程序流程图
开始 → 生成随机数g → 输入猜测数a → a>g:大了 / a
import random
g = random.randint(0, 9)
while 1:
a = int(input("猜一猜这个数(0~9):"))
if a > g: print("大了")
elif a < g: print("小了")
else: print("正确!"); break
📖 随机函数: random.randint(a,b)生成a到b之间的随机整数(包含a和b)

📘 7-偶数

📊 程序流程图
开始 → 创建文件"偶数.txt" → for a in range(1,20) → a%2==0? → 写入文件 → 结束
with open("偶数.txt", "w") as f:
for a in range(1, 20):
if a % 2 == 0:
f.write(str(a))
f.write(',')
📖 range()函数: range(start,stop,step)生成数字序列。如range(1,20)生成1~19。

📘 8-质数

with open("质数.txt", "w") as f:
for a in range(2, 20):
c = 0
b = 2
while not b > a:
if a % b == 0: c = c + 1
b = b + 1
if c < 2:
f.write(str(a))
f.write(',')
📖 质数定义: 只有1和它本身两个因数的自然数。

📘 9-加法表

with open("加法表.txt", "w") as f:
for a in range(1, 10):
for b in range(a, 10):
t = str(a)+'+'+str(b)+'='+str(a+b)
f.write(t+'\t')
f.write('\n')
📖 转义字符: \n换行、\t制表符、\\反斜杠、\'单引号、\"双引号

📘 10-闰年

while 1:
x = int(input('请输入年份:'))
if x % 400 == 0:
print(x,'年是闰年。')
elif x % 4 == 0 and x % 100 != 0:
print(x,'年是闰年。')
else:
print(x,'年不是闰年。')
📖 闰年规则: 能被400整除,或能被4整除但不能被100整除。

📘 11-星座查询器

while 1:
x = float(input('请输入出生日期(如:3.12):'))
if 3.21 <= x <= 4.19: print('白羊座')
elif 4.20 <= x <= 5.20: print('金牛座')
# ... 其他星座判断
📖 多分支语句: if...elif...else
星座日期星座日期
白羊座3.21-4.19天秤座9.23-10.23
金牛座4.20-5.20天蝎座10.24-11.22
双子座5.21-6.21射手座11.23-12.21
巨蟹座6.22-7.22摩羯座12.22-1.19

📘 12-汉译英

d = {0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'}
while 1:
t = int(input('输入:'))
print(d.get(t))
📖 字典: 字典用{}定义,键值对用冒号分隔,用get()方法安全访问。

📘 13-属相查询器

sx = ['猴','鸡','狗','猪','鼠','牛','虎','兔','龙','蛇','马','羊']
year = int(input('输入出生年份:'))
print(f'{year}年属相:{sx[year%12]}')
📖 列表: 列表用[]定义,索引从0开始。

📘 14-六十花甲

tian = ['甲','乙','丙','丁','戊','己','庚','辛','壬','癸']
di = ['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥']
with open("六十花甲.txt","w") as f:
for i in range(60):
f.write(tian[i%10]+di[i%12]+'\t')

📘 15-排序

l = []
for i in range(5):
l.append(int(input('输入整数:')))
l.sort()
print('递增:',l)
l.sort(reverse=True)
print('递减:',l)
📖 列表排序: sort()升序,sort(reverse=True)降序。

📘 16-口算训练器

import random
while 1:
a = random.randint(1,9)
b = random.randint(1,9)
print(f'{a}+{b}=?')
c = int(input())
if c==a+b: print('正确!')
else: print('错误!')

📘 17-随机出题器

import random, keyboard
def chu():
a = random.randint(2,100)
b = random.randint(2,a)
print(f'{a}/{b}=?')
keyboard.add_hotkey('space',chu)
keyboard.wait()
📖 keyboard库: 需要先安装:pip install keyboard

📘 18-点和直线

import turtle
turtle.dot(300,'yellow')
turtle.dot(250,'brown')
turtle.dot(200,'pink')
turtle.dot(150,'orange')
turtle.dot(100,'red')
turtle.dot(50,'black')
turtle.dot(10,'white')
📖 turtle绘图: dot()绘制点,pensize()设置笔粗,penup()/pendown()抬笔/落笔。

📘 19-点和直线的组合

from turtle import *
colors=['red','green','yellow','blue','orange','pink']
pensize(5)
for i in range(6):
fd(200)
dot(80,colors[i%6])
left(60)
write("六色环",font=("楷体",28))

📘 20-奥运五环

from turtle import *
colors=['blue','black','red','yellow','green']
pensize(12)
for i in range(3):
penup(); goto(i*180,0); pendown()
pencolor(colors[i%5]); circle(80)
penup(); goto(90,-90); pendown()
for i in range(3,5):
pencolor(colors[i%5]); circle(80)
penup(); fd(180); pendown()

📘 21-图章和克隆

from turtle import *
screensize(500,500)
register_shape('行人.gif')
shape('行人.gif')
penup(); goto(-250,-250)
for i in range(4):
for a in range(6):
clone(); fd(90)
left(90)

📘 22-光标键绘图

from turtle import *
shape('turtle'); color('red'); shapesize(3); pensize(8)
def tr(): right(45)
def tl(): left(45)
def f(): fd(100)
def b(): bk(100)
onkeypress(tr,'Right')
onkeypress(tl,'Left')
onkeypress(f,'Up')
onkeypress(b,'Down')
listen()

📘 23-鼠标绘图

from turtle import *
shape('turtle'); shapesize(6); color('blue'); pensize(10)
def L(x,y): left(45)
def R(x,y): right(45)
def F(x,y): fd(50)
onscreenclick(L,1)
onscreenclick(F,2)
onscreenclick(R,3)

📘 24-多边形的绘制和填充

from turtle import *
pensize(12)
color('red','blue')
begin_fill()
for i in range(6):
fd(200); left(60)
end_fill()
📖 填充: begin_fill()开始填充,end_fill()结束填充,color()设置画笔和填充颜色。

📘 25-互动多边形

from turtle import *
setup(width=1800,height=1100)
speed(10)
while 1:
a = int(numinput("边数","请输入正多边形边数:",3,minval=3,maxval=20))
clear()
for i in range(a):
fd(150); left(360/a)

📘 26-词频分析

import jieba
txt = open("steel.txt","r",encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word)==1: continue
counts[word] = counts.get(word,0)+1
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True)
for i in range(10):
word,count = items[i]
print(f"{word:<10}{count:>5}")
📖 需要安装: pip install jieba wordcloud matplotlib

📘 27-音乐

import pysynth_e
mlist = (('e5',2),('a4',4),('c5',2),('e5',2),('d5',4),('a4',2))
pysynth_e.make_wav(mlist,bpm=180,fn="音乐.wav")
📖 音色库: pysynth_s吉他、pysynth_e电子钢琴、pysynth_b钢琴、pysynth_d木管

📘 28-二维码

import qrcode
img = qrcode.make('http://www.csdsf.com')
img.save("csdsf.png")
📖 需要安装: pip install qrcode

📘 29-安全密码

# 加密
while 1:
x = input('输入明文:')
for ch in x:
print(ord(ch)+20)
# 解密
while 1:
a = int(input('输入密文:'))
print(chr(a-20))
📖 ord()和chr(): ord('a')返回97,chr(97)返回'a'

📘 30-猜拳

import random
choices = {1:'剪刀',2:'石头',3:'布'}
while 1:
a = int(input('请出拳(1剪刀 2石头 3布):'))
b = random.randint(1,3)
print(f'你出{choices[a]},电脑出{choices[b]}')
if a==b: print('平局')
elif (a==1 and b==3) or (a==2 and b==1) or (a==3 and b==2):
print('你赢了!')
else: print('你输了!')

📘 31-T恤选择器

import random, keyboard
txk = ['红','绿','橙','白','蓝','黄']
ls = 1
while 1:
keyboard.wait('space')
xc = random.randint(0,len(txk)-1)
print(f'第{ls}轮:你选中的颜色是:{txk[xc]}')
del txk[xc]
if len(txk)==0:
txk = ['红','绿','橙','白','蓝','黄']
ls += 1

📘 32-查询成绩

from openpyxl import load_workbook
name = input('输入学生姓名:')
wb1 = load_workbook('上学期成绩册.xlsx')
st1 = wb1['Sheet1']
for row in range(1, st1.max_row+1):
if st1.cell(row,1).value == name:
print(f'上学期{name}成绩:{st1.cell(row,2).value}')
📖 需要安装: pip install openpyxl

📖 附录:Python基础知识速查表

分类内容
算术运算符+ - * / % ** //
比较运算符== != > < >= <=
逻辑运算符and or not
数据类型转换int() str() float()
控制语句if...elif...else, while, for...in
列表操作append(), sort(), len(), max(), min()
字典操作get(), keys(), values(), items()
文件操作with open() as f: f.read() / f.write()
随机函数random.randint(a,b), random.choice(list)
turtle绘图fd(), bk(), left(), right(), goto(), dot(), circle(), color()