简体   繁体   English

如何理解我正在尝试编写的 function 中的未定义错误

[英]How to understand an undefined error in a function I'm trying to write

I'm a new engineer and I'm writing a simple phone book app in Python. It's pretty self explanatory, as it's a beginner project.我是一名新工程师,我正在 Python 中编写一个简单的电话簿应用程序。这是一个非常不言自明的项目,因为它是一个初学者项目。 When I was writing the function I forgot to tell it what to do if a entry that was being search wasn't found.当我写 function 时,我忘记告诉它如果没有找到正在搜索的条目该怎么办。

I have looked at several examples, and to the best of my growing knowledge base, coded what I thought was correct.我看过几个例子,并根据我不断增长的知识库,对我认为正确的代码进行了编码。 I am getting an error and would like to understand it.我收到一个错误,想了解它。

Also, optimization is key, so one of my objectives is to learn to code for optimization the first time.此外,优化是关键,所以我的目标之一是第一次学习编写优化代码。

Traceback (most recent call last):
  File "/Users/corcoding/Desktop/projects/phonebook-project/phonebook.py", line 20, in <module>
    print("phone number of" ,name1, "is", d1==[name])
NameError: name 'name' is not defined

Code:代码:

def menu():
    print("-------Lil Black Book--------")
    print("[1] Look up an entry")
    print("[2] Set an entry")
    print("[3] delete an entry")
    print("[4] List all entries")
    print("[5] Quit")
    print("what would you like to do (1-5)?")

menu()

   
d1 = {}
while True:
    n=int(input("enter number [1-5]:-"))
    if n ==2:
        name=input("enter name:-")
        phono=(input("enter phone number:-"))
        d1[name]=phono
    elif n==1:
        name1=input("enter name to SEARCH for phone number in the phone book")
        print("phone number of" ,name1, "is", d1[name])
    if name1 != d1[name]:
        print("entry not found")    
    if n== 3:
        name1=input("enter name to delete:-")
        d1.pop(name)
    elif n==5:  
        break 

I believe this code may accomplish what you are looking for:我相信这段代码可以完成你正在寻找的东西:

d1 = {}
while True:
    n = int(input("enter number [1-5]:-"))
    if n == 1:
      name1 = input("enter name to SEARCH for phone number in the phone book")
      if not(name1 in d1.keys()):
        name1 = input("please enter someone who is already in your book")
      else:
        print("phone number of" ,name1, "is", d1[name1]) 
    elif n == 2:
        name = input("enter name:-")
        phono = (input("enter phone number:-"))
        d1[name]=phono
    elif n == 3:
        name1 = input("enter name to delete:-")
        d1.pop(name)
    elif n == 4:
        print(d1)
    elif n == 5:  
        break 

First off, I ordered the if statements by n so it is easier to read.首先,我将if语句按n排序,这样更容易阅读。

Note that indenting does matter in Python!请注意,缩进在 Python 中很重要! Whatever you want to run inside of an if statement must be indented inside of it.无论您想在if语句中运行什么,都必须在其中缩进。

The main issue is when n = 1 .主要问题是什么时候n = 1 This is because we do not know if name1 exists inside of d1 .这是因为我们不知道name1是否存在于d1中。 Therefore, we must first check if name1 exists inside of d1 before calling d1[name1] .因此,在调用d1[name1]之前,我们必须首先检查d1中是否存在name1

Moved up the validation and changed the code.向上移动验证并更改代码。

def menu():
    print("-------Lil Black Book--------")
    print("[1] Look up an entry")
    print("[2] Set an entry")
    print("[3] delete an entry")
    print("[4] List all entries")
    print("[5] Quit")
    print("what would you like to do (1-5)?")


menu()

d1 = {}
while True:
    n = int(input("enter number [1-5]:-"))
    if n == 2:
        name = input("enter name:-")
        phono = (input("enter phone number:-"))
        d1[name] = phono
    elif n == 1:
        name1 = input(
            "enter name to SEARCH for phone number in the phone book")
        if name1 != d1.get(name1,None): # Validate name exist
            print("entry not found")
        else:
            print("phone number of", name1, "is", d1[name])
    if n == 3:
        name1 = input("enter name to delete:-")
        d1.pop(name)
    elif n == 5:
        break

Test run.测试运行。

[1] Look up an entry
[2] Set an entry
[3] delete an entry
[4] List all entries
[5] Quit
what would you like to do (1-5)?
enter number [1-5]:-1
enter name to SEARCH for phone number in the phone bookDoe
entry not found
enter number [1-5]:-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试了解Python的exec()函数 - I'm trying to understand Python's exec() function 我试图了解如何打印数组的所有可能组合 - I'm trying to understand how to print all the possible combinations of a array 我正在努力了解如何使用cmd模块 - I'm trying to understand just exactly how to use the cmd module 我试图了解参考在 python 中的工作原理 - I'm trying to understand how reference works in python 我试图理解为什么在使用 paramiko 1.7.6 时会出现“Permission Denied”错误 - I'm trying to understand why I'm getting a “Permission Denied” error when using paramiko 1.7.6 我正在尝试编写代码,但出现此错误 - I'm trying to write a code but i got this error 我正在尝试编写一个用于在序列中添加/相乘的通用函数 - I'm trying to write a general function for adding/multiplying terms in a sequence 我想了解递归过程吗? - I'm trying to understand the recursion process? 我正在尝试在虚拟环境中安装 django 但出现一些错误,我不明白它是怎么回事 - I'm trying to install django in virtual environment but getting some error and I don't understand what is it about 我正在尝试使用 CSV 文件中的数据对饼图进行 plot 饼图,但出现错误,我不明白 - I'm trying to plot a pie chart using data from a CSV file but I'm getting an error I don't understand
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM