I’m currently teaching myself how to web scrape with python. Once I’ve worked out all the kinks in that, I’ll upload something on here to show you some tips and tricks on how it works, and where I went wrong/right along the way. In the meantime, I’ve been trying to figure out how to use loops in python.
So without further ado, here’s a quick little python ‘for’ loop tutorial:
So all I’ve done here is:
- Set the loop range to 5 by calling “range(5)”
- Told python to print the value of “i” for every iteration in the range of 5.
Here’s what I’ve learnt:
- You have to write the “:” to start the loop
- Everything in the loop needs to be indented, that’s how python knows where the loop starts and finishes.
- As you can see above, python indexes start at 0 and exclude the upper bound.
- So if you have a range of, say, 5 to 9, you would see: (5,6,7,8)
- If you have a range of 6 you would see: (0,1,2,3,4,5)
- You don’t have to call the iterations “i”, you can call them anything as long as you tell python the name. For example you could write “for rabbit in range(5) print (rabbit)” and get: (0,1,2,3,4)
Thanks for reading, and I hope you learnt something today!