01-作业
import json
code_list = []
try:
with open(youbian.txt, r, encoding=utf8) as file:
while True:
content = file.readline().strip(,
)
if not content:
break
# print(content, type(content)) # [100000,"北京市"]
x = json.loads(content)
code_list.append(x)
except FileNotFoundError:
print(文件打开失败)
x = input(请输入一个邮编:)
# 1.把用户输入的字符串转换成为数字
# 2.把列表里的编码转换成为字符串
for code in code_list:
if str(code[0]) == x:
print(code[1])
break
else:
print(没有找到对应的城市)
02-名片管理系统(退出系统)
def add_user():
print(添加用户)
def del_user():
print(删除用户)
def modify_user():
print(修改用户)
def search_user():
print(查询用户)
def show_all():
print(显示所有名片)
def exit_system():
# print(退出系统)
answer = input(亲, 你确定要退出么?~~~~(> _ <)~~~~(yes or no))
return answer.lower() == yes
# if answer == yes:
# exit(0) # 使用系统内置函数exit,直接结束整个程序
def start():
while True:
print(
"---------------------------
名片管理系统 V1.0
1:添加名片
2:删除名片
3:修改名片
4:查询名片
5:显示所有名片
6:退出系统
---------------------------")
operator = input(请输入要进行的操作(数字):)
if operator == 1: # 添加名片
add_user()
elif operator == 2: # 删除名片
del_user()
elif operator == 3:
modify_user()
elif operator == 4:
search_user()
elif operator == 5:
show_all()
elif operator == 6:
is_sure = exit_system()
if is_sure:
break
# answer = input(亲, 你确定要退出么?~~~~(> _ <)~~~~(yes or no))
# if answer.lower() == yes:
# break
else:
print(您输入的不合法,请重新输入)
if __name__ == __main__:
start()
03-名片管理系统(添加用户)
04-名片管理系统(删除用户)
05-名片管理系统(修改用户)
06-名片管理系统(查询用户)
07-迭代器回顾
from collections.abc import Iterable
class Demo(object):
def __init__(self, n):
self.n = n
self.count = 0
def __iter__(self):
return self
def __next__(self):
self.count += 1
if self.count <= self.n:
return self.count - 1
raise StopIteration
d = Demo(10)
# print(isinstance(d, Iterable))
# x = d.__iter__()
# x.__next__()
# print(x is d) # True
for i in d:
print(i)
08-生成器的使用
# 生成器本质也是一个迭代器,它是一个特殊的迭代器
x = 5
y = 10
# if x > y:
# z = x
# else:
# z = y
# z = x if x > y else y 三元表达式
# 最简单的生成器
# nums = [i for i in range(10)] # 列表生成式(推导式)
# print(nums)
#
# g = (i for i in range(10)) # 得到的结果是生成器
# for m in g: # 生成器是一个特殊的迭代器,也可以方法在for...in后面
# print(m)
# 迭代器是一个对象,定义class
# 生成器写法上像一个函数
def my_gen(n):
i = 0
while i < n:
# return i # 函数里的return表示函数的执行结束
yield i # yield关键字,将函数变成生成器
i += 1
G = my_gen(10)
# print(next(iter(G)))
for i in G:
print(i)
09-生成器的练习
def fibonacci(n):
num1 = num2 = 1
count = 0
while count <= n - 2:
num1, num2 = num2, num1 + num2
count += 1
yield num1
F = fibonacci(12) # 此时并不会调用函数
for i in F:
print(i)
def demo(x): # x = 100
x = int(x) # x = 100
y = 100
demo(y)
print(y) # 100 100