The "for" loop


Hi, I was just introduced to the for-loop, and I am relatively confused about this subject. Any clairification would be appreciated in understanding this more. All I am looking for is a simple explanation in your own words please? Thank you so much! :slight_smile:

Replace this line with your code.



 stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
prices = {
   "banana": 4,
   "apple": 2,
   "orange": 1.5,
   "pear": 3

Each dictionary ( also called object )
has one or more key-value-pair's ( also called properties)
which are separated from each-other by a comma-,

The prices dictionary / object
has 4 properties
a banana property with property-key banana and its associated number Value 4
an apple property with property-key apple and its associated number Value 2
an orange property with property-key orange and its associated number Value 1.5
a pear property with property-key pear and its associated number Value 3

for - in - loop - e x p l a i n e d

With the for-in-loop you have a Method
which will iterate over all properties of a given object.
At each iteration it will assign the property-key as a string
to a variable name of your choice.
Thus for x in prices:
will lead to 4 iteration's
iteration-1 var x = "banana";
iteration-2 var x = "apple";
iteration-3 var x = "orange";
iteration-4 var x = "pear";
As they want you to display the the associated VALUE of the propery-key you would use
print prices[x]

If they wanted you to _Display the property-key and NOT it's associated VALUE
you would use
print x

As the stock dictionary / object uses the same property-key's
you can also use
print stock[x]


Thank you so much for the clarification! This helped me SO much! @leonhard.wettengmx.n


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.