類方法實現:用python實現一個簡單的單詞本,添加/查找/刪除單詞。


 
         

1.實現一個簡單的單詞本,功能:

 
         

①添加單詞,當所添加的單詞已存在時,讓用戶知道

 
         

②查找單詞,當查找的單詞不存在時,讓用戶知道

 
         

③刪除單詞,當刪除的單詞不存在時,讓用戶知道

 
         

以上功能可以無限次操作,直到用戶輸入bye退出程序

 1 #如何接收輸入的help項
 2 #coding:utf-8
 3 help='''
 4     1.add a word
 5     2.find a word
 6     3.delete a word
 7     input bye to exit
 8     '''
 9 print (help)
10 import sys
11 wordbook=[]
12 while(1):
13     command=input("please input your command:")
14     if command=="1":
15         word=(input("please input your the word you want to add:")).strip()
16         if word not in wordbook:
17             wordbook.append(word)
18         print ("the word already exists")
19     if command=="2":
20         word=(input("please input your the word you want to find:")).strip()
21         for i in wordbook:
if i==word: 24 print ("find it") 25 print ("words do not exist.") 26 if command=="3": 27 word=(input("please input your the word you want to delete:")).strip() 28 for i in wordbook: 29 if i==word: 30 wordbook.remove(i) 31 print ("Word deleted") 32 print ("words do not exist.") 33 if command=="bye": 34 sys.exit()

 

2.升級版,單詞本類型為字典,用封裝函數的方法來實現

 1 #如何接收輸入的help項
 2 #coding:utf-8
 3 def addword():
 4     word=(input("請輸入你要添加的單詞:")).strip()
 5     if word in wordbook.keys():
 6         print ("the word already exists")
 7     else:
 8         word_meaning=input("請輸入單詞的含義:")
 9         wordbook[word]=word_meaning
10         print ("單詞添加成功")
11     print ("最新的單詞本為:",wordbook)
12 def findword():
13     word=(input("請輸入你要查找的單詞:")).strip()
14     if word in wordbook.keys():
15         print ("您查找的單詞已存在,單詞的含義是:",wordbook[word])
16     else:
17         print ("沒有該單詞")
18 def deleteword():
19     word=(input("please input your the word you want to delete:")).strip()
20     if word in wordbook.keys():
21         del wordbook[word]
22         print ("單詞刪除成功")
23     else:
24         print ("沒有該單詞")
25     print ("最新的單詞本為:",wordbook)
26 
27 help='''
28     1.add a word
29     2.find a word
30     3.delete a word
31     input bye to exit
32     '''
33 print (help)
34 import sys
35 wordbook={}
36 
37 while(1):
38     command=input("please input your command:")
39     if command=="1":
40         addword()
41     if command=="2":
42         findword()
43     if command=="3":
44         deleteword()
45     if command=="bye":
46         sys.exit()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM