I would like to convert both the for
loops in my code into while
loops. Here is the code.
class CountryCatalogue:
def __init__(self, countryFile): # constructor method that takes name of file
self.countryCat = [] # The instance variable country cat needed
file = open(countryFile, "r") # open and read the file
for strip in file:
strip = strip.strip()
data = strip.split('|') # Remove '|' in each line
clean_data = Country(data[0], data[2], data[3], data[1]) # Create an object to country
self.countryCat.append(clean_data) # Append the item to the list
file.close() # Close the file
def setPopulationOfCountry(self, country, population):
for pop in range(len(self.countryCat)): # iterate through countryCat
if self.countryCat[pop].getName() == country.getName():
self.countryCat[pop].setPopulation(population) # updating data if needed
I tried to change the second for loop this way:
def setPopulationOfCountry(self, country, population):
pop = 0
while pop < (len(self.countryCat)):
if self.countryCat[pop].getName() == country.getName():
self.countryCat[pop].setPopulation(population) # updating data if needed
pop = pop 1
But it didn't work and I wasn't sure about the first for
Loop.
CodePudding user response:
your while loop:
def setPopulationOfCountry(self, country, population):
pop = 0
while pop < (len(self.countryCat)):
if self.countryCat[pop].getName() == country.getName():
self.countryCat[pop].setPopulation(population) # updating data if needed
pop = pop 1
you put the pop = pop 1 in the if statement, get it out:
def setPopulationOfCountry(self, country, population):
pop = 0
while pop < (len(self.countryCat)):
if self.countryCat[pop].getName() == country.getName():
self.countryCat[pop].setPopulation(population) # updating data if needed
pop = pop 1
CodePudding user response:
The easiest way that I found to change your file for loop to a while loop is to go through each line:
file = open(countryFile, "r") # open and read the file
strip = file.readline()
while strip != "":
strip = file.readline()