我对 if 语句和数字有疑问

I have a problem with if statement and numbers

我的问题是我想让 elif 语句只对数字起作用,但 elif 语句对任何数据类型都起作用,有什么方法可以将字符串类型的数字与其他数据类型分开

代码

```address_book = {'1111': 'Amal', '2222': 'Mohammed', '3333': "Khadijah", '4444': 'Abdullah'}


def enter():
    i = input('Please Enter The number: ')
    if len(i) != 4:
        print('This is invalid number')
    elif i in list(address_book):
        print(address_book[i])
    elif i in list(address_book.values()):
        print(list(address_book.keys())[list(address_book.values()).index(i)])
    **elif i.isdigit() not in list(address_book.keys()):
        print('Sorry, the number is not found')
        m = input('do you want to add new number? ')
        if m == 'yes':
            d = input('Please Enter The new number: ')
            w = input('Please Enter the number owner name: ')
            address_book[d] = w
            f = input('Do yo want to see address book: ')
            if f == 'yes':
                print(address_book)
            else:
                pass**
        else:
            pass
    else:
        print('This is invalid number')


enter()```

输出

```Please Enter The number: sdaa
Sorry, the number is not found
do you want to add new number? yes
Please Enter The new number: 3333
Please Enter the number owner name: Waleed
Do yo want to see address book: yes
{'1111': 'Amal', '2222': 'Mohammed', '3333': 'Waleed', '4444': 'Abdullah'}

Process finished with exit code 0```

您可以为此使用 and

elif i.isdigit() and i not in address_book:

请注意,您可以使用 in 来检查字典中是否有键,因此您不需要为此调用 .keys() 或将其转换为列表。

在你的字典里,key是字符串,默认的输入法是字符串输入,输入int很简​​单

 i = int( input('Please Enter The number: '))

由于键是字符串格式,因此您必须在签入 elif 时将其转换为字符串。

elif str(i) in list(address_book):
elif str(i) in list(address_book.values()):
elif str(i) not in list(address_book.keys()):

完整代码:

address_book = {'1111': 'Amal', '2222': 'Mohammed', '3333': "Khadijah", '4444': 'Abdullah'}


def enter():
    i = int( input('Please Enter The number: '))
    if len(str(i)) != 4:
        print('This is invalid number')
    elif str(i) in list(address_book):
        print(address_book[i])
    elif str(i) in list(address_book.values()):
        print(list(address_book.keys())[list(address_book.values()).index(i)])
    elif str(i) not in list(address_book.keys()):
        print('Sorry, the number is not found')
        m = input('do you want to add new number? ')
        if m == 'yes':
            d = input('Please Enter The new number: ')
            w = input('Please Enter the number owner name: ')
            address_book[d] = w
            f = input('Do yo want to see address book: ')
            if f == 'yes':
                print(address_book)
            else:
                print(address_book) 
        else:
            pass
    else:
        print('This is invalid number')


enter()