导入后的for循环在Python一线式中不起作用 [英] For loop after import doesn't work in Python one-liner

查看:150
本文介绍了导入后的for循环在Python一线式中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用import,并且随后出现for,则会出现invalid syntax错误.我不知道为什么会这样.

If I use import and a for follows afterwards I get an invalid syntax error. I have no idea why this happens.

> python3 -c 'import os; for a in range(1,5): print(a)'
  File "<string>", line 1
    import os; for a in range(1,5): print(a)
                 ^

删除import效果很好:

> python3 -c 'for a in range(1,5): print(a)'
1
2
3
4

或完全删除for循环:

> python3 -c 'import os; print(10)'
10

那是怎么回事?

推荐答案

这是一个错误,因为它不在Python语法中.

It's an error because it's not in the Python grammar.

如果您查看复合语句的语法规范,则说明将会看到一个语句列表(即您使用分号所做的内容)被定义为:

If you check out the syntax specification for compound statements, you'll see that a statement list (i.e. what you're making with the semicolon) is defined as:

stmt_list ::= simple_stmt (";" simple_stmt)* [";"]

for构造不是simple_stmt,而是compound_stmt.

但是print(10)simple_stmt,因此就很好了.

The print(10), however, is a simple_stmt and, as such, is just fine.

这篇关于导入后的for循环在Python一线式中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