Python Forum
Fundamental understanding-problem regards to while-loops
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Fundamental understanding-problem regards to while-loops
#7
The example has a couple extra steps that I'll explain at the end.

At the beginning of the loop, we declare a variable:

my_list = ["ketchup", "chicken", "potatoes", "veggies"]

for i in my_list:
Within the body of the loop, we can then reference the variable we declared:

my_list = ["ketchup", "chicken", "potatoes", "veggies"]

for i in my_list:
    print(i)
The variable does not have to be "i"; we can just as easily call it "x", "n", "bobsYourUncle", or "each". In any case, the variable is assigned to the value of the next item in the sequence. For the first iteration over "my_list", "i" is assigned to "ketchup"; when that iteration is done, "i" is reassigned to "chicken" and so forth.

In other languages, you can only perform a for loop with numbers (e.g. in Java: for i := 0; i < 10; i ++ {...} would loop 10 times) and then use the variable "i" as an index (hence "i" often being used) to an array object. So, to iterate over a sequence in Java (or another language), you have to do something like this (though written in Python):

for i in range(len(eww_Java)):
    value = eww_Java[i]
    print(value)
Python simplifies this by iterating over the sequence itself (the list, tuple, etc.) and assigning the variable to the next value in the sequence.
Reply


Messages In This Thread
RE: Fundamental understanding-problem regards to while-loops - by stullis - Oct-11-2018, 12:37 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Exporting Stock Fundamental Data to a CSV file with yahoo_fin DustinKlent 2 4,774 Aug-01-2022, 06:08 PM
Last Post: paulyan
  problem with for loops? Darbandiman123 1 2,051 Sep-26-2018, 06:35 PM
Last Post: nilamo
  Need help with understanding for/while loops! WombatHat42 2 2,369 Sep-26-2018, 11:46 AM
Last Post: ThiefOfTime

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020