首页 > 解决方案 > 在 def 函数中使用 input()

问题描述

我正在尝试使用 def() 函数创建一个联系人列表,以便稍后在代码中轻松地循环回到顶部。我遇到的问题是我在 def 部分定义了“function_question”,但是当我运行代码时,它给了我一个 NameError 说“function_question”没有定义。任何帮助或建议表示赞赏!

#Created a def so I can easily run back the code to the top. 
def user_prompt():
  print('Welcome to your contact directory.')
  function_question = int(input("What would you like to do? \n1  Add Conctact \n2  Find Contact \n3  Edit Contact \n4  Delete Contact:"))

user_prompt()

#Adding a contact to the contact list. 
while function_question == 1:
  name = input('What is the persons name? ')
  phone_number = input('What is the phone number? ')
  email = input('What is your email? ')
  address = input('What is the person adress? ')
  if len(phone_number) != 10:
    phone_number = input("the phone number you provided is not the proper length. Re-enter:")
  contact = [] + [name] + [phone_number] + [email] + [address]
  contact_list.append(contact)
  ans = input('Would you like to add another contact? ')
  if ans == 'yes':
    continue 
  if ans == 'no':
    user_prompt()

标签: python

解决方案


您可以简单地从函数返回值并将其保存到函数外部的变量中。喜欢:

def user_prompt():
  print('Welcome to your contact directory.')
  return int(input("question"))

input_question = user_prompt()

推荐阅读