作者mikemike1021 (mike)
看板Python
标题[心得] 互动模式下 if 结束後不得接任何程式码
时间Thu Dec 15 00:05:23 2022
论坛程式码好读版:
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 档案,上面的程式码都不会出错。
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 69.246.242.212 (美国)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1671033925.A.D24.html