第四章
实例1:刮刮乐
reward_info = ["谢谢惠顾", "一等奖", "三等奖", "谢谢惠顾", "谢谢惠顾",
"三等奖", "二等奖", "谢谢惠顾"]
num = int(input("请输入刮去的位置(1~8):"))
if 0 <= num <= len(reward_info):
info = reward_info[num - 1]
print(f"{info}")
else:
print("输入的位置不合规!")
实例2:商品价格区间设置与排序
price_li = [399, 4369, 539, 288, 109, 749, 235, 190, 99, 1000]
section_li = []
max_section = int(input("请输入最大价格:"))
min_section = int(input("请输入最小价格:"))
for i in price_li:
if min_section <= i <= max_section:
section_li.append(i)
print("1.价格降序排序")
print("2.价格升序排序")
choice_num = int(input("请选择排序方式:"))
if choice_num == 1:
section_li.sort(reverse=True)
else:
section_li.sort()
print(section_li)
实例3:好友管理系统
friends = []
print("欢迎使用好友系统")
print("1:添加好友")
print("2:删除好友")
print("3:备注好友")
print("4:展示好友")
print("5:退出")
while True:
num = int(input("请输入您的选项:"))
if num == 1:
add_friend = input("请输入要添加的好友:")
friends.append(add_friend)
print('好友添加成功')
elif num == 2:
if len(friends) == 0:
print("好友列表为空,不可删除")
else:
del_friend = input("请输入删除好友姓名:")
friends.remove(del_friend)
print("删除成功")
elif num == 3:
before_friend = input("请输入要修改的好友姓名:")
after_friend = input("请输入修改后的好友姓名:")
friend_index = friends.index(before_friend)
friends[friend_index] = after_friend
print("备注成功")
elif num == 4:
if len(friends) == 0:
print("好友列表为空")
else:
for i in friends:
print(i)
elif num == 5:
break
实例4:随机分配办公室
# 随机分配办公室
import random
offices = [[], [], []]
teachers = ['1', '2', '3', '4', '5', '6', '7', '8']
for teacher in teachers:
index = random.randint(0, 2)
offices[index].append(teacher)
i = 1
for office in offices:
num = len(office)
print(f"第{i}个办公室有{num}位老师")
print(office)
i += 1
实例5:中文数字对照表
uppercase_numbers = ("零", "壹", "贰", "叁", "肆", "伍",
"陆", "柒", "捌", "玖")
number = input("请输入一个数字:")
for i in range(len(number)):
print(uppercase_numbers[int(number[i])], end="")
第五章
实例1:单词识别
tues_or_thurs = {'h': 'Thursday', 'u': 'Tuesday'}
weekend = {'a': 'Saturday', 'u': 'Sunday'}
week = {'t': tues_or_thurs, 's': weekend,
'm': 'Monday', 'w': 'Wednesday', 'f': 'Friday'}
first_char = input('请输入第一位字母:').lower().strip()
if first_char in ['a', 't', 's', 'm', 'w', 'f']:
if week[first_char] == tues_or_thurs or week[first_char] == weekend:
second_char = input('请输入第二位字母:').lower().strip()
if second_char in ['u', 'h', 'a']:
print(week[first_char][second_char])
else:
print('请输入正确字母')
else:
print(week[first_char])
else:
print('请输入正确的字母')
实例2:手机通讯录
person_info = []
print("=" * 20)
print('欢迎使用通讯录:')
print("1.添加联系人")
print("2.查看通讯录")
print("3.删除联系人")
print("4.修改联系人")
print("5.查找联系人")
print("6.退出")
print("=" * 20)
while True:
per_dict = {}
fun_num = input('请输入功能序号:')
if fun_num == '1':
per_name = input('请输入联系人的姓名:')
phone_num = input('请输入联系人的手机号:')
per_email = input('请输入联系人的邮箱:')
per_address = input('请输入联系人的地址:')
# 判断输入的是否为空
if per_name.strip() == '' or phone_num.strip() == '' or per_email.strip() == '' or per_address.strip() == '':
print('请输入正确信息')
continue
else:
per_dict.update({'姓名': per_name, '手机号': phone_num, '电子邮箱': per_email, '联系地址': per_address})
person_info.append(per_dict) # 保存到列表中
print('保存成功')
elif fun_num == '2':
if len(person_info) == 0:
print('通讯录无信息')
for i in person_info:
print('--*' * 6)
for title, info in i.items():
print(title + ':' + info)
print('--*' * 6)
elif fun_num == '3': # 删除
if len(person_info) != 0:
del_name = input('请输入要删除的联系人姓名:')
for i in person_info:
if del_name in i.values():
person_info.remove(i)
print(person_info)
print('删除成功')
else:
print('该联系人不在通讯录中')
else:
print('通讯录无信息')
elif fun_num == '4': # 修改
if len(person_info) != 0:
modi_info = input('请输入要修改的联系人姓名:')
for i in person_info:
if modi_info in i.values():
# 获取所在元组在列表中的索引位置
index_num = person_info.index(i)
dict_cur_perinfo = person_info[index_num]
for title, info in dict_cur_perinfo.items():
print(title + ':' + info)
modi_name = input('请输入新的姓名:')
modi_phone = input('请输入新的手机号:')
modi_email = input('请输入新的邮箱:')
modi_address = input('请输入新的地址:')
dict_cur_perinfo.update(姓名=modi_name)
dict_cur_perinfo.update(手机号=modi_phone)
dict_cur_perinfo.update(电子邮箱=modi_email)
dict_cur_perinfo.update(联系地址=modi_address)
print(person_info)
else:
print('通讯录无信息')
elif fun_num == '5': # 查找
if len(person_info) != 0:
query_name = input('请输入要查找的联系人姓名:')
for i in person_info:
if query_name in i.values():
index_num = person_info.index(i)
for title, info in person_info[index_num].items():
print(title + ':' + info)
break
else:
print('该联系人不在通讯录中')
else:
print('通讯录无信息')
elif fun_num == '6': # 退出
break
实例3:生词本
words_book = set()
words_only_set = set()
print('=' * 20)
print('欢迎使用生词本')
print('1.查看生词本')
print('2.背单词')
print('3.添加新单词')
print('4.删除单词')
print('5.清空生词本')
print('6.退出生词本')
print('=' * 20)
while True:
word_dict = {}
fun_num = input('请输入功能编号:')
if fun_num == '1': # 查看生词本
if len(words_book) == 0:
print('生词本内容为空')
else:
print(words_book)
elif fun_num == '2': # 背单词
if len(words_book) == 0:
print('生词本内容为空')
else:
for random_words in words_book:
w = random_words.split(':')
in_words = input("请输入" + w[0] + '翻译' + ':\n')
if in_words == w[1].strip():
print('太棒了')
else:
print('再想想')
elif fun_num == '3': # 添加新单词
new_words = input('请输入新单词:')
# 检测单词是否重复
if new_words in words_only_set:
# 添加的单词重复
print('此单词已存在')
else:
# 执行单词添加
new_chinese = input('请输入单词翻译:')
word_dict.update({new_words: new_chinese})
# 转换成字符串存入 set 集合中
dict_str = str(word_dict).replace('{', '').replace('}', '').replace("'", '')
words_book.add(dict_str)
print('单词添加成功')
dict_str = dict_str.replace(',', '')
print(dict_str)
words_only_set.add(new_words)
elif fun_num == '4': # 删除单词
if len(words_book) == 0:
print('生词本为空')
else:
temp_list = list(words_book)
print(temp_list)
del_wd = input("请输入要删除的单词:")
# 如果要删除的单词不在单词集合中
if del_wd not in words_only_set:
print('删除的单词不存在')
else:
words_only_set.discard(del_wd)
for temp in temp_list:
if del_wd in temp:
words_book.remove(temp)
print('删除成功')
elif fun_num == '5': # 清空
if len(words_book) == 0:
print('生词本为空')
else:
words_only_set.clear()
words_book.clear()
print('生词本清空成功')
elif fun_num == '6': # 退出
print('退出成功')
break
第六章
实例1:计算器
def oper(parm_one, parm_two):
operator = input('请选择要执行的运算符:+、-、*、/' + '\n')
if operator == "+":
print("计算结果为:", +parm_one + parm_two)
elif operator == '-':
print("计算结果为:", parm_one - parm_two)
elif operator == '*':
print("计算结果为:", parm_one * parm_two)
elif operator == '/':
if parm_two == 0:
print('被除数不能为 0')
else:
print("计算结果为:", parm_one / parm_two)
num_one = int(input('请输入第一个数:'))
num_two = int(input('请输入第二个数:'))
oper(num_one, num_two)
实例2:学生信息管理系统
# 功能菜单打印
def print_menu():
print('=' * 30)
print('学生管理系统')
print('1.添加学生信息')
print('2.删除学生信息')
print('3.修改学生信息')
print('4.显示所有学生信息')
print('0.退出系统')
print('=' * 30)
# 新建一个列表,用来保存学生的所有信息
stu_info = []
# 添加学生信息
def add_stu_info():
# 提示并获取学生的姓名
new_name = input('请输入新学生的姓名:')
# 提示并获取学生的性别
new_sex = input('请输入新学生的性别:')
# 提示并获取学生的手机号
new_phone = input('请输入学生的手机号码:')
new_info = dict()
new_info['name'] = new_name
new_info['sex'] = new_sex
new_info['phone'] = new_phone
stu_info.append(new_info)
# 删除学生信息
def del_stu_info(student):
del_num = int(input('请输入要删除的序号:')) - 1
del student[del_num]
# 修改学生信息
def modify_stu_info():
if len(stu_info) != 0:
stu_id = int(input('请输入学生序号:'))
new_name = input('请输入学生姓名:')
new_sex = input('请输入学生性别(男/女):')
new_phone = input('请输入学生的手机号码:')
stu_info[stu_id - 1]['name'] = new_name
stu_info[stu_id - 1]['sex'] = new_sex
stu_info[stu_id - 1]['phone'] = new_phone
else:
print('学生信息表为空')
# 显示学生信息
def show_stu_info():
print('学生的信息如下:')
print('=' * 30)
print('序号 姓名 性别 手机号码')
i = 1
for temp_info in stu_info:
print("%d %s %s %s" % (i, temp_info['name'], temp_info['sex'], temp_info['phone']))
i += 1
# 主函数
def main():
while True:
print_menu() # 打印菜单
key = input("请选择功能:") # 获取用户输入的序号
if key == '1': # 添加学生信息
add_stu_info()
elif key == '2': # 删除学生信息
del_stu_info(stu_info)
elif key == '3': # 修改学生信息
modify_stu_info()
elif key == '4': # 查看所有学生的信息
show_stu_info()
elif key == '0':
quit_confirm = input('亲,真的要退出么?(Yes or No):')
if quit_confirm == 'Yes' or 'yes':
break # 跳出循环
else:
print('输入有误,请重新输入')
if __name__ == '__main__':
main()
实例3:汉诺塔
def hanoi(n, ch1, ch2, ch3):
if n == 1:
print(ch1, '->', ch3)
else:
hanoi(n - 1, ch1, ch3, ch2)
print(ch1, '->', ch3)
hanoi(n - 1, ch2, ch1, ch3)
plate_nums = int(input("请输入盘子的数量:"))
hanoi(plate_nums, 'A', 'B', 'C')
实例4:斐波那契数列
def fibonacci(n):
if n == 1 or n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
num = int(input('请输入一个正整数: '))
for i in range(1, num + 1):
print(fibonacci(i), end=' ')