Question about Python thema : conditional statements with Loops
Hello,
I've practiced with your files, but i've faced with some problems.
I can not understand the process of the below program
n = [1,2,3,4,5,6]
for x in range(len(n)):
print(n[x] * 10, end = " ") Output :
for x in range(len(n)):
print(n[x] * 10, end = " ") Output :
10 20 30 40 50 60
how can the output like above come out?
I guess,
n = [1,2,3,4,5,6]
len(n)
this output must be 6
and list(range(len(n)))
this output must be
0, 1, 2, 3, 4, 5
then i think the value of x contains range(len(n)) (0,1,2,3,4,5)
and the output should be 0,10,20,30,40,50
i can't just understand how this program works!
and i would like to ask for this statement : print(n[x] * 10, end = " ")
why should i write down n[x]?
or.. I guess n[x] that could be slicing?
can you explain it ?
thanks for reading
Daehyeon Kim
1 answers ( 0 marked as helpful)
Hi Daehyeon!
Thanks for reaching out.
Please accept my apologies for the delayed response.
This is a great question, indeed! In fact, you've nearly found out the explanation you are looking for, you have correctly pointed the problem.
When you are referring to n[x], think of indexing in Python. Moreover, we obtain the value of x from the sequence of numbers generated by the range() function (that you have correctly said becomes 0, 1, 2, 3, 4, 5).
Therefore, it turns out we want to print n[0], n[1], ..., n[5], which start by the 0-th element from the list n (i.e. the element at position 1 from the list n), which is the value of 1. Hence, the output of n[x] * 10 for the first element equals n[0] * 10 = 1 * 10 = 10.
The next element is at position 2, written as n[1], which is the values of 2. Hence, the relevant output is 20. And so on until we eventually obtain 50 and the loop ends.
Apparently, this operation may look a little confusing at first, but this is a great exercise to think over it until you say you've understood how a loop works. In addition, it is great that you want to look into such level of detail. Keep up the pace and interest and I am sure that after completing the different Python units in the program you will become an independent Python user!
Hope this helps.
Best,
Martin
Best,
Martin