16、函数实战
作者:互联网
# 创建一个全局列表容器来存储联系人字典
persons = []
# 创建联系人
def create_person():
name = input('name: ')
address = input('address: ')
phone = input('phone: ')
person = {'name': name, 'address': address, 'phone': phone}
persons.append(person)
# 列出所有联系人
def list_person():
for person in persons:
print('%s,%s,%s' % (person['name'], person['address'], person['phone']))
# 查询联系人
def query_person():
name = input('name: ')
for person in persons:
if person['name'] == name:
print('%s,%s,%s' % (person['name'], person['address'], person['phone']))
# 删除联系人
def delete_person():
name = input('name: ')
for person in persons:
if person['name'] == name:
persons.remove(person)
break
# 程序菜单
def get_choice():
print('1. create person')
print('2. list all persons')
print('3. query person')
print('4. delete person')
print('5. quit')
choice = input('Enter a number(1-5):')
return choice
# 主函数
def main():
while True:
choice = get_choice()
if choice == '1':
create_person()
elif choice == '2':
list_person()
elif choice == '3':
query_person()
elif choice == '4':
delete_person()
elif choice == '5':
break
else:
print('Invalid choice')
# 运行主程序
main()
参考资料
http://www.imooc.com/wiki/pythonlesson1/function2.html
标签:实战,函数,16,choice,person,persons,print,input,name 来源: https://www.cnblogs.com/tiansz/p/16389768.html