我的問題是我想讓 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```
uj5u.com熱心網友回復:
您可以and為此使用:
elif i.isdigit() and i not in address_book:
請注意,您可以使用它in來檢查字典中的鍵,因此您無需為此呼叫.keys()或將其轉換為串列。
uj5u.com熱心網友回復:
在您的字典中,鍵是字串,默認輸入法將字串作為輸入,將輸入作為 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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427561.html
下一篇:回圈并比較不同資料幀中的值
