簡體   English   中英

如何解決for循環python3中的if-else問題?

[英]How can I solve if-else problem in for loops python3?

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

Output 1:

enter name: alex

->tifanny

Output 2:

enter name: richard

->the name that you searched for is absent!

我想打印“bella”,但我的程序不這樣做。 我怎么解決這個問題?

  • 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!

對上述答案的改進是使用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!")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM