15个经典基础Python练手案例,基本功就是这样练成的

简介: 15个经典基础Python练手案例,基本功就是这样练成的

前言
大家好,我是辣条哥~

我翻看以前有给大家更新过不少小练手项目,但是逐渐发现很多人连最基础的都不知道,于是乎今天给大家安排十五个经典的练手案例,希望大家继续喜欢,当然要是放在收藏夹起灰也是可以的~

另外大家也可以进到我主页找到更多的项目案例

以及我的一些详细笔记分享:《点击蓝色字体跳转至主页》

目录
前言
一、 猜拳游戏
二、 计算1~100的累加和(包含1和100)
三、计算1~100之间偶数的累加和(包含1和100)
四、打印如下图形:
五、打印三角形
六、学校办公室分配
七、函数封装(一)
八、函数封装(二)
九、学员管理系统
十、九九乘法表
十一、制作文件的备份
十二、批量修改文件名
十三、斐波那契数列
十四、水仙花数
十五、实现冒泡排序
一、 猜拳游戏
需求:
1、从控制台输⼊要出的拳 —— ⽯头(1)/剪⼑(2)/布(3)
2、电脑 随机 出拳 —— 先假定电脑只会出⽯头,完成整体代码功能
3、⽐较胜负

参考代码:

import random

player = input('请输入:剪刀(0) 石头(1) 布(2):')

player = int(player)

产生随机整数:0、1、2 中的某一个

computer = random.randint(0,2)

用来进行测试

print('player=%d,computer=%d',(player,computer))

if ((player == 0) and (computer == 2)) or ((player ==1) and (computer == 0)) or ((player == 2) and (computer == 1)):

print('获胜,哈哈,你太厉害了')

elif player == computer:

print('平局,要不再来一局')

else:

print('输了,不要走,洗洗手接着来,决战到天亮')

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
二、 计算1~100的累加和(包含1和100)
参考代码:

encoding=utf-8

i = 1
sum = 0
while i <= 100:

sum = sum + i
i += 1

print("1~100的累积和为:%d" % sum)
1
2
3
4
5
6
7
8
9
三、计算1~100之间偶数的累加和(包含1和100)
参考代码:

encoding=utf-8

i = 1
sum = 0
while i <= 100:

if i % 2 == 0:
    sum = sum + i
i+=1

print("1~100的累积和为:%d" % sum)
1
2
3
4
5
6
7
8
9
10
四、打印如下图形:






1
2
3
4
5
参考代码:

i = 1
while i <= 5:

j = 1
while j <= 5:
    print("*", end=" ")
    j += 1
print()

i += 1

1
2
3
4
5
6
7
8
9
五、打印三角形



1
2
3
4
5
参考代码:

i = 1
while i <= 5:

j = 1
while j <= i:
    print("*", end=" ")
    j += 1
print()

i += 1

1
2
3
4
5
6
7
8
9

六、学校办公室分配
一个学校,有3个办公室,现在有8位老师等待工位的分配,请编写程序,完成随机的分配
参考代码:

encoding=utf-8

import random

定义一个列表用来保存3个办公室

offices = [[],[],[]]

定义一个列表用来存储8位老师的名字

names = ['A','B','C','D','E','F','G','H']

i = 0
for name in names:

index = random.randint(0,2)    
offices[index].append(name)

i = 1
for tempNames in offices:

print('办公室%d的人数为:%d'%(i,len(tempNames)))
i+=1
for name in tempNames:
    print("%s"%name,end='')
print("\n")
print("-"*20)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
七、函数封装(一)
1.写一个函数打印一条横线
2.打印自定义行数的横线
参考代码:

打印一条横线

def printOneLine():

print("-"*30)

打印多条横线

def printNumLine(num):

i=0

# 因为printOneLine函数已经完成了打印横线的功能,
# 只需要多次调用此函数即可
while i<num:
    printOneLine()
    i+=1

