为什么我的代码打印不止一次?

时间:2017-02-13 05:00:06

标签: python

number = raw_input("Please enter the fixture number: ")
    myfile = open('file.txt')
    for line in myfile:
        item = line.split(',')
        if item[0] == number:
            title = '{0:20} {1:20} {2:20} {3:20} {4:20} {5:20}'.format('Fixture number', 'date', 'nickname1', 'nickname2', 'Fixture Played', 'Winning Nickname')
            print(title)
            result = '{0:20} {1:20} {2:20} {3:20} {4:20} {5:20}'.format(item[0],item[1],item[3],item[4],item[5],item[6])
            print(result)
        elif item[0] != number:
            print("not exist")

大家好,我是python的新手,所以最近我遇到了一个问题

elif item[0] != number:

正在为我文件中的行数打印“不存在” 如果错误,如何才能打印一次?

2 个答案:

答案 0 :(得分:1)

item[0] == numberTrue时设置标记。循环终止后检查此标志,如果设置了标志,则打印"not exist"

myfile = open('file.txt')
found = False
for line in myfile:
    item = line.split(',')
    if item[0] == number:
        found = True
        title = '{0:20} {1:20} {2:20} {3:20} {4:20} {5:20}'.format('Fixture number', 'date', 'nickname1', 'nickname2', 'Fixture Played', 'Winning Nickname')
        print(title)
        result = '{0:20} {1:20} {2:20} {3:20} {4:20} {5:20}'.format(item[0],item[1],item[3],item[4],item[5],item[6])
        print(result)

if not found:
    print("not exist")

另一种方法是将else选项与for循环一起使用,但是,这要求您只在第一次item[0] == number True时打印(因为您需要离开循环break以阻止else子句触发)。

答案 1 :(得分:0)

您可以将else子句附加到for loop,如下所示:

number = raw_input("Please enter the fixture number: ")
myfile = open('file.txt')
for line in myfile:
    item = line.split(',')
    if item[0] == number:
        title = '{0:20} {1:20} {2:20} {3:20} {4:20} {5:20}'.format('Fixture number', 'date', 'nickname1', 'nickname2', 'Fixture Played', 'Winning Nickname')
        print(title)
        result = '{0:20} {1:20} {2:20} {3:20} {4:20} {5:20}'.format(item[0],item[1],item[3],item[4],item[5],item[6])
        print(result)
        break
else:
    print("not exist")

注意break。 for循环将在第一次匹配后退出(通过break)。如果for循环正常终止(即不匹配),则else块将运行