for loop without arrays

+2 Pranav Gujarathi · August 18, 2016
What if I want to make for loops simply using an index i as we do in c++ , that is, have for loops like (for int i=0;i<n;i++)

Post a Reply

Replies

Oldest  Newest  Rating
+1 AJ Abrahamsen · August 28, 2016
Would something like range() work for you?

if you wanted to loop through the first 10 indexes you would say:

for i in range(0, 10):

The value of i would start at 0 and increase by 1 each loop.  The for loop would end with i having a value of 9.
+1 Drew Davis · August 29, 2016
In Python, if you wanted to loop a chunk of code a certain number of times, you could something like this.

for x in range(0, 5):
     print(x)

In this code, 0 is the number you start from, and 5 is the number of times you will loop through the code. Your console should look like this:
0
1
2
3
4

Hope that helps!
+1 Renan Ben Moshe · September 14, 2016
Actually, the default initial value of the range function is 0, so you only need:

for x in range(5):
     print(x)

This is the equivalent of declaring the variable x, setting an offset of 1 and iterating until x<5. 
0 M Jayanam · October 4, 2016
You can use a for loop with a range

for x in range(5):
  do something with x

Or you can do w while loop and increase x by 1

while True:
  x+=1
  • 1

Python

131,256 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator