一些关于Python的简单项目1

随机投掷骰子

#掷骰子游戏  
# import random  
#  
# print("欢迎来到掷骰子游戏")  
# a = 1  
# b = 2  
# f = False  
# ans1 = 0  
# ans2 = 0  
# while ans1<=20 and ans2<=20:  
#     if f==False:  
#         print(f'请玩家{a}按Enter键投掷骰子')  
#         if input()=='':  
#             x = random.randint(1,7)  
#             print(x)  
#             ans1 += x  
#             f = True  
#     else:  
#         print(f'请玩家{b}按Enter键投掷骰子')  
#         if input() == '':  
#             x = random.randint(1, 7)  
#             print(x)  
#             ans2 += x  
#             f = False  
#  
# print(ans1,ans2)  
#  
# if ans1>=ans2:  
#     print("玩家1获胜")  
# else:  
#     print("玩家2获胜")  
  
import random  
def num():  
    return random.randint(1,7);  
  
def show(num):  
    print("+-------+")  
    print("|       |")  
    # print("|       |")  
    print(f"|   {num}   |")  
    print("|       |")  
    print("+-------+")  
  
  
def main():  
    a = 1  
    b = 2  
    f = False  
  
    ans1 = 0  
    ans2 = 2  
    while ans1 <= 20 and ans2 <= 20:  
        if f == False:  
            print(f'请玩家{a}按Enter键投掷骰子')  
            if input() == '':  
                x = num()  
  
                show(x)  
  
                ans1 += x  
                f = True  
        else:  
            print(f'请玩家{b}按Enter键投掷骰子')  
            if input() == '':  
                x = num()  
                show(x)  
  
                ans2 += x  
                f = False  
  
    print(ans1, ans2)  
  
    if ans1 >= ans2:  
        print("玩家1获胜")  
    else:  
        print("玩家2获胜")  
  
if __name__ == "__main__":  
    main()

统计单词并生成条形图

import matplotlib.pyplot as plt  
from collections import Counter  
import re  
  
  
def count_words(text):  
    # 使用正则表达式移除非字母字符  
    words = re.findall(r'\b\w+\b', text)  
  
    # 使用Counter统计单词出现的次数  
    word_counts = Counter(words)# 返回的是key-value键值对  
  
    return word_counts  
  
  
def plot_word_counts(word_counts):  
    # 获取单词和对应的次数  
    words = list(word_counts.keys())  
    counts = list(word_counts.values())  
  
    # 创建一个条形图  
    plt.figure(figsize=(10, 5))  
    plt.bar(words, counts)  
    plt.xlabel('Words')  
    plt.ylabel('Counts')  
    plt.title('Word Frequency')  
    plt.show()  
  
  
# 输入文本  
text = "Nihao wo shi du meng tian"  
  
# 统计单词出现的次数  
word_counts = count_words(text)  
  
# 绘制词频统计图  
plot_word_counts(word_counts)

烤羊肉串

import datetime  
  
  
  
print("欢迎来到烧烤店")  
  
list=[]  
f = False  
  
a =True  
while a:  
    print("1.烤羊肉串")  
    print("2.添加调料")  
    print("3.查看羊肉串状态")  
    print("4.退出")  
    a = int(input("请选择操作(1-4):"))  
    if  a==4:  
        a = False  
    elif a == 1:  
        f = True  
        print("请输入烤的时间(minute):")  
        x = int(input())  
        nowtime1 = datetime.datetime.now()  
        print(f'你的羊肉串要烤{x}分钟')  
        '''  
        print(f"羊肉已经烤了{x}分钟")  
                  
        '''  
    elif a == 2:  
        if f==False:  
            print("你还没有烤羊肉串")  
            continue  
  
        print("请输入需要添加的调料:")  
        str = input()  
        list.append(str)  
        print(f"成功添加调料:{str}")  
        print("当前羊肉串上的调料有")  
        for i in list:  
            print(i,end=" ")  
        print()  
    elif a == 3:  
        if f == False:  
            print("你还没有烤羊肉串")  
            continue  
  
        nowtime2 = datetime.datetime.now()  
        res = (nowtime2-nowtime1).seconds #获取当前时间,与我们之前刚烧烤的时间做一个差,得到时间差  
  
        res /= 60  
        print(f"已经过去{res}分钟")  
          
        if res < 5:  
            print("羊肉串还是生的")  
        elif res>=5 and res<10:  
            print("羊肉串半生不熟")  
        elif res>=10 and res < 15:  
            print("羊肉串熟了")  
        else:  
            print("烤糊了")  
        '''  
        if x < 5:            print("羊肉串还是生的")  
        elif x>=5 and x<10:            print("羊肉串半生不熟")  
        elif x>=10 and x < 15:            print("羊肉串熟了")  
        else:            print("烤糊了")  
        '''
	```
## 下井字棋游戏
```Python
# list = [[]for i in range(3)] #创建一个二维空列表  
# # for i in range(3):  
# #     print(list[i])  
# list[1][1].append(2)  
# for i in range(3):  
#     print(list[i])  
list = []  
for i in range(3):  
    list1 = []  
    for j in range(3):  
        list1.append(None)  
    list.append(list1)  
  
