【发布时间】: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