-1

I have this code that encounters the error: local variable 'vehicle' referenced before assignment. But when I look through my code below, I have assigned a list to the vehicle variable in the if, elif statement, before the 'vehicle' is being appended to the vehicles list. What could have gone wrong here?

def populate_vehicles(self, vehicle_file):

  empty_str = ''

  vehicle_str = vehicle_file.readline()
  vehicle_info = vehicle_str.rstrip().split(',')
  file_header_found = vehicle_info
  vehicle_str = vehicle_file.readline()

  while vehicle_str != empty_str:
      vehicle_info = vehicle_str.rstrip().split(',')
      if vehicle_str == '#CARS#' or vehicle_str == '#VANS#' or vehicle_str == '#TRUCKS#':
          file_header_found = vehicle_str

      else:
          if file_header_found == '#CARS#':
              vehicle = Car(*vehicle_info)


          elif file_header_found == '#VANS#':
              vehicle = Van(*vehicle_info)    

          elif file_header_found == '#TRUCKS#':
              vehicle = Truck(*vehicle_info)

      self.vehicles.add_vehicle(vehicle)

      vehicle_str = vehicle_file.readline()
Pawara Siriwardhane
  • 1,873
  • 10
  • 26
  • 38
  • Maybe none of the ```if...elif``` statements evaluate to ```True``` and then you are doing ```self.vehicles.add_vehicle(vehicle)``` where it is referenced. Try ```print(file_header_found)``` and check what is the output –  Jun 19 '21 at 02:36
  • 1
    There's no `else:` in the `if`/`elif` chain. If `header_found` does not match any of the three strings you compare it to, then `vehicle` will be undefined, just as Python told you. So, add an `else:`, and assign something to `vehicle` (or alternatively, give an error). – Tom Karzes Jun 19 '21 at 02:39

1 Answers1

0

If you enter the if, vehicle won't be set.

When you reference vehicle in the 2nd to last line in this case, it won't have been instantiated.

joeyagreco
  • 98
  • 2
  • 11