5 回答

TA貢獻1712條經驗 獲得超3個贊
正如前面的答案所指出的,您沒有將函數的返回值保存main_menu()在任何地方。但是您的代碼中還存在一些其他錯誤,因此讓我們首先解決這些錯誤。
您需要先定義函數,然后才能使用它。您似乎試圖add_number同時調用該函數并定義它。首先定義你的函數,然后像這樣調用它:
# Define the add_number() function
def add_number():
clean()
...
if main == 1:
# call the add_number() function
add_number()
您正在嘗試迭代一個數字,這將引發錯誤。您可以嘗試使用range該函數來代替。
number = int(input("----->"))
for i in range(number): # using range function
...
您正在嘗試將名稱轉換為 int,但我假設您可能希望它是一個字符串。
# this will throw an ValueError if you type a name like "John"
c_n = int(input("Name-->"))
# This will not throw an error because you are not converting a string into an int
c_n = input("Name-->")
您的 try 塊正在捕獲SyntaxErrors,但您可能想要捕獲ValueErrors。語法錯誤是代碼語法中的錯誤,例如忘記了 a:或其他內容。而值錯誤是當某些日期的值錯誤時產生的錯誤,例如當您嘗試將字符串轉換為 int 時。
# replace SyntaxError with ValueError
except ValueError:
print("Oops something went wrong!")
最后,如果您想在輸入聯系號碼后返回菜單,則需要某種循環。
while(True):
# here we are saving the return value main_menu() function
choice = main_menu()
if choice == 1:
add_number()
# add other options here
else:
print("Sorry that option is not available")
此循環將顯示 main_menu 并詢問用戶一個選項。然后,如果用戶選擇 1,它將運行該add_number()函數。一旦該功能完成,循環將重新開始并顯示菜單。
總而言之,看起來像這樣:
import pandas as pd
#list for containing telephone number
telephone = []
#list containing contact name
contact_name = []
def main_menu():
intro = """ ----------------------WElCOME to MyPhone-----------------------
To select the task please type the number corrosponding to it
1)Add New Number
2)Remove Contact
3)Access old contact
----> """
main = int(input(intro))
return main
def clean():
print("--------------------------------------------------------------------------------------")
def add_number():
clean()
try:
print("How many number(s) you want to add. Remember if you don't want to add any number just click enter",end="")
number = int(input("----->"))
for i in range(number):
c_n = input("Name-->")
t_n = int(input("Number-->"))
contact_name.append(c_n)
telephone.append(t_n)
else:
print("Contacts are Saved!??")
except ValueError:
print("Oops something went wrong!")
while(True):
choice = main_menu()
if choice == 1:
add_number()
# add other options here
# catch any other options input
else:
print("Sorry that option is not available")

TA貢獻1824條經驗 獲得超8個贊
變量main
僅在函數內有效main_menu
。您需要將 的結果分配main_menu()
給某些東西才能使用它。
main = main_menu() if main == 1: ...

TA貢獻1836條經驗 獲得超13個贊
當您調用該函數時,您需要將結果放入變量中(或以其他方式使用它)。
例如:
selection = main_menu()
函數內部定義的變量在函數結束后消失;該return
語句僅返回值,而不是整個變量。

TA貢獻1847條經驗 獲得超11個贊
當您調用該函數時,它會返回 main,但是,必須將其分配給某個對象才能使用它執行某些操作。僅調用該函數不會創建變量 main。這是因為函數的范圍。
main = main_menu()

TA貢獻1788條經驗 獲得超4個贊
你的代碼中有很多錯誤。def = 只聲明函數但不調用它。
首先,如前所述,您在調用 main_menu() 時需要執行以下操作:
main = main_menu()
其次,在 if 中您應該調用 adD_number 函數:
if main ==1: add_number()
但請確保在調用之前聲明 add_number() (使用 def)。
祝你好運!
添加回答
舉報