[心得] 互动模式下 if 结束后不得接任何程式码

楼主: mikemike1021 (mike)   2022-12-15 00:05:23
论坛程式码好读版:https://forum.community.tw/t/topic/475
顺便再宣传一下 community.tw,最近在举办抽奖活动,详情见论坛内的置顶活动内容
这是一个无广告的论坛,自动程式码着色、上标签等,方便大家分享程式码讨论
也避免用贴图片的方式,这样之后也比较容易搜寻到,详情可见 #1Yukoxd2
本文开始
>>> a = 5
>>> if a == 5:
... print("a is 5")
... else:
... print("a is not 5")
... print("if-else end")
先猜猜看,在 python interactive mode 这样会不会正常执行呢?
答案是会跳出 SyntaxError: invalid syntax 错误
找了一下资料,Stack Overflow: read eval print loop - Why am I getting an invalid syntax error in Python
REPL right after IF statement?
这里有提到
The body of the loop is indented: indentation is Python’s way of grouping
statements. At the interactive prompt, you have to type a tab or space(s) for
each indented line. In practice you will prepare more complicated input for
Python with a text editor; all decent text editors have an auto-indent
facility. When a compound statement is entered interactively, it must be
followed by a blank line to indicate completion (since the parser cannot
guess when you have typed the last line). Note that each line within a basic
block must be indented by the same amount.
有清楚指出在 interactive mode 一定要用空白行作为最后一个区块的结束
但这只有限制在最后一个区块,所以多用函数包住,就可以让 print 直接在 if 结束之
后使用,但函数结束后还是只能空白行结束;以及限制在interactive mode,所以在
jupyter notebook 或者写成 python 档案,上面的程式码都不会出错。

Links booklink

Contact Us: admin [ a t ] ucptt.com