akhlyd
akhlyd

Reputation: 3

Replacing a while loop with a for statement with python list

I have to create a list of cars, a function to display the cars but replace the fourth car with a phrase, and call the function, for an assignment. One of the parts of the grading scheme is to use a for statement to iterate, not a while loop. It also says that it can be done in under 10 lines of code.

I have created a while loop that does prints the proper list, but I cannot manage to change it to a for statement successfully.

def my_Assign3_challenge(cars):
  i=0
  while i<len(cars):
    print(cars[i])
    i=i+1
    if i==3:
      print("I would never buy that!")
      i=i+1
cars=["toyota","mitsubishi","dodge","ford","mini"]
my_Assign3_challenge(cars)

This for statement just prints the list, without the change:

def my_Assign3_challenge(cars):
  for x in cars:
    if x!= 3:
      print(x)
    else:
      print("I would never buy that!")
cars=["toyota","mitsubishi","dodge","ford","mini"]
my_Assign3_challenge(cars)

I also managed a couple times to have just the first list item repeat indefinitely, I can't find the code that did that now, though.

I would greatly appreciate if anyone could take a look at this and tell me where I went wrong. I'm sure it's just a simple mistake, as I am very new to coding, but I would love your help!

Upvotes: 0

Views: 123

Answers (3)

itwasthekix
itwasthekix

Reputation: 615

I can do it in 3 lines:

challenge = lambda x : [v if i !=3 else "I would never buy that!" for i, v in enumerate(x)]
cars=["toyota","mitsubishi","dodge","ford","mini"]
challenge(cars)

output:

Out[54]: ['toyota', 'mitsubishi', 'dodge', 'I would never buy that!', 'mini']

Upvotes: 0

Prune
Prune

Reputation: 77847

Your while loop iterates through the list indices ...

while i<len(cars):
  print(cars[i])

... but you changed your referencing with the for loop: you now reference the elements themselves, the brand names:

for x in cars:

but you still treat x as if it were an integer index. Since x is now a sequence of brand names, it will never equal 3. You need to make up your mind which way you're going to refer to the list elements, and make your second set of code use that way consistently.

Upvotes: 1

Axisnix
Axisnix

Reputation: 2907

The for loop in the function:

def my_Assign3_challenge(cars):
  for x in cars:
    if x!= 3:
      print(x)
    else:
      print("I would never buy that!")
cars=["toyota","mitsubishi","dodge","ford","mini"]
my_Assign3_challenge(cars)

Outputs

toyota
mitsubishi
dodge
ford
mini

You need to get the index using .index()

The code would be:

def my_Assign3_challenge(cars):
  for x in cars:
    if cars.index(x) != 3:
      print(x)
    else:
      print("I would never buy that!")
cars=["toyota","mitsubishi","dodge","ford","mini"]
my_Assign3_challenge(cars)

Upvotes: 0

Related Questions