为什么这会给我一个错误,我该如何修复它?

2024-10-03 04:30:37 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

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试图分割它,但是那里什么都没有,我该如何修复它?你知道吗


Tags: 密码inputifthatlinenotstartelse
2条回答

使用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这样的布尔测试中,空字符串被认为是错误的。你知道吗

在执行任何其他操作之前,您需要一个条件语句:

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,这是可以消除的。你知道吗

相关问题 更多 >