为什么这会给我一个错误,我该如何解决?

时间:2013-08-19 07:10:05

标签: python python-3.x

这是我的代码:

line = ' '
while line != '':
    line = input('Line: ')
    phonic = line.split()
    start = phonic[0]
    start_4 = phonic [3]
    a = start[0]
    if start_4.startswith(a):
        print('Good!')
    else:
        print("That's not right!")

我想我知道,自从line = ''以来,phonic正试图分裂它,但那里什么都没有,我该如何解决?

2 个答案:

答案 0 :(得分:5)

在你做任何其他事情之前,你会想要一个条件陈述:

line = ' '
while line:
    line = input('Line: ')
    if not line:
        break # break out of the loop before raising any KeyErrors
    phonic = line.split()
    start = phonic[0]
    start_4 = phonic [3]
    a = start[0]
    if start_4.startswith(a):
        print('Good!')
    else:
        print("That's not right!")

请注意,while line != ''可以简单地缩短为while line,因为''被视为False,因此!= False== True,这是可以根除。

答案 1 :(得分:0)

使用while True创建无限循环,并使用break结束它。现在,您可以在读取空行时立即结束循环,并在尝试寻址不存在的元素时不会失败:

while True:
    line = input('Line: ')
    if not line:
        break

    phonic = line.split()
    start = phonic[0]
    start_4 = phonic [3]
    a = start[0]
    if start_4.startswith(a):
        print('Good!')
    else:
        print("That's not right!")

请注意,您甚至不必仅仅测试if line;在if等布尔测试中,空字符串被视为false。