当我运行以下代码时,我得到一个错误:“IndentationError:unident不匹配任何外部缩进级别”。在
我做错什么了?我在下面列出了我的代码以供参考:
file=open('csquetionseasy.txt','r')
print(file.read(432))
answersinputeasy=input('enter the letter responding to the correct answer for all 3 questions e.g. BBB')
if answersinputeasy==('BAA'):
print('you got 3/3!')
else:
if answersinputeasy==('BAB'):
print('2/3!')
else:
if answersinputeasy==('BBB'):
print('1/3!')
else:
if answersinputeasy==('ABB'):
print('0/3!')
else:
if answersinputeasy==('AAB'):
print('1/3!')
else:
if answersinputeasy==('AAA'):
print('2/3!')
else:
if answersinputeasy==('ABA'):
print('1/3!')
出现错误
"IndentationError: unident does not match any other indentation level"
的原因是,您将选项卡链接在一起以创建嵌套逻辑语句(在伪代码中):这不是Python喜欢在逻辑块中看到语法的方式。此外,您将遇到的下一个错误是在else子句中使用嵌套if语句。在
要在Python中运行
^{pr2}$else if
语句,您需要使用语法elif:
,后跟一个缩进行,其中包含满足该条件时要执行的代码(在伪代码中):另一个最佳实践是,如果您不打算对从用户那里获得的字符串进行任何进一步验证,那么您应该在条件块中包含一个显式的
else
子句,其中包含一组elif
语句。假设用户传入XYZ
。它们不会满足您定义的任何条件,因此代码将继续从这个逻辑块的底部继续(这可能是一件好事,也可能不是好事)。在下面的代码中,我添加了一个示例,说明显式else
子句可能是什么样子,但最终由您决定什么对您的应用程序有意义:使用}语句的结果为false时,需要
elif
而不是else
。当if
和{else
语句来执行某些操作。在另外,如果要指示代码块,则必须将该块的每一行缩进相同的量,通常是四个空格。在
相关问题 更多 >
编程相关推荐