Python basic small project

Today, I will write a special basic Python small project for you. You are welcome to support and give your own perfect modifications
(because what I wrote is very basic, and the running speed is not very good.

1. Metro fare

topic

Subway ticket price
The price of subway transportation is adjusted to: 3 yuan within 6 kilometers (inclusive); 4 yuan from 6 kilometers to 12 kilometers (inclusive); 5 yuan from 12 kilometers to 22 kilometers (inclusive); 6 yuan from 22 kilometers to 32 kilometers (inclusive) ; For the part of more than 32 kilometers, every additional 1 yuan can be used for 20 kilometers.
If you use the municipal transportation card to swipe the rail transit, the price will be given a 20% discount for the trips after the accumulative expenditure of each card exceeds 100 yuan in each natural month; the price will be given a 50% discount for the trips that exceed 150 yuan; the cumulative expenditure reaches
400 No more discounts for rides after RMB 10000.

Requirements:
Assuming that every month, Xiao Ming needs to go to work for 20 days, and every time he goes to work, he needs to go back and forth once, that is, he needs to take the subway of the same route twice a day; when
Xiao Ming swipes the bus card for the first time at the beginning of each month, he will deduct 5 yuan ;
Write a program, get the distance from the keyboard, and help Xiaoming calculate the total monthly fee if the municipal transportation card is not used, and the total monthly fee of the municipal transportation card.

When I wrote this, I used a lot of if nesting, which was very inefficient

program source code

# 使用巨多if嵌套,效率很低
while True:
    day = 1
    j = 1
    money = 0
    print("== 请输入距离 或 按'q'退出 ==")
    distance = input(">>> ")   # 设置距离
    if distance.isdecimal():
        distance = int(distance)
        if distance > 0:
            print("\n== 是不是一卡通? 'y'是 'n'不是==")
            yikatong = input(">>>[y/n] ")
            if yikatong.lower() == "y":     #把输入的字母变成小写
                while day <= 20:
                    j = 1
                    while j <= 2:
                        if money < 100:
                            if distance <= 6:
                                money += 3
                            if distance > 6 and distance <= 12:
                                money += 4
                            if distance > 12 and distance <= 22:
                                money += 5
                            if distance > 22 and distance <= 32:
                                money += 6
                            if distance > 32:
                                money += ((distance - 33) // 20) + 6 + 1
                        elif money >= 100 and money < 150:
                            if distance <= 6:
                                money += 3 * 0.8
                            if distance > 6 and distance <= 12:
                                money += 4 * 0.8
                            if distance > 12 and distance <= 22:
                                money += 5 * 0.8
                            if distance > 22 and distance <= 32:
                                money += 6 * 0.8
                            if distance > 32:
                                money += (((distance - 33) // 20) + 6 + 1) * 0.8
                        elif money >= 150 and money < 400:
                            if distance <= 6:
                                money += 3 * 0.5
                            if distance > 6 and distance <= 12:
                                money += 4 * 0.5
                            if distance > 12 and distance <= 22:
                                money += 5 * 0.5
                            if distance > 22 and distance <= 32:
                                money += 6 * 0.5
                            if distance > 32:
                                money += (((distance - 33) // 20) + 6 + 1) * 0.5
                        elif money > 400:
                            if distance <= 6:
                                money += 3
                            if distance > 6 and distance <= 12:
                                money += 4
                            if distance > 12 and distance <= 22:
                                money += 5
                            if distance > 22 and distance <= 32:
                                money += 6
                            if distance > 32:
                                money += (((distance - 33) // 20) + 6 + 1)
                        j += 1
                    day += 1
                money += 5
                print("\n你的总花费为:%.4f元\n" % money)
            elif yikatong.lower() == "n":   #把输入的字母变成小写
                while day <= 20:
                    j = 1
                    while j <= 2:
                        if distance <= 6:
                            money += 3
                        if distance > 6 and distance <= 12:
                            money += 4
                        if distance > 12 and distance <= 22:
                            money += 5
                        if distance > 22 and distance <= 32:
                            money += 6
                        if distance > 32:
                            money += ((distance - 33) // 20) + 6 + 1
                        j += 1
                    day += 1
                money += 5
                print("你的总花费为:%.4f元" % money)
            else:
                print("\nXX 输入有误请重新输入 XX")
        else:
            print("必须大于0,请从新输入")
    elif distance.lower() == "q":
        break
    else:
        print("必须是数字,而且大于0,请从新输入")

run screenshot

insert image description here

2. Shopping cart

topic

shopping cart

The following product list
goods = [
{"name": "computer", "price": 1000},
{"name": "Iphone", "price": 1200},
{"name": "luxury car", "price ": 3280},
{"name": "Villa", "price": 6500},
{"name": "Yacht", "price": 5800},
{"name": "Beauty", "price": 2500},
]

Complete the following requirements:
Require the user to enter the total assets, including: 15000
Determine whether the entered amount can buy the product with the lowest price. If the user cannot re-enter, display the
product list, let the user select the product according to the serial number, and add it to the shopping cart
to view the shopping cart , if there is the same product in the shopping cart, do not display it repeatedly, and add a number after the product to indicate that there are two or more products in the shopping cart. When checking out, judge whether the shopping cart is
empty, and if it is empty, prompt to fill the shopping cart
Allow users to delete products in the shopping cart, or empty the shopping cart
. If the balance is insufficient during checkout, it will prompt that the account balance is insufficient

program source code


goods = [
    {
    
    "name": "电脑", "price": 1000},
    {
    
    "name": "Iphone", "price": 1200},
    {
    
    "name": "豪车", "price": 3280},
    {
    
    "name": "别墅", "price": 6500},
    {
    
    "name": "游艇", "price": 5800},
    {
    
    "name": "美女", "price": 2500},
]
while True:
    q = 0
    money = []
    shopping_cart = []
    for i, v in enumerate(goods, 1):
        money.append(v["price"])
    print("请输入您的总金额")
    salary = input(">>> ")
    if salary.isdecimal():  # 判断只让输入十进制数字
        salary = int(salary)
        money.sort()
        if salary <= 0:
            print("\n你玩我呢,没钱还来买\n")
            print("直接退出")
            break
        elif salary > 0 and salary < money[0]:  # 判断输入的金额能否购买价格最低的商品
            print("你的金额买不起任何一个东西\n")
        elif salary > money[0]:
            while True:
                all_price = 0
                print("\33[36;1m商品列表\33[1m".center(40, "="))
                for i, v in enumerate(goods, 1):
                    print("%d %s \33[34;1m%d\33[1m" % (i, v["name"].ljust(4, " "), v["price"]))
                print("请输入产品\33[31;1m序号\33[1m添加到购物车、返回上一层请按 \33[31;1mP \33[1m、完全退出请按 \33[31;1mQ\33[1m")
                seq_num = input(">>> ")
                if seq_num.lower() == "p":
                    break
                if seq_num.lower() == "q":
                    q = 1
                    break
                if seq_num.isdecimal():
                    seq_num = int(seq_num)
                    if seq_num > 0 and seq_num <= len(goods):
                        shopping_cart.append(goods[seq_num - 1])
                        for y in shopping_cart:
                            all_price += y["price"]
                        print("\33[33;1m%s\33[1m 已添加到购物车\n" % (goods[seq_num - 1]["name"]))
                        while True:
                            print("继续添加产品请按 \33[31;1mC\33[1m 、结算请按 \33[31;1mB\33[1m 、查看购物车请按 \33[31;1mS\33[1m 、完全退出请按 \33[31;1mQ\33[1m")
                            final_cho = input(">>> ")
                            if final_cho.lower() == "c":
                                break
                            elif final_cho.lower() == "b":
                                while True:
                                    print("您的余额为:\33[34;1m%d\33[1m 您购买的商品总价为:\33[34;1m%d\33[1m 确定购买吗? 确定 \33[31;1mY\33[1m 取消 \33[31;1mN\33[1m" % (salary, all_price))
                                    confirm_bill = input(">>> ")
                                    if confirm_bill.lower() == "y":
                                        if shopping_cart != []:
                                            if salary >= all_price:
                                                salary = salary - all_price
                                                print("购买成功\n")
                                                all_price = 0
                                                shopping_cart = []
                                                break
                                            elif salary < all_price:
                                                print("-_-!余额不足\n")
                                                break
                                        elif shopping_cart == []:
                                            print("购物车空空如也,填充后再来吧\n")
                                            break
                                    elif confirm_bill.lower() == "n":
                                        break
                                    else:
                                        print("输入有误,请重新输入\n")
                            elif final_cho.lower() == "s":
                                while True:
                                    print("\33[35;1m购物车\33[1m".center(40, "="))
                                    temp_cart = []
                                    for y in shopping_cart:
                                        if y not in temp_cart:
                                            temp_cart.append(y)
                                    for m, z in enumerate(temp_cart, 1):
                                        print("%d %s \33[34;1m%d\33[1m %d个" % (m, z["name"].ljust(4, " "), z["price"], shopping_cart.count(z)))
                                    print("\n购物车商品总金额为:\33[34;1m%d\33[1m" % all_price)
                                    print("您的余额为:\33[34;1m%d\33[1m" % salary)
                                    print("按\33[31;1m序号\33[1m可删除商品 、继续请按 \33[31;1mC\33[1m 、清空购物车请按 \33[31;1mE\33[1m")
                                    ctrl_shop_cart = input(">>> ")
                                    if ctrl_shop_cart.lower() == "c":
                                        break
                                    elif ctrl_shop_cart.lower() == "e":
                                        all_price = 0
                                        shopping_cart = []
                                        print("以清空购物车")
                                        break
                                    elif ctrl_shop_cart.isdecimal():
                                        ctrl_shop_cart = int(ctrl_shop_cart)
                                        if ctrl_shop_cart > 0 and ctrl_shop_cart <= len(temp_cart):
                                            all_price = all_price - temp_cart[ctrl_shop_cart - 1]["price"]
                                            shopping_cart.reverse()
                                            shopping_cart.remove(temp_cart[ctrl_shop_cart - 1])
                                            shopping_cart.reverse()
                                            print("删除成功\n")
                                        else:
                                            print("输入超出范围,请重新输入")
                                    else:
                                        print("输入有误,请重新输入\n")
                            elif final_cho.lower() == "q":
                                q = 1
                                break
                            else:
                                print("输入有误,请重新输入\n")
                    else:
                        print("数字超出范围,请重新输入\n")
                else:
                    print("请输入数字\n")
                if q == 1:
                    break

    else:
        print("\n只能输入数字,请重新输入\n")

    if q == 1:
        break

run screenshot

insert image description here
insert image description here

3. Business Card Manager

topic

The business card manager
needs to complete the basic functions:
adding business cards,
deleting business cards
, modifying business cards , querying
business cards , exiting the system.

program source code

print("=" * 20)
print("==\t学生名片管理系统")
print("1:添加名片")
print("2:删除名片")
print("3:修改名片")
print("4:查找名片")
print("5:显示名片")
print("6:退出")
print("=" * 20)
all_li = []
while True:
    print("\n==请输入序号==")
    first_num = input(">>> ")
    if first_num.isdecimal():
        first_num = int(first_num)
        if first_num == 1:
            dic_one = {
    
    }
            print("请输入要添加的名字")
            name = input(">>> ")
            print("请输入%s的年龄" % name )
            age = input(">>>")
            print("请输入%s的学号" % name)
            stu_num = input(">>> ")
            print("请输入%s的微信" % name)
            weixin = input(">>> ")

            dic_one["name"] = name
            dic_one["age"] = age
            dic_one["stu_num"] = stu_num
            dic_one["weixin"] = weixin
            all_li.append(dic_one)
            print("==添加成功==")
        elif first_num == 2:
            while True:
                print("\n==请输入要删除的名字==")
                del_name = input(">>> ")
                count = 0
                f = 0
                for i in all_li:
                    count += 1
                    if i["name"] == del_name:
                        count -= 1
                        f = 1
                        break
                if f == 0:
                    print("找不到你要找的名字,请重新输入")
                    continue
                del all_li[count]
                print("删除成功")
                break
        elif first_num == 3:
            while True:
                print("请输入要修改的名字")
                mod_name = input(">>> ")
                count = 0
                f = 0
                for i in all_li:
                    count += 1
                    if i["name"] == mod_name:
                        count -= 1
                        f = 1
                if f == 0:
                    print("找不到你要找的名字,请重新输入")
                    continue
                print("\n==名字已找到,想修改对应此名的哪项选项==")
                print("1:名字 2:年龄 3:学号 4:微信")
                while True:
                    print("== 请输入对应的序号 ==")
                    mod_num = input(">>> ")
                    if mod_num.isdecimal():
                        mod_num = int(mod_num)
                        if mod_num == 1:
                            print("\n请输入你要修改的名字")
                            mod_name2 = input(">>> ")
                            all_li[count]["name"] = mod_name2
                            print("修改成功")
                            break
                        if mod_num == 2:
                            print("\n请输入%s的新年龄" % all_li[count]["name"])
                            mod_age = input(">>> ")
                            all_li[count]["age"] = mod_age
                            print("修改成功")
                            break
                        if mod_num == 3:
                            print("\n请输入%s的新学号" % all_li[count]["name"])
                            mod_stu_num = input(">>> ")
                            all_li[count]["stu_num"] = mod_stu_num
                            print("修改成功")
                            break
                        if mod_num == 3:
                            print("\n请输入%s的新微信" % all_li[count]["name"])
                            mod_weixin = input(">>> ")
                            all_li[count]["weixin"] = mod_weixin
                            print("修改成功")
                            break
                    else:
                        print("输入有误,重新输入")
                break
        elif first_num == 4:
            while True:
                print("\n==请输入要查找的名字==")
                c = 0
                find_name = input(">>> ")
                for i in all_li:
                    if i["name"] == find_name:
                        print("名字\t\t年龄\t\t学号\t\t微信")
                        print("%s\t\t%s\t\t%s\t\t%s"%(i["name"],i["age"],i["stu_num"],i["weixin"]))
                    else:
                        print("找不到你要找的名字请重新输入")
                        c = 1
                if c == 1:
                    continue
                break
        elif first_num == 5:
            result = "名字\t年龄\t学号\t微信"
            print(result.expandtabs(20))
            for i in all_li:
                result2 = "%s\t%s\t%s\t%s"%(i["name"],i["age"],i["stu_num"],i["weixin"])
                print(result2.expandtabs(20))
        elif first_num == 6:
            break
        else:
            print("输入超出范围,请重新输入")
    else:
        print("输入有误,请重新输入")

run screenshot

insert image description here

4. User exchange display

topic

For example, a dictionary of the form

city ​​= {"Beijing": {"Chaoyang": ["Wangjing", "Dawanglu"], "Changping": ["Shahe", "Xiaochangping"]}, "Yanbian": {"Yanji": [
" Peking University", "Tienan"], "Longjing": ["Tumen", "Hunchun"]},
"Shanghai": {"New Shanghai": ["Pudong", "Puxi"], "Old Shanghai": ["Shanghai Beach", "Night Night City"]}}
Complete the following requirements:
allow users to add content,
allow users to view a certain level of content,
they can view the content, modify the content
, and delete the content.
Each level of loop nesting must contain a return Up one level, also includes exit all

program source code

city = {
    
    "北京": {
    
    "朝阳": ["望京", "大望路"], "昌平": ["沙河", "小昌平"]},
        "延边": {
    
    "延吉": ["北大", "铁南"], "龙井": ["图们", "珲春"]},
        "上海": {
    
    "新上海": ["浦东", "浦西"], "老上海": ["上海滩", "不夜城"]}}

while True:
    p = 0
    q = 0
    print("\33[35;1m一级列表\33[1m".center(50,"="))
    for i,v in enumerate(city,1):
        print(i,v)
    print("添加请按\33[31;1m A\33[1m 、查看请按\33[31;1m 序号\33[1m 、退出请按\33[31;1m Q\33[1m")
    init_cho = input(">>> ")
    if init_cho.lower() == "q":
        break
    elif init_cho.isdecimal():
        init_cho = int(init_cho)
        if init_cho > 0 and init_cho <= len(city):
            while True:
                first_li = []
                for i, v in enumerate(city, 1):
                    first_li.append(v)
                print("删除\33[31;1m%s\33[1m请按\33[31;1m Y\33[1m 、修改请按\33[31;1m M\33[1m 、返回上一级请按\33[31;1m P\33[1m 、进入下一级请按\33[31;1m N\33[1m 、全部退出请按\33[31;1m Q\33[1m"% first_li[init_cho-1])
                deci_cho = input(">>> ")
                if deci_cho.lower() == "y":
                    del city[first_li[init_cho-1]]
                    print("删除成功,自动跳回上一级")
                    break
                elif deci_cho.lower() == "q":
                    q = 1
                    break
                elif deci_cho.lower() == "p":
                    break
                elif deci_cho.lower() == "m":
                    print("您要改成什么名字?")
                    mod_sheng_name = input(">>>")
                    if mod_sheng_name.isalpha():
                        city[mod_sheng_name] = city.pop(first_li[init_cho-1])
                        print("修改成功")
                elif deci_cho.lower() == "n":
                    while True:
                        p2 = 0
                        second_li = []
                        print("\33[34;1m二级列表\33[1m".center(50,"="))
                        for x, y in enumerate(city[first_li[init_cho-1]], 1):
                            print(x, y)
                            second_li.append(y)
                        print("请按\33[31;1m序号\33[1m选择、返回上一级请按\33[31;1m P\33[1m 、全部退出请按\33[31;1m Q\33[1m")
                        sec_cho = input(">>> ")
                        if sec_cho.lower() == "p":
                            p = 1
                            break
                        elif sec_cho.lower() == "q":
                            q = 1
                            break
                        elif sec_cho.isdecimal():
                            sec_cho = int(sec_cho)
                            if sec_cho > 0 and sec_cho <= len(city[first_li[init_cho - 1]]):
                                while True:
                                    print("删除\33[31;1m%s\33[1m请按\33[31;1m Y\33[1m 、修改请按\33[31;1m M\33[1m 、返回上一级请按\33[31;1m P\33[1m 、进入下一级请按\33[31;1m N\33[1m 、全部退出请按\33[31;1m Q\33[1m"% second_li[sec_cho-1])
                                    third_cho = input(">>> ")
                                    if third_cho.lower() == "y":
                                        del city[first_li[init_cho-1]][second_li[sec_cho-1]]
                                        print("删除成功,自动跳回上一级")
                                        break
                                    elif third_cho.lower() == "m":
                                        print("您要改成什么名字?")
                                        mod_shi_name = input(">>>")
                                        city[first_li[init_cho - 1]][mod_shi_name] = city[first_li[init_cho - 1]].pop(second_li[sec_cho-1])
                                        print("修改成功,自动跳回上一级")
                                        break
                                    elif third_cho.lower() == "p":
                                        break
                                    elif third_cho.lower() == "q":
                                        q = 1
                                        break
                                    elif third_cho.lower() == "n":
                                        while True:
                                            print("\33[36;1m三级列表\33[1m".center(50, "="))
                                            for t, n in enumerate(city[first_li[init_cho - 1]][second_li[sec_cho - 1]], 1):
                                                print(t, n)
                                            print("请按\33[31;1m序号\33[1m选择删除或修改、添加请按 \33[31;1mA\33[1m 、返回上一级请按\33[31;1m P\33[1m 、全部退出请按\33[31;1m Q\33[1m")
                                            last_cho = input(">>> ")
                                            if last_cho.isdecimal():
                                                last_cho = int(last_cho)
                                                while True:
                                                    if last_cho > 0 and last_cho <= len(city[first_li[init_cho - 1]][second_li[sec_cho - 1]]):
                                                        print("删除请按 \33[31;1mD\33[1m 、修改请按 \33[31;1mM\33[1m 、返回上一级请按\33[31;1m P\33[1m 、全部退出请按\33[31;1m Q\33[1m")
                                                        one_more_cho = input(">>> ")
                                                        if one_more_cho.lower() == "d":
                                                            del city[first_li[init_cho - 1]][second_li[sec_cho - 1]][last_cho - 1]
                                                            print("删除成功,自动跳回上一层")
                                                            break
                                                        elif one_more_cho.lower() == "m":
                                                            print("您要改成什么名字?")
                                                            mod_last = input(">>> ")
                                                            city[first_li[init_cho - 1]][second_li[sec_cho - 1]][last_cho - 1] = mod_last
                                                            print("修改成功,自动跳回上一层")
                                                            break
                                                        elif one_more_cho.lower() == "p":
                                                            break
                                                        elif one_more_cho.lower() == "q":
                                                            q = 1
                                                            break
                                                        else:
                                                            print("输入有误,请重新输入\n")
                                                    else:
                                                        print("输入超出范围,请重新输入\n")
                                            elif last_cho.lower() == "a":
                                                print("请输入添加的名")
                                                add_last = input(">>> ")
                                                city[first_li[init_cho - 1]][second_li[sec_cho - 1]].append(add_last)
                                                print("添加成功")
                                            elif last_cho.lower() == "p":
                                                p2 = 1
                                                break
                                            elif last_cho.lower() == "q":
                                                q = 1
                                                break
                                            if q == 1:
                                                break
                                    else:
                                        print("输入有误,请重新输入\n")
                                    if q == 1:
                                        break
                                    if p2 == 1:
                                        break
                            else:
                                print("输入超出范围,请重新输入\n")
                        else:
                            print("输入有误请重新输入\n")
                        if q == 1:
                            break
                if q == 1:
                    break
                if p == 1:
                    break
        else:
            print("输入超出范围,请重新输入\n")
    elif init_cho.lower() == "a":
        while True:
            print("\33[36;1m添加信息\33[1m".center(50, "="))
            print("请输入省/直辖市、返回上一级请按\33[31;1m P\33[1m 、全部退出请按\33[31;1m Q\33[1m")
            add_sheng = input(">>> ")
            if add_sheng.lower() == "p":
                break
            elif add_sheng.lower() == "q":
                q = 1
                break
            elif city.get(add_sheng,0) == 0:
                city.update({
    
    add_sheng:{
    
    }})
            print("添加成功\n")
            print("请输入市/州、返回上一级请按\33[31;1m P\33[1m 、全部退出请按\33[31;1m Q\33[1m")
            add_shi = input(">>> ")
            if add_shi.lower() == "p":
                break
            elif add_shi.lower() == "q":
                q = 1
                break
            elif city[add_sheng].get(add_shi,0) == 0:
                city[add_sheng].update({
    
    add_shi:[]})
                print("添加成功\n")
                while True:
                    print("请输入县/街道、可多次写入、返回上一级请按\33[31;1m P\33[1m 、全部退出请按\33[31;1m Q\33[1m")
                    add_xian = input(">>> ")
                    if add_xian.lower() == "p":
                        break
                    if add_xian.lower() == "q":
                        q = 1
                        break
                    city[add_sheng][add_shi].append(add_xian)
                    print("添加成功")
            if q == 1:
                break
    elif init_cho == "5":
        print(city)
    else:
        print("输入有误,请重新输入\n")
    if q == 1:
        break

run screenshot

insert image description here

Summarize

At present, the writing of these four small programs is very simple. Basic loop nesting is used to achieve basic effects. I hope it will be helpful to everyone. At the same time, everyone is welcome to communicate and discuss, and continue to optimize and improve this program.

Guess you like

Origin blog.csdn.net/weixin_61587867/article/details/132229113