+ 3
Can anyone help me? I don't understand loops
https://code.sololearn.com/cDR5svhfof00/?ref=app https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2435/?ref=app I try a lot but i am still confused. I don't understand this lesson. (I will appreciate if anyone can explain this to me as simple as he/she can.)
15 Antworten
+ 8
words = ["hello", "world", "spam", "eggs"]
counter = 0
max_index = len(words) - 1
The first element in words starts at index 0:
words [0] = "hello";
...
words [3] = "eggs"
The length of words is 4, because it contains 4 elements.
Now it should be clear why max_index = len (words) - 1
= 4 - 1 = 3
while counter <= max_index:
This is your condition. The loop runs until counter <= max_index. If the counter gets larger the loop stops.
word = words[counter]
print(word + "!")
counter = counter + 1
counter = 0 -> word = words [0] = "hello"
print hello!
increment counter
counter = 1 -> word = words [1] = "world"
print world!
increment counter
and so on...
counter gets 4 -> larger than max_index -> stop loop
As you can see the loop prints all elements of your list.
+ 3
Denise Roßberg really thank you!
+ 3
Elen V Your welcome :)
+ 3
Loops :
In your code:
words = ["hello", "world", "spam", "eggs"]
counter = 0
max_index = len(words) - 1
while counter <= max_index:
word = words[counter]
print(word + "!")
counter = counter + 1
You are saying to the program while counter(is 0) is less than or equal to max index(length of the array words note : the tru e length of the array is 4 but in this example is 3 simply because the array start counting from 0 )
Print word +!
Where word is the array words with the number counter inside it.
Counter = counter + 1
Means in every value of counter returns it value and add 1 to it ex
If counter = 2
The loop will start counting from 2 to the end
Of the loop
The end of loop ex
While number<=number2
Number:beginning of the loop
Number2:the end of the loop
You can reverse the loop
While number>=number2
Bla Bla
Number = number -1
Hope this explanation will help you 😊
Peace
+ 3
Moumen Al_Bakkar 😂😂 sorry
Thank you too
+ 3
Loops are used to repeat code segments.
+ 3
Hope you understand now.
+ 2
$p@rK thanks 👍
+ 2
You are welcome 😊
+ 2
No need to thank me.
+ 2
Sonic 👍
+ 1
if you want to write your name one time u can write (in C#) { Console.WriteLine("Elen"); }
if you want to write it twise you can copy and paste last line...
But how about 100 times ?
or 1000 ?
do u want to copy paste copy past......
OF COURSE no..
so we have to use loop sometimes to repeat things without wasting time.
+ 1
Elen V why didn't u thank me 😐
+ 1
Sonic, yes now i understand and i want to thank you all of you 🤗
+ 1
I can try it to explain in pseudocode.
You got a kind of data.
Lets say a list.
ex_list = [1,2,3,4]
And you want to do something with every elenent of the data, then you say:
for [each] element in .
The tool is
for i in ex_list:
do something.
Hope it helps.