florence-y
florence-y

Reputation: 871

For loop not running specified amount of times- TypeError: 'int' object is not iterable

I have simulated a Monty Hall Game, and I would like to repeat the following code by what the user inputs. I am a very novice programmer, so bear with me. I just don't know if I am placing the for loop correctly.

Below is my code that I want to tell it to run the rest of the code v amount of times via a for loop, which the user input before. v in this case is 2. I get a TypeError, however, that only makes it run once, this happens anytime v>1:

for t in range(1,v+1)

print('Game',t)
  doors = [1,2,3]
  prizes = ['C','G1','G2']
  while valid == True:
    random.shuffle(prizes)
    initial_doors = list(zip(doors,prizes))
    doors = initial_doors[:]
    print('Doors are Set Up as:',doors)
    user = int(input('Select door 1, 2, or 3:\n'))
    user = user - 1
    (a,b)=doors[0]
    (c,d)=doors[1]
    (e,f)=doors[2]
    if user == 0:
      selected_door = a
      print('You selected door', selected_door)
    elif user == 1:
      selected_door = c
      print('You selected door', selected_door)
    elif user == 2:
      selected_door = e
      print('You selected door', selected_door)
      user_door = doors.pop(user)
    valid = False

  monty_door = [i for i, j in doors if 'G' in j] # This is where the error occurs
  monty_door = str(monty_door)
  monty_door = monty_door[1]
  monty_door = int(monty_door)
  print('Monty selected door', monty_door)

  car_door = [i for i, j in initial_doors if 'C' in j]
  car_door = str(car_door)
  car_door = car_door[1]
  car_door = int(car_door)

  if car_door != selected_door:
    win = 'switch'
    print('Player should', win, 'to win.')
  elif car_door == selected_door:
    win = 'stay'
    print('Player should', win, 'to win')

Output is below, where it should have another iteration underneath. You see v=2 after user is asked how many tests they want to run, and the error is printed at the end:

How many tests should we run? Type Exit to exit: 2
Game 1
Doors are Set Up as: [(1, 'G1'), (2, 'C'), (3, 'G2')]
Select door 1, 2, or 3:
 2
You selected door 2
Monty selected door 1
Player should stay to win
Game 2 # Error message below, line 58 is commented above
Traceback (most recent call last):
  File "python", line 58, in <module>
  File "python", line 58, in <listcomp>
TypeError: 'int' object is not iterable

Upvotes: 0

Views: 40

Answers (1)

Nogoseke
Nogoseke

Reputation: 1009

Your problems seems to be that you are setting valid = False at the end of the first game, then on the second game you are not entering your while loop and doors is just [1, 2, 3] which explains the error you are getting.

Upvotes: 1

Related Questions