# list[1][1]=2  
# print(list[1][1])  
  
def show(): #显示图  
    print("---------")  
    for i in range(3):  
        for j in range(3):  
            if list[i][j] == None:  
                if j != 2:  
                    print(" ",end="|")  
                else:  
                    print(" ",end="")  
            else:  
                if j != 2:  
                    print(list[i][j],end="|")  
                else:  
                    print(list[i][j],end="")  
        print()  
        print("---------")  
  
  
  
  
def Play(x):  
    print(f'请玩家{x}输入选择的位置')  
    row = int(input("请输入行号(0-2):"))  
    col = int(input("请输入列号(0-2):"))  
    if x == 1:  
        if list[row][col] !=None:  
            print("该地方已被占用,请重新选择")  
            Play(x)  
            return 2  
        else:  
            list[row][col] = 'x'  
            show()  
            return 2  
  
  
    else:  
        if list[row][col] != None:  
            print("该地方已被占用,请重新选择")  
            Play(x)  
            return 1  
  
        else:  
            list[row][col] = 'o'  
            show()  
            return 1  
  
def Judge():  
    # 行判断  
    for i in range(3):  
        if list[i][0] == list[i][1] == list[i][2] and list[i][1] != None:  
            if list[i][0] =='x':  
                return 1  
            else:  
                return 2  
        else:  
            continue  
    # 列判断  
    for i in range(3):  
        if list[0][i] == list[1][i] == list[2][i] and list[0][i] != None:  
            if list[0][i] =='x':  
                return 1  
            else:  
                return 2  
        else:  
            continue  
  
    # 对角线  
    if list[0][0] == list[1][1] ==list[2][2] and list[1][1] != None:  
        if list[0][0] == 'x':  
            return 1  
        else:  
            return 2  
    if list[0][2] == list[1][1] == list[2][0] and list[1][1] != None:  
        if list[0][0] == 'x':  
            return 1  
        else:  
            return 2  
    return None  
  
def main():  
    Winner = None  
    x=int(input("请输入谁是先手:"))  
    l=1  
  
    while Winner == None and l<=9:  
        x = Play(x)  
        Winner = Judge()  
        l+=1  
  
    if Winner !=  None:  
        print(f'获胜者是{Winner}')  
        print("你服不服?")  
        str = input()  
        if(str=='我不服'):  
            main()  
        else:  
            pass  
  
  
    else:  
        print("平局")  
  
if __name__ == "__main__":  
    main()

电子商务系统

不带商品类的版本,就是简单用字典存一下

# class commodity(): #     def __init__(self,str,price):  
#         self.str = str  
#         self.price = price  
#         #这里是商品的类  
  
#这里做了一个商品的字典,包括金额  
shangpin = {'衣服':150,'零食':30,'饮料':40,'玩具':80}  
  
  
class shopping(): #购物车类  
    list = []  
    ans = 0  
  
    def __init__(self,ans,list):  
        self.ans = ans  
        self.list = list  
  
    def add(self): #添加函数  
        print(shangpin)  
        print("请输入添加的商品个数:")  
  
        c = int(input())  
        for i in range(c):  
            print("请输入商品的名称:")  
            str = input()  
            while str not in shangpin:  
                print("该商品不存在,请重新选择")  
                str = input()  
  
  
            self.list.append(str)  
            self.ans += shangpin[str]  
               
            # self.list.append(str)  
            # print("请输入商品的价格:")  
            # x = int(input())            # self.ans += shangpin[str]  
    def Show(self): #显示购物车  
        print("购物车商品有:")  
        for i in self.list:  
            print(i,end=" ")  
        print()  
  
        print(f"购物车中总金额为:{self.ans}")  
  
    def Clear(self): #清空购物车之后所有都需要回到初始状态  
        self.ans = 0  
        self.list = []  
  
    def Payment(self): #支付金额  
        print(f"你需要支付的金额是{self.ans}")  
        print("是否要支付(Yes/No)")  
        str1 = input()  
        if str1 == "Yes":  
            print("请输入你支付金额:")  
            x1 = int(input())  
            res = x1-self.ans  
            if res < 0:  
                print(f"你的支付金额不够,需要再支付{res*-1}元")  
            else:  
                print(f'需要向你找零{res}元')  
                self.clear()  
        else:  
            print("你取消了支付")  
  
  
  
