def use(x):
if x==0:
return "type 1 is search, 2 is add, 3 is remove, 4 is quit:"
elif x==1:
return "sorry, we cannot recognize the input,please try again"
elif x==3:
return "type the items you want to "
elif x==4:
return "your revise had been preserved!"
elif x==5:
return "now the new fooddict is: "
elif x==6:
return "thank you for using"
else:
return "error: spelling mistake or the item does not exist"
这一段是给后面的程序准备的。原因:主程序中有一些重复的互动语句,可以用use(x)代替,不仅节省了代码,而且使主程序代码更加格式化。
import time, json #this version is for seller
#initialize:
lst_num=[]
lst_char=[]
cnt2=0
with open("fooddict.json","r") as f:
fooddict_=json.load(f)#value here refers to price
print("oh,remember to separate price and item by comma, separate different\
items by '/' when you want to input multiple things once")
a=input(use(0))
以上是初始程序,用来启动while循环的条件
def func(fooddict_,a):
while a.isdigit():
num=int(a)
if num==1:
result1=input(use(3)+"search:").split("/")
for i in result1:
if i in list(fooddict_.keys()):
print("the price for {} is {} pounds\n". format(i, fooddict_[i]))
else:
print(use(2),"\n")
elif num==2:
cnt=0
result2=input(use(3)+"add and the price:").split("/")
x=len(result2)
while cnt<x:
for i in range(x):
part=result2[i].split(",")
if len(part)==2:
if part[1].count(".")==1:
lst_num.append(float(part[1]))
elif part[1].count(".")==0:
lst_num.append(int(part[1]))
else:
print(use(1))
time.sleep(1)
break
lst_char.append(part[0])
fooddict_[lst_char[i]]=lst_num[i]
cnt+=1
else:
print(use(1),"\n")
time.sleep(1)
result2=input(use(3)+"add and the price:").split("/")
print(use(5),fooddict_)
with open("fooddict.json","w") as f1:
json.dump(fooddict_,f1)
print(use(4),"\n")
elif num==3:
result3=input(use(3)+"remove:").split("/")
for i in result3:
if i in list(fooddict_.keys()):
del fooddict_[i]
print(use(5),fooddict_)
with open("fooddict.json","w") as f1:
json.dump(fooddict_,f1)
print(use(4),"\n")
else:
print(use(2),"\n")
elif num==4:
print(use(6))
time.sleep(2)
global cnt2
cnt2+=1
break
else:
print(use(1),"\n")
a = input(use(0))
他主要就是分四部分,你输入1就跳到“查“这个模块,输入2跳入 “增”这个模块-支持一次多数据输入,但是限制你运行一次程序只能新增一组数据。输入3就是“删”,4是退出循环。
#main program:
while True:
if not a.isdigit():
print(use(1), "\n")
a = input(use(0))
if a=="4":
print(use(6))
time.sleep(2)
break
else:
func(fooddict_,a)
if cnt2==1:
break
这个程序看起来十分繁琐,而且使用了大量判断和循环,所以虽然他实现了功能,但在很大程度上消耗了计算机的计算能力。以上代码作为有效编程的反例,既没有没有使用多个自定义函数每个都执行简单的任务,也没有进行任何注释或有效换行来区分不同代码块,而且变量名也不代表该变量的实际意义,所以显得代码非常难懂而复杂。
所以为了格式化代码,美化代码使得代码更加的可持续且更好理解,我们需要使用多个自定义函数将一个大的,功能纷杂的程序分解成多个执行简单程序的子程序,使用有效换行,加入适当的注释,且在代码第一行注释上该代码实现的功能。
我稍微解释一下如何退出嵌套循环。我们这里因为使用了嵌套while循环,所以不论是在内层还是外层使用break都只能退出一层循环而另一层还是照样转。所以我们需要一些条件来从内层循环破到外层-把检测退出的内层条件变成全局变量,退出内层循环后根据条件退出外层循环。见下图:
elif num==4:#退出内层循环的代码段
print(use(6))
time.sleep(2)
#将出cnt2变量设为全局变量,这样外层循环if-else分支代码可以检测到cnt2的变化从而判断是否退出主循环
global cnt2
cnt2+=1
break
else:#退出外层循环的代码段
func(fooddict_,a)
if cnt2==1:
break
另外一个更为优雅的退出方法是sys.exit()方法,它主要用于退出主进程。另外os._exit(0)可以代替break,退出线程(这个方法可以在特定条件下停止执行函数内所有代码,比break要狠一些)。
当然,这个线上商品增删改查程序也有两处bug:1输入二的增命令程序只能保存一次增添的值,第二次循环再选2时,输入的值就不能被保存了。2.原本变量start有一个判断,即判断输入的值是否是数型,而在第二次及以后执行循环时,若输入非规范内容,系统会自动跳到第一次循环选择的命令(输入规范内容就没有影响)
线上中英字典代码如下
import time,json
with open("dct.json","w")as f:
Dict=json.load(f)
def search_word():
word_s = input("what word do you want to search: ")
if word_s in Dict:
print("its meaning is:", Dict[word_s])
time.sleep(2)
else:
print("sorry, we do not have that")
def delet_word():
word = input("what word do you wnat to search: ")
if word in Dict:
word_2 = int(
input("{}has been deleted,this is new dictionary:".format(Dict[word])))
del Dict[word]
print(Dict)
with open("dct.json","w")as f1:
json.dump(Dict,f1)
else:
print("sorry, we do not have the word that you want to delete")
time.sleep(1)
def append_word():
word_append = input("what word do you want to add: ")
word_meaning = input("please write its meaning: ")
Dict[word_append] = word_meaning
print("this is new dictionary:", Dict)
with open("dct.json","w") as f2:
json.dump(Dict,f2)
time.sleep(1)
while True:
commend=input("input your demand,press 1 if you want to search any word,press 2 if you want to delete any word,press 3 if you want to add any word,press4 if you want to log out: ")
if commend=='1':
search_word()
elif commend=='2':
delet_word()
elif commend=='3':
append_word()
elif commend == '4':
print("Welcome to use again! shutting down ...")
time.sleep(2)
break
else:
print("sorry, we cannot implement you commend. But you can try pressing 1,2,3 or 4")
time.sleep(2)
原理:虽然这个线上中英字典代码很长,他的主要原理是非常简单的。它主要用到的知识有:循环,字典,自定义函数和文件知识。他主要是通过判断用户输入数字来执行增删改查的子程序,然后将这些子程序分别放入主程序中,实现这个功能。
这个实现原理,能看的出来,上面的线上商店类似,虽然这个没有一次多次添加或删除的功能,但代码结构更加简洁。with open("dct.json","r") as f 这行用来读取dct.json文件中的字典词典,其中键对应的是英文,值对应的是其中文翻译。大家可以根据需要手动在dct.json文件中添加多种翻译词典。注:大家要先在电脑中下载该语言的字体包再写关于该语言的词典
顺便提一下json库。一般我们用with open("xxx.txt","w") as f 只能写入txt文件,也就是说这些文件提取出来都是字符串。如果我们想保存字典或列表而不想让他单纯的变成字符串,我们就需要用到json。json支持我们输入各种格式的文件/数据,并保留原来的数据结构,这样我们取出数据就可以直接用了!json.dump()是json库支持导入数据的一个方法,括号里面接收两个参数,第一个是要导入的数据,第二个是要导入到的文件数据。json.load()则是导出json文件中的数据,所以括号里面只接受一个参数,即要导出的文件,用一个变量接收他即可。