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

 

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

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


📝 Exercise 4-13

Task:
A buffet-style restaurant offers only five basic foods .
Think of five simple foods, and store them in a tuple .
• Use a for loop to print each food the restaurant offers .
• Try to modify one of the items, and make sure that Python rejects the change .
• The restaurant changes its menu, replacing two of the items with different foods .
Add a block of code that rewrites the tuple, and then use a for loop to print each of the items on the revised menu

✅ Solution Code:


foods = ("meat","egg","fish","rice","chapati")
for food in foods:
    print(food)

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

#the below code show error as tuples cant be modified
#  foods[0] = "water"      # show error ---'tuple' object does not support item assignment

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


foods = ("meat","pizza","burger","rice","chapati")   # replace 2 items 
for food in foods:
    print(food)

🧠 Code Explanation:

This Python code demonstrates how to work with tuples, including their immutability and how to redefine them. Here's how it works:

  1. Create a tuple of foods:

    The variable foods is assigned a tuple containing five food items: ("meat", "egg", "fish", "rice", "chapati"). Tuples are immutable, meaning their elements cannot be changed after creation.

  2. Iterate through the tuple:

    A for loop is used to iterate through each item in the foods tuple and display its contents.

  3. Attempt to modify the tuple:

    A commented-out line of code attempts to modify the first element of the tuple (foods[0] = "water"). This would raise an error because tuples do not support item assignment.

  4. Redefine the tuple:

    The foods variable is reassigned to a new tuple with two items replaced: ("meat", "pizza", "burger", "rice", "chapati"). This demonstrates that while tuples themselves are immutable, the variable referencing the tuple can be reassigned to a new tuple.

  5. Iterate through the new tuple:

    A for loop is used again to iterate through the updated foods tuple and display its contents.

This code demonstrates the immutability of tuples in Python and how to redefine a tuple by assigning a new one to the same variable.

🔍 Output:


meat
egg
fish
rice
chapati
--------------------------------------------------------
----------------------------------------------------------        
meat
pizza
burger
rice
chapati

📚 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

Previous Post Next Post

Contact Form