in Python:
ele = 0
for ele in range(0,4):
print('-')
print(ele)
I realized that this will print 3 instead of 4 in the end, which is different from C-style for loop. is while the option to achieve C-style behavior?
You can add an independent variable to count the loop iterations with enumerate():
N = 4
items = range(0, N)
i = 0
for i, x in enumerate(items, 1):
print(i, ":", x)
print("number of loop iterations done:", i)
You should make sure to reset the value before the loop, as it is not set to zero, when the loop did not iterate even once.
For reference:
In python the range function works differently, if you want to print something N times try this:
ele = 0
for i in range(N):
print("-")
print(ele)
Also is not the only approach you could take for printing, you can also:
print("-\n"*(N-1) + "-" + ele)
The range() function works in different ways:
You can also refer to the official documents: docs.python.org/3/library/functions.html#func-range
Hope this helps :D!
ele = 0
for ele in range(0,4):
print('-')
print(ele+1)
A for with a range is roughly equivalent to a for on a list, i.e. your loop could also be written as:
for ele in [0, 1, 2, 3]:
print('-')
If you want ele to be equal to the number of loops after executing the for instruction, you could also write:
for ele in [1, 2, 3, 4]:
print('-')
which can be rewritten using range as:
for ele in range(1, 5):
print('-')
since range goes from the first parameter to the number immediately before the second parameter.
print(ele+1)?for ele in range(1,5):?for .... else ...where the else clause will only be executed if the loop wasn't terminated using abreak. (In C you would check the value of ele and if it is 4, you'd know the loop wasn't terminated using a break, hence this suggestion)