【问题标题】:Changing a for loop's previous entry更改 for 循环的上一个条目
【发布时间】:2020-07-03 07:52:12
【问题描述】:

是否可以在 for 循环运行后更改它,然后在下一次迭代中返回并更改它?

#the code example
score = 50
running = True
while running:
    for rounds in range(0, 6):
        for rounds in range(0, 6):
           if input() == x:
           score - 3
           print(score)
         elif input() == y:
           score - 2
           print(score)
         elif input() == z:
           score - 1
           print(score)
         elif input() == **change**:
            #Edit previous loop input because of an error or typo(x should have been z previous iteration) #How would one make this happen?

【问题讨论】:

  • 您能否详细说明更改循环的含义?
  • 我不太明白你的问题。但是一件事是错误的,您在内部循环中重用了变量rounds。您应该为该名称使用不同的名称。
  • 无法撤销。如果你运行代码,它已经发生了。最好的办法是在运行和进行测试之前检查拼写错误。
  • 我想让输入改变分数,在我们通过循环时降低分数。但是如果前一个循环的前一个输入是错误的,它可以在当前循环中改变它。我收到了一个答案,说我可以添加相同的数量来修复它。

标签: python for-loop iteration


【解决方案1】:

我不认为 Loop 可以退回一次或几次迭代。问题在于您希望它返回的迭代次数。 尽管可以通过反转操作来实现您的用例,但您正在这样做。

#the code example
score = 50
running = True
while running:
    for rounds in range(0, 6):
        for rounds in range(0, 6):
           if input() == x:
           score - 3
           print(score)
             elif input() == y:
               score - 2
               print(score)
             elif input() == z:
               score - 1
               print(score)
             elif input() == undoX:
               score + 3
               print(score)
             elif input() == undoY:
               score + 2
               print(score)
             elif input() == undoZ:
               score + 1
               print(score)

实现它的粗略方法是 undoX(一次操作反转)、undoX2(两次操作反转)等。 input() 的进一步数据类型未知;如果它是整数,则可以用“-x”替换“undoX”。 如果您想在撤消操作后保持迭代次数不变,而不是将 range(0,6) 更改为 range(0,iterations) 并在修改后的情况下写入;

            elif input() == undoX:
               score + 3
               iterations+1 //To keep no. of iterations intact with every undoOperation
               print(score)

【讨论】:

    猜你喜欢
    • 2013-08-14
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    • 1970-01-01
    相关资源
    最近更新 更多