0

Project to create a phone book, where is the mistake?!!

I try to do an exercise, the Requirements: Build a program that represents the phone book, so that it receives the phone number, and returns to us the name of the owner of the number. In the event that a number in the directory is sent, the name of the owner of the entered number will be printed, and in the event that a number that is not in the phone book is entered, the message will be printed: "Sorry, the number is not found" If the phone number is less than or more than 10 digits, or some other value (it contains letters, symbols, and logical values for example), the sentence will be printed: "This is invalid number"

My code is:

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)

If we enter a number from the numbers in the dictionary, it gives us an empty result!!!! e.x. if we enter '6666666666' what is in the dictionary we will get empty result

What is the rong?

coder
  • 1

1 Answers1

0

You have two issues:

  • The first and most important one is the scoping issue. Functions create their own namespace, so the namey variable in the function is different from the namey defined globally.
  • Then there is the fact that you try to compare a string (what your get from input) and an integer (the value in your dictionary).

Here's how you could make your code work:

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)

Notice that:

  • the input that we read is cast with int(qustion)
  • we use global namey at the beginning of the function to tell your function that it can modify the global variable named namey.
epap
  • 39
  • 4
  • [This response](https://stackoverflow.com/a/13383729/12824895) is a good starting point for understanding how global variables work overall. – epap May 31 '23 at 11:56