我是编程新手,并尝试从automatetheboringstuff.com学习Python。 在第2章末尾,出现了以下问题。 即使在我通过官方答复之后,我仍然无能为力。 请帮忙!
问:8。确定此代码中的三个块:
spam = 0 if spam == 10: print('eggs') if spam > 5: print('bacon') else: print('ham') print('spam') print('spam')
官方回答:
这三个块是if语句和行内的所有内容
print('bacon')
和print('ham')
。print('eggs') if spam > 5: print('bacon') else: print('ham') print('spam')
答案 0 :(得分:2)
每次增加一行的缩进时都会开始一个新块,并在相应的unindent之前结束。
spam = 0
if spam == 10:
print('eggs') # indent increased, block A
if spam > 5: # still block A
print('bacon') # still block A, indent increased, block B inside block A
else: # still block A, indent decreased, block B ended in line above
print('ham') # still block A, indent increased, block C inside block A
print('spam') # still block A, indent decreased, block C ended in line above
print('spam') # indent decreased, block A ended in line above