Exercise 4-2 Solution Python Crash Course Chapter 4: Working With Lists

 

📘 Python Crash Course – Chapter 4: Working With Lists – Exercise 4-2 Solution

Welcome to another solution from Python Crash Course by Eric Matthes.


📝 Exercise 4-2

Task:
Think of at least three different animals that have a common char acteristic . Store the names of these animals in a list, and then use a for loop to print out the name of each animal .
• Modify your program to print a statement about each animal, such as A dog would make a great pet.
• Add a line at the end of your program stating what these animals have in common . You could print a sentence such as Any of these animals would make a great pet!

✅ Solution Code:


animals = ["dog",'cat','parrot']

for animal_name in animals:
    print(animal_name)

print("-----------------------------------------------------------")

for animal_name in animals:
    print(f'A {animal_name} would make a great pet')

print("-----------------------------------------------------------")

for animal_name in animals:
    print(f'A {animal_name} would make a great pet')
print("All of them are friendly in nature")

print("-----------------------------------------------------------")

🧠 Code Explanation:

This Python code demonstrates how to use a list and a for loop to iterate through items and print personalized messages about animals. Here's how it works:

  1. Create a list of animals:

    The variable animals is assigned a list containing three animals: ["dog", "cat", "parrot"].

  2. Print each animal name:

    A for loop is used to iterate through the animals list, and the print() function is used to display each animal name.

  3. Print personalized statements:

    The for loop is modified to include an f-string that prints a personalized statement for each animal, such as "A dog would make a great pet".

  4. Add a concluding statement:

    After the loop, a final statement is printed outside the loop, expressing a general characteristic of all the animals in the list. For example, "All of them are friendly in nature".

🔍 Output:


dog
cat
parrot
-----------------------------------------------------------
A dog would make a great pet
A cat would make a great pet
A parrot would make a great pet
-----------------------------------------------------------
A dog would make a great pet
A cat would make a great pet
A parrot would make a great pet
All of them are friendly in nature
-----------------------------------------------------------

📚 Related Exercises from Chapter 4:


🔗 Connect With Us:

“The only way to learn a new programming language is by writing programs in it.”
– Dennis Ritchie

📌 Tags: #Python #PythonCrashCourse #CodingForBeginners #LearnPython #PythonProjects #PythonTips #introducingLists

Previous Post Next Post

Contact Form