【问题标题】:For-loop inside while-loop error - Python循环内的for循环错误 - Python
【发布时间】:2018-08-04 20:12:20
【问题描述】:

以下 Python 代码在 while 循环内的 for 循环中的“:”上给出了语法错误。如果删除了 for 循环,代码可以正常工作。已经搜索了这个网站并用谷歌搜索了这个问题没有答案。我正在学习 Python。想了解问题出在哪里。谢谢。

banana = True
orange = 0
print("Test1")
while(orange < 10):
    print("Test Orange %s" % orange)
    for(banana == True):
        print("Test Banana")
        banana = False
    orange += 1

【问题讨论】:

  • 你希望 for 循环做什么?
  • for 循环需要循环条件/计数器,而不是条件语句。那是您的代码中的错误。在此处阅读文档:docs.python.org/3/tutorial/controlflow.html#for-statements
  • 你为什么认为for(banana == True):应该引发语法错误?
  • 你可能只想做if banana is True而不是for。
  • 感谢您的链接。我希望 for 循环像 while 循环一样执行。执行 for 循环中的任何操作,直到该条件不再成立。此初始测试的最终结果是执行 for 循环的操作 x 次,具体取决于另一个变量。我刚刚开始使用它作为一个占位符。

标签: python for-loop while-loop syntax-error colon


【解决方案1】:

错误不是因为冒号:。您正在使用for循环检查banana == Truefor loop的结构不是这样使用的。请改用 while 循环。

while(orange < 10):
    print("Test Orange %s" % orange)
    while(banana == True):
        print("Test Banana")
        banana = False
    orange += 1

【讨论】:

  • 为什么不只是一个if
  • if 也可以,看来他想使用循环。这就是为什么我建议while。 @IşıkKaplan
【解决方案2】:
for(banana == True):

此行不正确。 你想使用 if 吗?像这样。

banana = True
orange = 0
print("Test1")
while(orange < 10):
    print("Test Orange %s" % orange)
    if banana == True:
        print("Test Banana")
        banana = False
    orange += 1

【讨论】:

  • 检查bool对象与True是否相等根本不是一个好主意,写if banana
  • 是的,我知道。但为了他简单起见,我这样说。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
相关资源
最近更新 更多