I’m in the ‘for Loops and the range() Function’ part of Automate the Boring Stuff’s chapter 2, and while I understand how the function itself works, the variable is beyond me.
for i in range(10):
print("This will show up ten times")
#I got the above from a Python tutorial video
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
#I got the above from Automate the Boring Stuff chapter 2
In the first example, this one is very simple, but I don’t see the variable i get assigned anything, and it confuses me how that works. For the second example, I can see it’s using an assigned variable, so that part makes sense to me. I do not understand (‘ + str(i) + ‘)’) too well, however. What’s in it is generally daunting, and it’d be great if someone couple explain how this works. I understand it’s functionality, but if I were going off of memory, the first one seems much simpler to use.
>Solution :
So you can think of range(10) as a list of numbers from zero to 9 [0, 1, 2, .., 9]
when we loop through this list of numbers we assign the variable i to a number on this list.
ex:
loop1: i=0
loop2: i=1
loop3: i=2
loop4: i=3
and so on.
In the first example, you didn’t use the variable i in anything so simply it didn’t appear
In the 2nd one: we use 'Jimmy Five Times (' + str(i) + ')'
which means adding the string 'Jimmy Five Times (' to the variable i (after changing it from integer into string) then adding ')' at the end, and this process is called concatenating strings.
NOTE: You can’t add int to str that’s why we used str(i)
ex:
loop1: i=0 -> ‘Jimmy Five Times (0)’
loop2: i=1 -> ‘Jimmy Five Times (1)’
loop3: i=2 -> ‘Jimmy Five Times (2)’
loop4: i=3 -> ‘Jimmy Five Times (3)’