簡體   English   中英

在代碼搜索完列表並且找不到列表中的單詞從而答復錯誤后,如何打印?

[英]How do you print after the code is done searching through the list and it can't find the word in the list so it replies error?

我有一個for循環,因此它可以遍歷整個列表,但是我如何像最后一行那樣輸入,因為沒有名為Bob的星星,並說這是錯誤?

big_str = "0.998448,0.035746,-0.042707,352,6.18,14\n0.873265,0.031968,0.486196,358,2.07,15,ALPHERATZ\n0.512379,0.020508,0.858515,432,2.28,21,CAPH\n0.883455,0.044652,-0.466383,720,5.41,34\n0.963482,0.055705,0.261913,886,2.83,39,ALGENIB\n0.752989,0.044458,0.656529,905,5.71,41"

def getStarString(n):
  line_list = big_str.split("\n")
  for x in line_list:
    y = getStarName(x)
    if y == "None":
        continue
    else:
        if y == n:
            print(x)
        if y != n:
            continue
            if y != n:
                print("ERROR: No star called " + n + " could be found.")
def getStarName(name):
  names = list(name.split(","))
  for i in range(0, len(names)):
    if len(names) == 7:
        x = names[6]
        return x
    else:
        return "None"

getStarString("ALGENIB")
getStarString("BOB")

getStarString可能是正確的,如下所示:

def getStarString(n):
  line_list = big_str.split("\n")
  for x in line_list:
    y = getStarName(x)
    if y == "None":
        continue
    elif y == n:
            print(x)
            return
  print("ERROR: No star called " + n + " could be found.")

輸出為:

0.963482,0.055705,0.261913,886,2.83,39,ALGENIB
ERROR: No star called BOB could be found.

找到匹配項時跳出循環。 然后,使用forelse:子句打印一條消息,如果該消息未中斷則結束。

def getStarString(n):
  line_list = big_str.split("\n")
  for x in line_list:
    y = getStarName(x)
    if y != "None" and y == n:
        print(x)
        break
  else:
    print("ERROR: No star called " + n + " could be found.")

暫無
暫無

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

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