Misplaced Return Statement in for Loops
In this programming issue, the user encounters difficulty in creating a program that allows user input for three animals. The program is designed to populate a list with Pet objects containing name, animal type, and age. However, after inputting the first animal, the program abruptly concludes.
Upon analysis, it becomes evident that the problem lies within the placement of the return statement within the make_list function.
The for loop implements code in the code block repeatedly for a specified number of iterations. When the return statement is placed inside the loop, it prematurely exits the function after adding only the first animal to the list.
To rectify this issue, the return statement should be placed after the for loop. This ensures that the function continues to execute the loop's iterations and adds all three animals to the list before returning it.
Corrected Code:
import pet_class
def make_list():
pet_list = []
print('Enter data for three pets.')
for count in range(1, 4):
print('Pet number ' str(count) ':')
name = raw_input('Enter the pet name:')
animal = raw_input('Enter the pet animal type:')
age = raw_input('Enter the pet age:')
pet = pet_class.PetName(name, animal, age)
pet_list.append(pet)
return pet_list
pets = make_list()
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3