为什么这一行给我语法错误?

2024-03-28 21:46:34 发布

您现在位置:Python中文网/ 问答频道 /正文

import random;  while True: print (random.randrange (1, 100 + 1, 2))

我试图生成无穷多的奇数,范围从1到100


Tags: importtruerandom奇数printrandrangewhile
1条回答
网友
1楼 · 发布于 2024-03-28 21:46:34

分号不能用于连接任意语句,只能连接“小”语句:

stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
             import_stmt | global_stmt | nonlocal_stmt | assert_stmt)

小语句是(粗略地说)任何不涉及缩进的语句。你知道吗

相反,您需要使用文字换行符来分隔导入和循环。如果您的shell支持它,您可以使用

python -c $'import random\nwhile ...'

否则,您需要放宽对“一行”的定义:

python -c 'import random
while ...
'

相关问题 更多 >