簡體   English   中英

我需要多個輸入來運行主 function 電話簿 python

[英]i need multiple input to run main function phonebook python

我在編寫重復輸入部分的程序時遇到問題。 例如

input 1 ___run add_contact()
again ask for input
input 4____run disp_contact()
...
...

我從來沒有寫過長代碼::\

我完全是初學者。 並在業余時間學習了一點 Python 我的導師說你應該定義幾個函數並將它們放在一個主要的 function 中以獲得輸入。 所以如果有人能告訴我為什么我會這樣卡住,我將不勝感激。

contact={}
print(''' phone book
    1. add contact
    2.delete contact
    3.search contact
    4.display all
    5.Quit''')

def add_contact():
    name=input('enter the name: ')
    number=input('enter the number: ')
    contact[name]=number
    print(name, 'added to phone book!')
    
def del_contact():
    name=input('enter the name: ')
   
    while name not in contact:
        print("not found! try again" )
        name=input('enter again: ')

    else:    
        print(name,' deleted')
        del contact[name]
        name=False
      
        
        
def search_contact():
    name=input('enter the name: ')
    while name not in contact:
        print('not found!')
        name=input('enter again: ')  
    else:
        print(name, 'number is :',  contact[name])  
        
def disp_contact():
    if len(contact)>0:
       print('phone book contacts are: ')
       for i in contact:
         print(i, end=' ')
    else:
      print('phone book is empty!')    
    
        
def main_def(num):
       

       if num==1:
              add_contact()
              
       elif num==2:
              del_contact()
              
       elif num==3:
              search_contact()
              
       elif num==4:
              disp_contact()

       elif num==5:
          print('bye bye') 



x=int(input(' enter a number: '))
main_def(x)

您可以在一段時間內包裝main_def while True ,並在給出5時使用exit(O)正確退出

def main_def(num):
    if num == 1:
        add_contact()
    elif num == 2:
        del_contact()
    elif num == 3:
        search_contact()
    elif num == 4:
        disp_contact()
    elif num == 5:
        exit(0)

while True:
    x = int(input(' enter a number: '))
    main_def(x)

筆記

對於del_contactsearch_contact ,你不需要像這樣放在后面的else

def del_contact():
    name = input('enter the name: ')

    while name not in contact:
        print("not found! try again")
        name = input('enter again: ')

    print(name, ' deleted')
    del contact[name]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM