Yol*_*and 5 python bash timeit
我正在尝试,python -mtimeit所以我把python -mtimeit "n = 0; while n < 10: pass"
然后出现了无效的语法错误.与分号和循环相同.
但是,当我尝试分号并单独循环时.两者都很好.
python -c "for i in range(10): print(n)"
python -c "n = 1; n = 2; print(n)"
Run Code Online (Sandbox Code Playgroud)
为什么会如此?如何在timeit中测试while循环?非常感谢你!
小智 10
while,for之前不能有分号,它们需要在一条线上.如果你看一下Python语法:
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)* [";"]
Run Code Online (Sandbox Code Playgroud)
你会看到那些声明只compound_stmt需要一行一行.可以用分号分隔的唯一语句是simple_stmtgroup:
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
Run Code Online (Sandbox Code Playgroud)