python - 在 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()
解决方案
您可以简单地从函数返回值并将其保存到函数外部的变量中。喜欢:
def user_prompt():
print('Welcome to your contact directory.')
return int(input("question"))
input_question = user_prompt()
推荐阅读
- r - 维度命令与此数据框的维度不匹配
- python - 如何使用python将具有多行的字符串写入文件
- html - Twitter 网站没有开放图形标签?
- bash - 输出被定向到 /dev/tty 而不是标准的“stdin”
- angular - 我想使用 ngModel 属性在下拉列表中显示默认值。但我没有得到默认值
- jboss - NoClassDefFoundError:无法链接 org/glassfish/jersey/server/ResourceConfig
- scala - 如何从类名中获取伴随对象?
- python - 在 Python 中使用非 ascii 字符文件名(表情符号)操作文件
- java - 如何在 Apache Beam 中使用 BigQuery IO 写入 BigQuery?
- python - 具有长时间启动和 gunicorn 超时的应用程序