def show(): #显示操作列表  
    print("==========")  
    print("1.查看商品")  
    print("2.添加商品到购物车")  
    print("3.查看购物车")  
    print("4.结账")  
    print("5.退出")  
    print("请选择操作(1/2/3/4/5)")  
  
def main():  
    f = True  
    ShoppingCar = shopping(0,[])  
  
    while f:  
        show()  
        x=int(input())  
        if x == 5:  
            f = False  #这里可以直接写成break
        elif x == 1:  
            print(shangpin)  
        elif x == 2:  
            ShoppingCar.add()  
  
        elif x == 3:  
            ShoppingCar.Show()  
  
        elif x == 4:  
            ShoppingCar.Payment()  
  
  
  
if __name__ == '__main__': #执行主函数  
    main()

带商品类的版本

# class commodity():  
#     def __init__(self,str,price):  
#         self.str = str  
#         self.price = price  
#         #这里是商品的类  
  
#这里做了一个商品的字典,包括金额  
# shangpin = {'衣服':150,'零食':30,'饮料':40,'玩具':80}  
shangpin = []  
  
#好吧刚读懂题意,还得给商品定义一个类,有id,名字,价格,库存  
class commodity():  
    def __init__(self,id,str,price,kucun):  
        self.str = str  
        self.price = price  
        self.id = id  
        self.kucun = kucun  
        #这里是商品的类  
  
def init():  
    shangpin.append(commodity(1,"电视",499.99,10))  
    shangpin.append(commodity(2, "手机", 699.99, 15))  
    shangpin.append(commodity(3, "耳机", 99.99, 20))  
    shangpin.append(commodity(4, "笔记本电脑", 1299.99, 5))  
  
def show1():#显示库存  
    for i in shangpin:  
        print(f"ID:{i.id},商品名:{i.str},价格:{i.price},库存:{i.kucun}")  
  
class shopping(): #购物车类  
    list = []  
    ans = 0  
  
    def __init__(self,ans,dict1):  
        self.ans = ans  
        self.dict1 = dict1  
  
    def add(self): #添加函数  
       # print(shangpin)  
        show1()  
        print("请输入填加商品的种数:")  
  
        c = int(input())  
        for i in range(c):  
            print("请输入商品的ID:")  
            id1 = int(input())  
  
            for i in shangpin:  
                if id1 == i.id:  
                    print("请输入购买的数量:")  
                    num = int(input())  
                    if num > i.kucun:  
                        print("库存不够")  
                    else:  
                        i.kucun -= num  
                        # str2 = i.str  
                        if i.str in self.dict1:#这里还需要判断字典中是不是有这个键值对  
                            self.dict1[i.str] += num  
                        else:  
                            self.dict1[i.str] = num  
                        # self.dict1[str2]+=num  
                        self.ans += i.price*num  
  
            # self.list.append(str)  
            # print("请输入商品的价格:")  
            # x = int(input())            # self.ans += shangpin[str]  
    def Show(self): #显示购物车  
        if self.dict1 == {}:  
            print("你还没有添加商品")  
            return  
        print("购物车商品有:")  
        for i in self.dict1:  
            print(f"商品名字:{i},商品数量{self.dict1[i]}")  
        #print()  
  
        print(f"购物车中总金额为:{self.ans}")  
  
    def Clear(self): #清空购物车之后所有都需要回到初始状态  
        self.ans = 0  
        self.dict1 = dict()  
  
    def Payment(self): #支付金额  
        print(f"你需要支付的金额是{self.ans}")  
        print("是否要支付(Yes/No)")  
        str1 = input()  
        if str1 == "Yes":  
            print("请输入你支付金额:")  
            x1 = int(input())  
            res = x1-self.ans  
            if res < 0:  
                print(f"你的支付金额不够,需要再支付{res*-1}元")  
            else:  
                print(f'需要向你找零{res}元')  
                self.clear()  
        else:  
            print("你取消了支付")  
  
  
  
def show(): #显示操作列表  
    print("==========")  
    print("1.查看商品")  
    print("2.添加商品到购物车")  
    print("3.查看购物车")  
    print("4.结账")  
    print("5.退出")  
    print("请选择操作(1/2/3/4/5)")  
  
def main():  
    init()  
  
    f = True  
    ShoppingCar = shopping(0, {})  
  
    while f:  
        show()  
        x=int(input())  
        if x == 5:  
            f = False #这里可以直接写成break  
        elif x == 1:  
            show1()  
  
        elif x == 2:  
            ShoppingCar.add()  
  
        elif x == 3:  
            ShoppingCar.Show()  
  
        elif x == 4:  
            ShoppingCar.Payment()  
  
  
  
if __name__ == '__main__': #执行主函数  
    main()
posted @ 2023-12-22 10:52  du463  阅读(15)  评论(0编辑  收藏  举报