In python to create a range (an ordered sequential list of numbers), we can use the range function. For example, if we wanted a variable my_range to hold a list of numbers from 1 to 10, we can use
my_range = range(1,11)
range function accepts 2 parameters, start and end and it'll generate those numbers while excluding the last number.
You can optionally pass in a 3 number to use as the step parameter which is defaulted to 1 so for example if you wanted a list of numbers that goes backward from 11 to 1 you can use
my_range = range(11,0,-1)
You can create a loop that loops over each element of a list and execute some code (inside the loop indicated by indentation that is one level deeper after the for loop statement) by using:
The indentation (of the print statement) of the code after the for loop statement indicates that that code belongs to the loop. You can have multiple lines of code to run in the loop. You'll just have to indent the lines the same way to indicate that they're the same block of code.
Code: Select all
for item in range(1,11): print (item)
Notice the colon (:) at the end of the for statement indicating that the beginning of a block of code.
So the loop will loop over all items of range(1,11) (1-10) and set
itemvariable to hold the value of current item in list and as it executes it'll print out item each time through the loop.
Try out what you've learned so far here.
Next lesson: If... Else... in Python Previous lesson: Lists in Python