python编程如何使用循环从字典列表中排除if语句的值



如何使用python编写循环,字典和if语句的命令如果我想从字典列表中输出结果,并为其他输入打印一个句子这是我的程序,谁能找到解决这些错误的方法?

def phone_guide():
guide_number = input("Enter a number:")

numbers = {"Amal": 1111111111, "Mohammed": 2222222222, "Khadijah": 3333333333, "Abdullah": 4444444444}

While guide_number == 1111111111:
print("Amal")

elif guide_number == 2222222222:
print("Mohammed")

elif guide_number == 3333333333:
print("khadijah")

elif guide_number == 4444444444:
print("Abdullah")

elif guide_number != numbers:
print("Sorry, the number is not found")

#This mean the number has to be from the dictionary list

else:
print("This is invalid number")

#This mean if the number less or more than 10 number or different value or string 
phone_guide()

您需要解决多个问题。缩进是错误的,循环有问题。您需要遍历字典并检查value是否存在。

def phone_guide():
print "Enter a number:"
guide_number = input()
numbers = {"Amal": 1111111111, "Mohammed": 2222222222, "Khadijah": 3333333333, "Abdullah": 4444444444}
for key,value in numbers.items():
if guide_number == value:
print(key)
return
print("Sorry, the number is not found")
phone_guide()

首先,如果您想要检查号码,则存储name: number是不必要的复杂。有可能像number: name那样逆转它吗?numbers = {1111111111: "Amal", 2222222222: "Mohammed", ...}

其次,你不需要所有这些if/elif/else语句。您可以检查项是否在字典的键或值中。1111111111 in numbers.keys()1111111111 in numbers.values()

要匹配您的电话号码有效性,您可以使用像这样的正则表达式并检查typeof(phone_number) == int.

import re
invalid = 1234568
valid = 0123456789
re.match(r'd+{10}', valid)
>>> True
re.match(r'd+{10}', invalid)
>>> False

给定所有这些信息,你应该能够得出解决方案。

您的代码中有多个错误。再看一遍python的基础知识。

def phone_guide():
guide_number = int(input("Enter a number:"))
numbers = {"Amal": 1111111111, "Mohammed": 2222222222, "Khadijah": 3333333333, "Abdullah": 4444444444}
for key, value in numbers.items():
if guide_number == value:
return key
return "This is invalid number"
def phone_guide():
guide_number = input("Enter a number:")
numbers = {"Amal": 1111111111, "Mohammed": 2222222222, "Khadijah": 3333333333, "Abdullah": 4444444444}
if guide_number == 1111111111:
print("Amal")
elif guide_number == 2222222222:
print("Mohammed")
elif guide_number == 3333333333:
print("khadijah")
elif guide_number == 4444444444:
print("Abdullah")
elif guide_number != numbers:
print("Sorry, the number is not found")
else:
print("This is invalid number")

按照上面的方法编写代码。在python中,你只能在if后面使用elif。

相关内容

  • 没有找到相关文章

最新更新