Python 儿童乐园程序示例 - 简单易懂的代码实现
以下是一个简单的儿童乐园程序的示例,使用 Python 代码实现:
class Child:
def __init__(self, name, age):
self.name = name
self.age = age
class Playground:
def __init__(self):
self.children = []
def add_child(self, child):
self.children.append(child)
def remove_child(self, child):
self.children.remove(child)
def list_children(self):
for child in self.children:
print(f'Name: {child.name}, Age: {child.age}')
# 创建儿童乐园对象
playground = Playground()
while True:
print('1. 添加儿童')
print('2. 移除儿童')
print('3. 列出所有儿童')
print('4. 退出')
choice = input('请输入选项:')
if choice == '1':
name = input('请输入儿童姓名:')
age = int(input('请输入儿童年龄:'))
child = Child(name, age)
playground.add_child(child)
print('儿童添加成功!')
elif choice == '2':
name = input('请输入要移除的儿童姓名:')
for child in playground.children:
if child.name == name:
playground.remove_child(child)
print('儿童移除成功!')
break
else:
print('找不到该儿童!')
elif choice == '3':
playground.list_children()
elif choice == '4':
break
else:
print('无效选项,请重新输入!')
这个程序创建了两个类:'Child'表示儿童,具有姓名和年龄属性;'Playground'表示儿童乐园,具有添加、移除和列出儿童的方法。
在主循环中,用户可以选择添加、移除、列出儿童或退出程序。根据用户的选择,程序会执行相应的操作。
原文地址: https://www.cveoy.top/t/topic/fLSR 著作权归作者所有。请勿转载和采集!