-4

这是我的代码:

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 试图拆分它,但是那里什么都没有,我该如何解决?

4

2 回答 2

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, 这可以被根除。

于 2013-08-19T07:11:19.460 回答
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.

于 2013-08-19T07:14:13.260 回答