【问题标题】:How to reference variables from previous iterations of a loop?如何从循环的先前迭代中引用变量?
【发布时间】:2018-02-17 06:11:18
【问题描述】:

这里的示例是 Python 3 中的一个程序,可以帮助您记住 pi 的数字。我尝试使用 var counter1 来显示当前分数,而 counter2 是上一轮的分数。但是,我无法使用 if 语句来打印您从上一轮改进了多少,因为我不允许在循环中的 if 语句之后引用 counter2。这应该怎么做?我觉得我的代码效率低下,感觉完全不对。 ct 变量试图仅在我们通过第一轮时才运行 if 语句。

def test():
  ans = (input("\nList the digits of pi! Three point... \nPi = 3."))
  if (ans).isdigit() == False:print("Oops! Numbers only!")
  counter1=0
  for i in range(0,(len(ans))):
      if ans[i] == pi[i]:
          counter1+=1
      else: break
  next = pi[counter1:counter1+6]
  if counter1==1: article=""
  else: article="s"
  print("\nYou got {0} digit{1}. \n\n{2}\n{3}".format(counter1, article, "3."+pi[0:counter1], (' '*(counter1+2))+next))
  if counter1!=counter2 and ct!=0:
    print("That's {0} more digits than the last time!".format(counter2-counter1))
  inp=input("Continue? Y/N")
  if inp=="N":
    exit()
  counter2=counter1
  ct+=1
  test()

ct=0
counter2=0
test()

【问题讨论】:

  • @OmarEinea 使用全局变量是discouraged
  • 你想达到什么目的..?

标签: python loops for-loop iteration


【解决方案1】:

您正在尝试(打破命名空间)是完全禁止和错误的。当您说要访问上次迭代中的变量时,您也使用了错误的词,实际上您要访问上次函数运行中的变量。

除非你在你的函数中传递之前的值

,否则没有办法做到这一点
def test(prev_value):
    ...
    ...

if not val:
    val = 0
val = test(prev_value=val)

【讨论】:

    【解决方案2】:

    我认为您的代码无法正常工作。这是您的修改。我使用while 作为重复条件。该函数可以接受输入test(vat1, var2, ..).


    代码:

    import math
    
    pi = str(math.pi);
    
    def test(prev, count):
        ans_pi = input("(Attempt no."+str(count)+") Please input the digits of Pi : 3.");
        if ans_pi.isdigit() != True:
            print("Retry, input must be numbers");
            return test(prev, count);
        else:
            current=0;
            for i in range(len(ans_pi)):
                if ans_pi[i]==pi[2+i]:
                    current+=1;
                else:
                    break;
            print("\nYou got {} digit(s). \n\n".format(current))
            if current!=prev and count>1: 
                print("That's {} more digit(s) than the last time! \n \n".format(current-prev)) 
    
            while(input("Continue? (Y) \n\n").capitalize() == "Y"):
                prev=current;
                count+=1;
                return test(prev, count);
            exit();
    
    prev=0;
    test(prev,1)
    

    示例输出:

    (Attempt no.1) Please input the digits of Pi : 3.145
    
    You got 2 digit(s).
    
    
    Continue? (Y)
    
    y
    (Attempt no.2) Please input the digits of Pi : 3.14156
    
    You got 4 digit(s).
    
    
    That's 2 more digit(s) than the last time!
    
    
    Continue? (Y)
    
    n
    

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 1970-01-01
      • 2021-04-12
      • 2019-06-01
      • 2020-03-03
      • 2012-08-02
      • 2012-09-10
      • 2020-05-14
      • 2019-11-29
      相关资源
      最近更新 更多