printNumLine(3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
八、函数封装(二)
1.写一个函数求三个数的和
2.写一个函数求三个数的平均值
参考代码:

求3个数的和

def sum3Number(a,b,c):

return a+b+c # return 的后面可以是数值,也可是一个表达式

完成对3个数求平均值

def average3Number(a,b,c):

# 因为sum3Number函数已经完成了3个数的就和,所以只需调用即可
# 即把接收到的3个数,当做实参传递即可
sumResult = sum3Number(a,b,c)
aveResult = sumResult/3.0
return aveResult

调用函数,完成对3个数求平均值

result = average3Number(11,2,55)
print("average is %d"%result)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
九、学员管理系统

学生的信息可以使用一个字典类型

管理学生可以使用列表

定义全局变量学生列表

student_list = [] # list()

print("全局变量:", id(student_list))

显示功能菜单的函数

def show_menu():

print("-----学生管理系统v1.0-----")
print("1. 添加学生")
print("2. 删除学生")
print("3. 修改学生信息")
print("4. 查询学生信息")
print("5. 显示所有学生信息")
print("6. 退出")

添加学生

def add_student():

name = input("请输入学生的姓名:")
age = input("请输入学生的年龄:")
sex = input("请输入学生的性别:")

# 定义学生字典类型的变量
student_dict = {} # dict()
# 把学生的信息使用字典进行存储
student_dict["name"] = name
student_dict["age"] = age
student_dict["sex"] = sex
# 这里可以不使用global因为列表是可变类型,可以在原有数据的基础上进行修改,内存地址不变
# 因为列表的内存地址不变,全局变量不需要使用global
# 加上global表示内存地址要发生变化

# 把学生信息添加到学生列表中
student_list.append(student_dict)
# global student_list
# # student_list = [{'name': "李四", "age":"18", "sex":"男"}]
# student_list.append(student_dict)

显示所有学生信息

def show_all_student():

# print(student_list, id(student_list))
for index, student_dict in enumerate(student_list):
    # 学号和下标的关系
    student_no = index + 1

    print("学号:%d 姓名:%s 年龄:%s 性别:%s" % (student_no, student_dict["name"],
                                       student_dict["age"], student_dict["sex"]))

删除学生信息

def remove_student():

student_no = int(input("请输入要删除学生的学号:"))
# 获取学生字典信息的下标
index = student_no - 1
if index >= 0 and index < len(student_list):
    # 根据下标删除学生信息
    del student_list[index]
else:
    print("请输入正确的学号")

修改学生信息

def modify_student():

student_no = int(input("请输入要修改学生的学号:"))
# 根据学号计算下标
index = student_no - 1

if index >= 0 and index < len(student_list):
    # 根据下标获取学生字典信息
    student_dict = student_list[index]

    name = input("请输入您修改后的名字:")
    age = input("请输入您修改后的年龄:")
    sex = input("请输入您修改后的性别:")

    student_dict["name"] = name
    student_dict["age"] = age
    student_dict["sex"] = sex
else:
    print("请输入正确的学号")

查询学生

def search_student():

name = input("请输入要查询的学生姓名:")

# 遍历学生列表信息
for index, student_dict in enumerate(student_list):
    # pass # 空实现
    if student_dict["name"] == name:
        student_no = index + 1
        # 说明找到了这个学生
        print("学号:%d 姓名:%s 年龄:%s 性别:%s" % (student_no, student_dict["name"],
                                           student_dict["age"], student_dict["sex"]))
        break
else:
    print("对不起,没有找到这个学生")

程序启动的函数

def run():

while True:
    # 显示功能菜单
    show_menu()
    # 接收用户的指令
    menu_option = input("请输入您需要的功能选项:")

    if menu_option == "1":
        print("添加学生")
        add_student()
    elif menu_option == "2":
        print("删除学生")
        remove_student()
    elif menu_option == "3":
        print("修改学生信息")
        modify_student()
    elif menu_option == "4":
        print("查询学生信息")
        search_student()
    elif menu_option == "5":
        print("显示所有学生信息")
        show_all_student()
    elif menu_option == "6":
        print("退出")
        break

执行程序启动的函数

run()

1
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
十、九九乘法表
参考代码:

i=1
while i<=9:

j=1
while j<=i:
    print('{}*{}={}'.format(j,i,i*j),end=' ')
    j+=1
print()
i+=1

1
2
3
4
5
6
7
8

十一、制作文件的备份
输入文件的名字,然后程序自动完成对文件进行备份
参考代码:

提示输入文件

oldFileName = input("请输入要拷贝的文件名字:")

以读的方式打开文件

oldFile = open(oldFileName,'rb')

提取文件的后缀

fileFlagNum = oldFileName.rfind('.')
if fileFlagNum > 0:

fileFlag = oldFileName[fileFlagNum:]

组织新的文件名字

newFileName = oldFileName[:fileFlagNum] + '[复件]' + fileFlag

创建新文件

newFile = open(newFileName, 'wb')

把旧文件中的数据,一行一行的进行复制到新文件中

for lineContent in oldFile.readlines():

newFile.write(lineContent)

关闭文件

oldFile.close()
newFile.close()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
十二、批量修改文件名
把已经存在的文件进行批量的修改
参考代码:

coding=utf-8

批量在文件名前加前缀

import os

funFlag = 1 # 1表示添加标志 2表示删除标志
folderName = './renameDir/'

获取指定路径的所有文件名字

dirList = os.listdir(folderName)

遍历输出所有文件名字

for name in dirList:

print(name)

if funFlag == 1:
    newName = '[图灵]_' + name
elif funFlag == 2:
    num = len('[图灵]_')
    newName = name[num:]
print(newName)

os.rename(folderName+name, folderName+newName)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
十三、斐波那契数列
参考代码

1 def fibonacci():
2 num = input("Please input your number\n")
3 i,a,b= 0,0,1 //赋值
4 if int(num) < 0:
5 print("你输入的数据不合理")
6 elif int(num)== 1:
7 print(a)
8 else:
9 while i < int(num):
10 print(a)
11 #sum = a+b
12 #a = b
13 #b = sum
14 a, b = b, a + b #a, b = b, a + b这里不能写成 a=b b=a+b,如果写成这样,b就不是前两位相加的值,而是已经被b赋过值的a和b相加的值
15 i+=1
16 fibonacci()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
十四、水仙花数
参考代码:

for n in range(100,1000):

i = n // 100

j = n // 10 % 10

k = n % 10

if n == i ** 3 + j ** 3 + k ** 3:

    print (n)

1
2
3
4
5
6
7
8
9
10
11
十五、实现冒泡排序
冒泡排序(Bubble Sort)是一种常见的排序算法,相对来说比较简单。

冒泡排序重复地走访需要排序的元素列表,依次比较两个相邻的元素,如果顺序(如从大到小或从小到大)错误就交换它们的位置。重复地进行直到没有相邻的元素需要交换,则元素列表排序完成。
参考代码:

coding=utf-8

def bubble_sort(array):

for i in range(1, len(array)):
    for j in range(0, len(array)-i):
        if array[j] > array[j+1]:
            array[j], array[j+1] = array[j+1], array[j]
return array

if name == '__main__':

array = [10, 17, 50, 7, 30, 24, 27, 45, 15, 5, 36, 21]
print(bubble_sort(array))

1
2
3
4
5
6
7
8
9
10
11
12

————————————————

目录
相关文章
|
15天前
|
Python
python集合的创建案例分享
【4月更文挑战第11天】在Python中,通过大括号或`set()`函数可创建集合。示例包括:使用大括号 `{}` 创建带元素的集合,如 `{1, 2, 3, 4, 5}`;使用 `set()` 函数从列表转换为集合,例如 `set([1, 2, 3, 4, 5])`,以及创建空集合 `set()`。当元素有重复时,集合会自动去重,如 `set([1, 2, 2, 3, 4, 4, 5])`。但尝试将不可哈希元素(如列表、字典)放入集合会引发 `TypeError`。
17 1
|
19天前
|
Python
Python文件操作学习应用案例详解
【4月更文挑战第7天】Python文件操作包括打开、读取、写入和关闭文件。使用`open()`函数以指定模式(如'r'、'w'、'a'或'r+')打开文件,然后用`read()`读取全部内容,`readline()`逐行读取,`write()`写入字符串。最后,别忘了用`close()`关闭文件,确保资源释放。
18 1
|
2月前
|
数据采集 JSON JavaScript
Python爬虫案例:抓取猫眼电影排行榜
python爬取猫眼电影排行榜数据分析,实战。(正则表达式,xpath,beautifulsoup)【2月更文挑战第11天】
70 2
Python爬虫案例:抓取猫眼电影排行榜
|
1月前
|
JSON JavaScript 前端开发
Python中使用JsonPath:概念、使用方法与案例
Python中使用JsonPath:概念、使用方法与案例
44 0
|
3天前
|
人工智能 Python
【AI大模型应用开发】【LangChain系列】实战案例1:用LangChain写Python代码并执行来生成答案
【AI大模型应用开发】【LangChain系列】实战案例1:用LangChain写Python代码并执行来生成答案
8 0
|
8天前
|
机器学习/深度学习 人工智能 自然语言处理
总结几个GPT的超实用之处【附带Python案例】
总结几个GPT的超实用之处【附带Python案例】
|
11天前
|
Python
[重学Python]Day 2 Python经典案例简单习题6个
[重学Python]Day 2 Python经典案例简单习题6个
15 0
|
19天前
|
Python
Python数据类型学习应用案例详解
Python基础数据类型包括整数(int)、浮点数(float)、字符串(str)、布尔值(bool)、列表(list)、元组(tuple)、字典(dict)和集合(set)。整数和浮点数支持算术运算,字符串是不可变的文本,布尔值用于逻辑判断。列表是可变有序集合,元组不可变。字典是键值对的无序集合,可变,而集合是唯一元素的无序集合,同样可变。示例代码展示了这些类型的基本操作。
11 1
|
19天前
|
Python
Python控制结构学习应用案例详解
Python控制结构包含条件语句、循环语句和异常处理。条件语句用if-elif-else判断数字正负;for循环示例输出1到10的整数,while循环计算1到10的和;异常处理用try-except-finally处理除零错误,打印提示信息并结束。
10 3
|
19天前
|
Python
Python函数学习应用案例详解
【4月更文挑战第7天】学习Python函数的应用,包括计算两数之和、判断偶数、计算阶乘、生成斐波那契数列及反转字符串。示例代码展示了函数接收参数和返回结果的功能,如`add(a, b)`求和,`is_even(num)`判断偶数,`factorial(n)`计算阶乘,`fibonacci(n)`生成斐波那契数,以及`reverse_string(s)`反转字符串。
14 1