【问题标题】:While loop inside of for loop [closed]for循环内的while循环[关闭]
【发布时间】:2014-03-22 17:53:09
【问题描述】:

我正在尝试执行使用两个嵌套循环的 Python 脚本。
第一个是 for 和第二个(嵌套的一个是 while)。

这是我的代码:

for currentData in data:
    currentState = ''
    count = 0
    while currentState == '': 
        currentState = someMetdhodExecution() ...
        count++

当我将while 放入for 中时,脚本崩溃。

请帮我解决这个问题。

提前谢谢你!

【问题讨论】:

  • 请格式化您的代码。使用四个空格将行标记为代码。
  • count++ 语法无效。
  • “崩溃”是什么意思?
  • 请准确说明错误。 Python 会为您生成详细的错误回溯,您应该在此处显示。
  • count++ -> count += 1

标签: python loops for-loop while-loop


【解决方案1】:

for 循环中包含while 循环并没有错。

演示:

i = 0
kebab = ["chicken","garlic","cheese","tomato","lettuce","chilli"]    
print "Kebabs are so good, this is what mine has:"
excitement_over_kebab = 1    

for ingredients in kebab:    
    while excitement_over_kebab == 1:
        print kebab[i]
        i+=1
        if i == 6:
            print "Enough talk, my lunch break is over."
            excitement_over_kebab = 0

输出:

Kebabs are so good, this is what mine has:
chicken
garlic
cheese
tomato
lettuce
chilli
Enough talk, my lunch break is over.

【讨论】:

  • 你让我饿了。干得好。
【解决方案2】:

你的程序没有崩溃,它应该给你一个SyntaxError(至少,它不是执行错误)。 Python 中不存在语法count++。你应该使用count += 1:

for currentData in data:
    currentState = ''
    count = 0
    while currentState == '': 
        currentState = someMethodExecution() ...
        count += 1
        #     ^^^^  note the modification here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-14
    • 2016-03-25
    • 2019-11-10
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 2023-04-09
    相关资源
    最近更新 更多