问题描述
我正在尝试python -mtimeit
,所以我放了python -mtimeit "n = 0; while n < 10: pass"
然后出现一个无效的语法错误.与分号和for循环相同.
I was trying out python -mtimeit
so I put python -mtimeit "n = 0; while n < 10: pass"
Then an invalid syntax error showed up. same with semicolon and for loop.
但是,当我尝试分号并单独循环时.两者都很好.
However, when I try semicolon and loop individually. Both worked fine.
python -c "for i in range(10): print(n)"
python -c "n = 1; n = 2; print(n)"
为什么会这样,如何在timeit循环中进行测试?非常感谢你!
Why is this so and how can I test while loop in timeit? Thank you very much!
推荐答案
while
,for
之前不能有分号,它们必须在一行上.如果您查看的是 Python语法:
while
, for
can't have semicolon before, they need to be on one line. If you looked at Python grammar:
compound_stmt ::= if_stmt
| while_stmt
| for_stmt
| try_stmt
| with_stmt
| funcdef
| classdef
| decorated
suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement ::= stmt_list NEWLINE | compound_stmt
stmt_list ::= simple_stmt (";" simple_stmt)* [";"]
您将看到 compound_stmt
一部分的语句必须为一行独自的.只能用分号分隔的语句是 simple_stmt
组:
you will see that the statements that are part of compound_stmt
need to be one one line alone. The only statements that can be separated by semicolon are simple_stmt
group:
simple_stmt ::= expression_stmt
| assert_stmt
| assignment_stmt
| augmented_assignment_stmt
| pass_stmt
| del_stmt
| print_stmt
| return_stmt
| yield_stmt
| raise_stmt
| break_stmt
| continue_stmt
| import_stmt
| global_stmt
| exec_stmt
这篇关于Python命令行参数分号循环错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!