for 循環中錯誤的Return 語句
在此程式設計問題中,使用者在建立允許使用者輸入三種動物的程式時遇到困難。該程式旨在用包含名稱、動物類型和年齡的 Pet 物件填入清單。然而,輸入第一個動物後,程式突然結束。
經分析,問題顯然出在 make_list 函式中 return 語句的位置。
for 迴圈重複實作程式碼區塊中的程式碼指定的迭代次數。當 return 語句放置在循環內時,它會在僅將第一個動物加入列表後過早退出函數。
要修正此問題,return 語句應放置在 之後 for 迴圈。這確保了函數繼續執行循環的迭代,並在返回之前將所有三種動物添加到清單中。
已修正的程式碼:
<code class="python">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()</code>
以上是為什麼錯誤的 return 語句會導致 for 迴圈中程式過早終止?的詳細內容。更多資訊請關注PHP中文網其他相關文章!