为什么不能在 Python 中的 for 循环之前使用分号? [英] Why can't use semi-colon before for loop in Python?

查看:55
本文介绍了为什么不能在 Python 中的 for 循环之前使用分号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用分号在 Python 中连接行,例如

I can join lines in Python using semi-colon, e.g.

a=5; b=10

但是为什么我不能对 for 做同样的事情

But why can't I do the same with for

x=['a','b']; for i,j in enumerate(x): print(i,":", j)

推荐答案

简短(但有效)的答案只是因为语言 语法 未定义为允许它".至于为什么那样,除非你问谁想出了语法的那部分,否则很难确定,但我想这是由于可读性,这是目标之一Python1.

The short (yet valid) answer is simply "because the language grammar isn't defined to allow it". As for why that's the case, it's hard if not impossible to be sure unless you ask whoever came up with that portion of the grammar, but I imagine it's due to readability, which is one of the goals of Python1.

你为什么要写这样晦涩难懂的东西?把它分成多行:

Why would you ever want to write something obscure like that? Just split it up into multiple lines:

x = ['a','b']
for i,j in enumerate(x):
    print(i, ":", j)

我认为这个变体要清楚得多.

I would argue that this variant is much clearer.

1 来自 import this:可读性很重要.

这篇关于为什么不能在 Python 中的 for 循环之前使用分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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