-5

I've got some code here and I'm trying to review it to practice. The aim of the code is to read in a colour of a car and count up how many times that colour has been mentioned.

The code is below and it does work:

car = {}
color = input("Car: ")

while color:
  if color not in car:
    car[color] = 1
  else:
    car[color] = car[color] + 1
  color = input("Car: ")
for x in car:
  print("Cars that are", x, ":", car[x])

But I'm not sure what the following means or does:

for x in car:
      print("Cars that are", x, ":", car[x])

I'm not sure about what phrases like for i in range: or for x in cars: mean.

I am new to programming. It would be appreciated is I could get an explanation about what they actually do in Python and what they mean as x wasn't assigned as a variable in the code.

Thanks.

James
  • 55
  • 7

1 Answers1

0

That's what for loop in Python is. for x in car basically means for key in dictionary since car is declared as a Dictionary above (car ={} ) so for key in that Dictionary you ll print the key and value that the key hold. for example if you have

  dic = {"audi": "blue", "bmw": "red"}
  for x in dic:
    print(x) #x is audi and bmw
    print(dic[x]) # dic[x] is blue and red because they are the values hold by those keys 

when you make a for loop as for x in car, python will assign every key to x so the values of x are the value of the key in the car Dictionary. you can think of it that Python is smart and know what you want to do.

for i in range(value) is another way to make a for loop in PYthon. this will give i a value from 0 to that value for every Iteration. It's like:

       for(int i=0;i<value;i++) 

if you are coming from other Languages like C Family

basilisk
  • 1,156
  • 1
  • 14
  • 34