【问题标题】:How can I solve if-else problem in for loops python3?如何解决for循环python3中的if-else问题?
【发布时间】:2021-04-01 12:24:34
【问题描述】:
list = [["alex","tiffany"],["richard","bella"],["bruno","jessica"]]

enter = input("enter name: ")

for i in list:

    if enter == i[0]:

        print(i[1])

    else:

        print("the name that you searched for is absent!")

    break

输出 1:

enter name: alex

->tifanny

输出 2:

enter name: richard

->the name that you searched for is absent!

我想打印“bella”,但我的程序没有这样做。我该如何解决这个问题?

【问题讨论】:

  • 想想循环逻辑——如果它不在第一个子列表中,你真的要打印它没有找到吗?跳出循环?
  • 首先不要使用变量名list list 实际上是一个内置关键字,其次它需要是列表的列表吗? dict 在这里会是一个更好的数据结构
  • 非常感谢您的帮助,我明白这个问题了,我很感激!

标签: python-3.x for-loop if-statement


【解决方案1】:
  • break 放错地方了。
  • 双倍行距违反标准格式标准
  • 单字母变量名只能用于索引变量
  • 命名变量 list 与可导入的 list 类型冲突。
  • 您需要跟踪是否找到该名称

要了解有关编写 Python 程序的标准的更多信息,请阅读PEP8;您还可以了解像 pylint 这样的 Python linter。

这是一个工作程序。它仍然可以更好,但我想让你可以识别程序:

names = [["alex","tiffany"],["richard","bella"],["bruno","jessica"]]
name = input("Enter name: ")
found = False
for item in names:
    if name == item[0]:
        print(item[1])
        found = True
        break
if not found:
    print("The name that you searched for is absent!")

它在行动:

$ python x.py
Enter name: richard
The name that you searched for is absent!
bella
The name that you searched for is absent!

$ python x.py
Enter name: richard
bella

$ python x.py
Enter name: x
The name that you searched for is absent!

【讨论】:

  • 非常感谢!这个解决方案打开了我的心态
【解决方案2】:

对上述答案的改进是使用for 循环的else 子句。这样你就不需要found 变量和第二个if

names = [["alex","tiffany"],["richard","bella"],["bruno","jessica"]]
name = input("Enter name: ")
for item in names:
    if name == item[0]:
        print(item[1])
        break
else:
    # This code will be executed if the for loop runs till its end
    # without 'break' being called.
    print("The name that you searched for is absent!")

【讨论】:

  • 非常感谢您的解决方案。我会记住的:))
猜你喜欢
  • 1970-01-01
  • 2020-03-24
  • 2022-12-07
  • 2019-07-03
  • 1970-01-01
  • 2017-08-02
  • 2019-12-04
  • 2021-09-16
  • 1970-01-01
相关资源
最近更新 更多