英文:
What is a counter and how is it used in Python loops?
问题
可以有人解释一下什么是计数器吗?
所以我有这两个示例:
n=0
while n < 5:
print(n)
n=n+1
mysum =0
for i in range(7,10):
mysum += i
print(mysum)
它说要在循环内使用计数器,而对于for
和while
,你需要在循环外设置while
,但它根本没有解释什么是计数器,我对while
和for
中的计数器是什么非常困惑。
我尝试在网上搜索,得到的回答是计数器是告诉迭代发生多少次的东西,但我仍然不清楚。
英文:
Can someone explain to me what is a counter ?
So i have these two examples:
n=0
while n < 5:
print(n)
n=n+1
mysum =0
for i in range(7,10):
mysum += i
print(mysum)
It says that for use a counter inside the loop, while for while, you need to set up the while outside of the loop, but it didint explain what is a Counter at all, and i am very confused of what is the counter in while and for.
I tried search it online ,and i got counter is the one telling how many times the iteration happens, which I am stil unlcear
答案1
得分: 1
基本上,计数器是在存在条件或要应用于重复多次的过程时进行计数的东西。比如,如果要打印100个数字的和,就需要一个计数器来达到100。
n=0
while n < 5:
print(n)
n=n+1
到目前为止,在你的第一段代码中,n 表现得像一个计数器,尽管它只是从用户那里获取的一个数字或输入,它会一直工作直到满足条件,比如打印数字的和,直到它们小于5。
mysum = 0
for i in range(7, 10):
mysum += i
print(mysum)
但在第二段代码中,i 表现得像一个计数器变量,因为在 for 循环 中应该有计数器元素。因此,它将运行由计数器声明的次数。
英文:
Basically, the counter is something that counts whenever there exits a condition or you want to apply it for the process that repeats more than one time. As printing a sum of 100 numbers then you must require a counter to reach the number 100.
n=0
while n < 5:
print(n)
n=n+1
So far in your 1st code n is behaving as a counter though it's just a number taken from the user or as input, it will work till your condition is fulfilled like printing the sum of numbers till they are less than 5.
mysum =0
for i in range(7,10):
mysum += i
print(mysum)
But for the 2nd code i is behaving as a counter variable as for for loop counter element should be present there. So it will run that number of times as declared by the counter.
答案2
得分: 0
计数器会记录程序通过循环迭代的次数。在你的第一个代码示例中,变量 n
是计数器。在第二个示例中,i
是计数器。
在许多编程语言中(如Python),for
循环使编写涉及计数器的循环更简单。然而,在特别是Python中,for
循环也可以用于许多其他用途。
英文:
A counter keeps count of how many times the program iterates through the loop. In your first code example, the variable n
is the counter. In your second example, i
is the counter.
In many programming languages (such as Python), for
-loops make it simpler to write loops that involve a counter. However, in Python in particular, for
-loops can be used for many other things too.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论