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

 

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

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


📝 Exercise 4-6

Task:
Store a message in a variable, and then print that message.Use the third argument of the range() function to make a list of the odd numbers from 1 to 20 .
Use a for loop to print each number

✅ Solution Code:


num=list(range(1,21,2))
for no in num:
    print(no)

🧠 Code Explanation:

This Python code demonstrates how to generate a list of odd numbers and iterate through it using a for loop. Here's how it works:

  1. Create a list of odd numbers:

    The range(1, 21, 2) function generates a sequence of numbers starting from 1, ending before 21, and incrementing by 2. This ensures that only odd numbers between 1 and 20 are included. The list() function converts this range into a list, which is stored in the variable num.

  2. Iterate through the list:

    A for loop is used to iterate through each number in the num list. The variable no takes on each value in the list, one at a time.

This code demonstrates how to use the third argument of the range() function to generate a sequence with a specific step size and how to iterate through the resulting list.

🔍 Output:


1
3
5
7
9
11
13
15
17
19

📚 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