fruits = ["mango", "banana", "apple", "yolk", "mulberry"]
letter = input("Enter the letter you want to search: ")
letter2 = input("Enter the second letter you want to search: ")
for word in fruits:
if word[0].startswith(letter) and word[1].startswith(letter2):
result = word
if result == word:
print(result)
else:
print("no result")我使结果部分正常工作,但是每当输入错误的输入时,“无结果”输出就不会显示。
发布于 2022-10-31 15:13:24
你为什么拿“开始”做比较?您可以像这样直接进行比较:
if word[0] == letter1 and word[1] == letter2:做这样的事:
fruits = ["mango", "banana", "apple", "yolk", "mulberry"]
letter = input("Enter the letter you want to search: ")
letter2 = input("Enter the second letter you want to search: ")
result = ""
for word in fruits:
if word[0] == letter and word[1] == letter2:
result = word
break
if len(result) > 0:
print(result)
else:
print("no result")发布于 2022-10-31 15:19:14
你也可以像这样使用你的代码
fruits = ["mango", "banana", "apple", "yolk", "mulberry"]
letter = input("Enter the letter you want to search: ")
letter2 = input("Enter the second letter you want to search: ")
flag = False
result=""
for word in fruits:
if word[0].startswith(letter) and word[1].startswith(letter2):
flag = True
result = word
if(flag == False):
print("no result")
else:
print(result)发布于 2022-10-31 15:21:11
您不需要使用嵌套的if和else条件。请记住,此代码将比较列表中的每一项,并显示每个结果,无论它们是否匹配。
fruits = ["mango", "banana", "apple", "yolk", "mulberry"]
letter = input("Enter the letter you want to search: ")
letter2 = input("Enter the second letter you want to search: ")
for word in fruits:
if word[0].startswith(letter) and word[1].startswith(letter2):
print(word)
else:
print("no result")https://stackoverflow.com/questions/74265295
复制相似问题