案例一:制作简单的待办事项列表
案例背景
在这个案例中,我们将创建一个简单的待办事项列表应用程序。这个应用将允许用户添加、删除和显示待办事项。
案例目的
学习Python的基础语法、列表操作和文件操作。
实现代码
def show_task_list(task_list):
for i, task in enumerate(task_list, start=1):
print(f"{i}. {task}")
def add_task(task_list, task):
task_list.append(task)
def delete_task(task_list, task_index):
try:
del task_list[task_index - 1]
except IndexError:
print("Task index is out of range.")
def main():
task_list = []
while True:
print("\n1. Show all tasks")
print("2. Add a task")
print("3. Delete a task")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
show_task_list(task_list)
elif choice == "2":
task = input("Enter the task: ")
add_task(task_list, task)
elif choice == "3":
task_index = int(input("Enter the task index to delete: "))
delete_task(task_list, task_index)
elif choice == "4":
break
else:
print("Invalid choice. Please enter a number between 1 and 4.")
if __name__ == "__main__":
main()
案例分析
在这个案例中,我们使用Python的列表来存储待办事项,并通过简单的函数实现添加、删除和显示功能。这个案例帮助我们熟悉了Python的基础语法和列表操作。
案例二:计算器程序
案例背景
计算器是一个非常基础的程序,通过它我们可以学习Python的算数运算、用户输入处理以及循环语句。
案例目的
学习Python的基本算数运算、用户输入处理和循环语句。
实现代码
def calculator():
while True:
operation = input("Enter the operation (+, -, *, /): ")
if operation not in ('+', '-', '*', '/'):
print("Invalid operation.")
continue
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if operation == '+':
print(f"The result is: {num1 + num2}")
elif operation == '-':
print(f"The result is: {num1 - num2}")
elif operation == '*':
print(f"The result is: {num1 * num2}")
elif operation == '/':
if num2 != 0:
print(f"The result is: {num1 / num2}")
else:
print("Cannot divide by zero.")
another = input("Do you want to perform another operation? (yes/no): ")
if another.lower() != 'yes':
break
if __name__ == "__main__":
calculator()
案例分析
在这个案例中,我们通过循环和条件语句实现了一个基本的计算器程序。这个案例让我们了解了Python的基本算数运算和用户输入处理。
