Reputation:
def Data():
while True:
try:
PetTotal = int(input("Please enter the number of pets: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
else:
PetBreeds = []
Ages = []
while True:
try:
Gender = int(input("Enter gender option: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if Gender > 2 or Gender < 1:
print("Wrong!")
continue
else:
Count = 0
while Count != PetTotal:
Breed = str(input("Breed: "))
Age = float(input("Age: "))
if Gender == 1:
PetBreeds.append(Breed)
Ages.append(Age)
Count = Count + 1
else:
PetBreeds.append(Breed)
Ages.append(Age)
Count = Count + 1
PetInfo = dict(zip({PetBreeds, Ages))
return PetBreeds, Gender;
I have added some input validation to my code as I am trying to understand it. However, my code no longer works properly. When PetTotal
is above 2, it only loops once so that only one pet type can be entered (rather than two). I'm sure the answer is obvious but I can't figure it out...any help is greatly welcomed!
Upvotes: 0
Views: 51
Reputation: 9468
the final line in your method return
s - which will cause the outermost loop (the one controlling how many pets to process) to exit.
I think you want your code to look similar to
pets = []
total = input("...")
while len(pets) < total:
# or `for i in range(0, total):` as in Keshav's answer
pet = { }
... # process input for gender, age, etc
pets.append(pet)
Upvotes: 1
Reputation: 379
The else part will execute only once irrespective of the value entered in try case, so try to apply a for loop so that the else part is executed n number of times
for i in range(0,PetTotal):
#else part here
Upvotes: 1