简体   繁体   中英

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?

I have a for loop so it can go through the whole list but how do I input for like the very last line that there is no star named Bob and say that it is an error?

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 may be correct as follows:

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.")

The output is:

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

Break out of the loop when you find a match. Then use the else: clause of for to print a message if it ended without breaking.

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.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM