Python电话簿程序没有返回字典中数字的预期结果,如何解决?

ej83mcc0  于 2023-06-07  发布在  Python
关注(0)|答案(1)|浏览(159)

创建一个电话簿项目,错误在哪里?!!
我试着做一个练习,要求:构建一个表示电话簿的程序,以便它接收电话号码,并向我们返回号码所有者的姓名。如果发送的是电话簿中的号码,则将打印输入号码的所有者的姓名,如果输入的号码不在电话簿中,则将打印消息:如果电话号码少于或多于10位数,或其他值(例如,它包含字母,符号和逻辑值),则会打印句子:“这是无效号码”
我的代码是:

namephone = {'Amal':1111111111, 
             'Mohammed':2222222222,
             'Khadijah':3333333333,
             'Abdullah':4444444444,
             'Rawan':5555555555,
             'Faisal':6666666666,
             }

namey = ''

def serch(h):
    for x, y in namephone.items():
        if y == h:
            namey = x
            continue
        else:
            namey = 'Sorry, the number is not found'
    return namey
    
qustion =input("pleas inter number")

if qustion.isdigit() and len(qustion )== 10:
    serch(qustion)
else:
    print('This is invalid number')

print(namey)

如果我们从字典中输入一个数字,它会给我们一个空的结果!!!!e.x.如果我们输入'666666666'字典中的内容,我们将得到空结果
荣是什么?

b4lqfgs4

b4lqfgs41#

您有两个问题:

  • 第一个也是最重要的一个是范围问题。函数创建自己的命名空间,因此函数中的namey变量与全局定义的namey变量不同。
  • 然后是你试图比较一个字符串(你从输入中得到的)和一个整数(字典中的值)的事实。

下面是如何让你的代码工作:

namephone = {'Amal':1111111111, 
             'Mohammed':2222222222,
             'Khadijah':3333333333,
             'Abdullah':4444444444,
             'Rawan':5555555555,
             'Faisal':6666666666,
             }

namey = ''

def serch(h):
    global namey
    for x, y in namephone.items():
        if y == h:
            print("found")
            namey = x
            break
        else:
            namey = 'Sorry, the number is not found'
    return
    
qustion =input("pleas inter number")

if qustion.isdigit() and len(qustion )== 10:
    serch(int(qustion))
else:
    print('This is invalid number')

print("name_y:", namey)

请注意:

  • 我们读取输入被转换为int(qustion)
  • 我们在函数的开头使用global namey来告诉你的函数它可以修改名为namey的全局变量。

相关问题