Python练手小项目

计算器

创建一个简单的计算器,能够进行加、减、乘、除四种基本运算。

python 复制代码
# 定义加法函数
def add(x, y):
    return x + y

# 定义减法函数
def subtract(x, y):
    return x - y

# 定义乘法函数
def multiply(x, y):
    return x * y

# 定义除法函数
def divide(x, y):
    if y == 0:
        return "Error! Division by zero."  # 防止除以零
    return x / y

# 打印操作选项
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

# 获取用户选择的操作
choice = input("Enter choice(1/2/3/4): ")

# 获取用户输入的两个数字
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# 根据用户选择的操作调用相应的函数
if choice == '1':
    print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
    print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
    print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
    print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
    print("Invalid input")  # 处理无效输入

猜数字游戏

编写一个猜数字游戏,计算机随机生成一个1到100之间的数字,用户需要猜这个数字,程序会提示猜大了还是猜小了,直到猜对为止。

python 复制代码
import random  # 导入随机数模块

# 生成一个1到100之间的随机数
number_to_guess = random.randint(1, 100)
attempts = 0  # 初始化尝试次数

print("Guess the number between 1 and 100")

while True:
    guess = int(input("Enter your guess: "))  # 获取用户猜测的数字
    attempts += 1  # 尝试次数加一
    if guess < number_to_guess:
        print("Too low!")  # 提示猜的数字太小
    elif guess > number_to_guess:
        print("Too high!")  # 提示猜的数字太大
    else:
        print(f"Congratulations! You've guessed the number in {attempts} attempts.")  # 猜对了
        break  # 结束循环

简单的记事本

创建一个简单的记事本应用,用户可以添加、查看和删除笔记。

python 复制代码
notes = []  # 初始化一个空列表来存储笔记

# 添加笔记的函数
def add_note():
    note = input("Enter your note: ")
    notes.append(note)
    print("Note added!")

# 查看所有笔记的函数
def view_notes():
    print("Your notes:")
    for i, note in enumerate(notes, 1):
        print(f"{i}. {note}")

# 删除笔记的函数
def delete_note():
    view_notes()  # 先显示所有笔记
    note_index = int(input("Enter the note number to delete: ")) - 1
    if 0 <= note_index < len(notes):
        del notes[note_index]
        print("Note deleted!")
    else:
        print("Invalid note number")  # 处理无效输入

# 主循环
while True:
    print("\n1. Add Note")
    print("2. View Notes")
    print("3. Delete Note")
    print("4. Exit")

    choice = input("Enter your choice: ")

    if choice == '1':
        add_note()
    elif choice == '2':
        view_notes()
    elif choice == '3':
        delete_note()
    elif choice == '4':
        break  # 退出循环
    else:
        print("Invalid choice. Please try again.")  # 处理无效选择

简单的联系人管理系统

创建一个简单的联系人管理系统,可以添加、查看、删除联系人。

python 复制代码
contacts = {}  # 初始化一个空字典来存储联系人

# 添加联系人的函数
def add_contact():
    name = input("Enter contact name: ")
    phone = input("Enter contact phone number: ")
    contacts[name] = phone
    print("Contact added!")

# 查看所有联系人的函数
def view_contacts():
    print("Your contacts:")
    for name, phone in contacts.items():
        print(f"Name: {name}, Phone: {phone}")

# 删除联系人的函数
def delete_contact():
    name = input("Enter the name of the contact to delete: ")
    if name in contacts:
        del contacts[name]
        print("Contact deleted!")
    else:
        print("Contact not found")  # 处理联系人未找到的情况

# 主循环
while True:
    print("\n1. Add Contact")
    print("2. View Contacts")
    print("3. Delete Contact")
    print("4. Exit")

    choice = input("Enter your choice: ")

    if choice == '1':
        add_contact()
    elif choice == '2':
        view_contacts()
    elif choice == '3':
        delete_contact()
    elif choice == '4':
        break  # 退出循环
    else:
        print("Invalid choice. Please try again.")  # 处理无效选择

简单的待办事项列表

创建一个简单的待办事项列表应用,可以添加、查看和删除待办事项。

python 复制代码
todo_list = []  # 初始化一个空列表来存储待办事项

# 添加任务的函数
def add_task():
    task = input("Enter a new task: ")
    todo_list.append(task)
    print("Task added!")

# 查看所有任务的函数
def view_tasks():
    print("Your tasks:")
    for i, task in enumerate(todo_list, 1):
        print(f"{i}. {task}")

# 删除任务的函数
def delete_task():
    view_tasks()  # 先显示所有任务
    task_index = int(input("Enter the task number to delete: ")) - 1
    if 0 <= task_index < len(todo_list):
        del todo_list[task_index]
        print("Task deleted!")
    else:
        print("Invalid task number")  # 处理无效输入

# 主循环
while True:
    print("\n1. Add Task")
    print("2. View Tasks")
    print("3. Delete Task")
    print("4. Exit")

    choice = input("Enter your choice: ")

    if choice == '1':
        add_task()
    elif choice == '2':
        view_tasks()
    elif choice == '3':
        delete_task()
    elif choice == '4':
        break  # 退出循环
    else:
        print("Invalid choice. Please try again.")  # 处理无效选择
相关推荐
特立独行的猫A2 小时前
别再用 nohup 了:让应用在后台常驻的正确姿势与 systemd 服务详解
java·后端·python
吃我一窝jio4 小时前
Python与Go线程模型深度对比
java·开发语言·python
zwd20055 小时前
Manim 怎么放大画面的某一部分?
python·动画·可视化·manim·数学动画
屿华AI6 小时前
AUTOSAR 实战-诊断工具 | UDS 0x27 安全访问的配置化实现:种子密钥算法插件化设计
python·测试工具·汽车
RobinDevNotes6 小时前
Claude Code 剪视频,不上传、不要 API Key
人工智能·python·音视频·开发工具·ipython
如夏倾城7 小时前
VRRP(虚拟路由器冗余协议Virtual Router Redundancy Protocol)
网络·python·网络协议·安全·智能路由器·负载均衡·信息与通信
IvanCodes8 小时前
LangChain(04):Runnable 与 LCEL 的执行与组合机制
python·langchain·agent
特创数字科技8 小时前
纯本地离线运行的文档脱敏工具(技术分享)
前端·驱动开发·python
东莞市云毅网络有限公司9 小时前
用 Playwright 搭一套问答平台引用监测的最小骨架
python·数据清洗·rag·企业知识库·文档解析
Thanks_ks9 小时前
【第 010 讲】全面掌握 Python 变量与常量:变量的定义与赋值 | 标识符与命名规范 | 变量的底层机制 | 常量与魔术数字
python·内存·变量·标识符·常量·赋值·命名规范