π Python Crash Course – Chapter 4: Working With Lists – Exercise 4-8 Solution
Welcome to another solution from Python Crash Course by Eric Matthes.
π Exercise 4-8
Task:
A number raised to the third power is called a cube .
For example,
the cube of 2 is written as 2**3 in Python .
Make a list of the first 10 cubes (that
is, the cube of each integer from 1 through 10), and use a for loop to print out
the value of each cube
✅ Solution Code:
num = list(no**3 for no in range(1,11))
for data in num:
print(data)
π§ Code Explanation:
This Python code demonstrates how to generate a list of cubes of numbers and iterate through it using a for
loop. Here's how it works:
-
Generate a list of cubes:
A list comprehension is used to calculate the cube of each number in the range from 1 to 10. The expression
no**3
raises each numberno
to the power of 3, and therange(1, 11)
function generates numbers from 1 to 10 (inclusive). The resulting list of cubes is stored in the variablenum
. -
Iterate through the list:
A
for
loop is used to iterate through each cube in thenum
list. The variabledata
takes on each value in the list, one at a time.
This code demonstrates how to use list comprehensions to perform mathematical operations on a sequence of numbers and how to iterate through the resulting list.
π Output:
1
8
27
64
125
216
343
512
729
1000
π Related Exercises from Chapter 4:
- ➤ Exercise 4-1 | Pizzas
- ➤ Exercise 4-2 | Animals
- ➤ Exercise 4-3 | Counting to Twenty
- ➤ Exercise 4-4 | One Million
- ➤ Exercise 4-5 | Summing a Million
- ➤ Exercise 4-6 | Odd Numbers
- ➤ Exercise 4-7 | Threes
- ➤ Exercise 4-8 | Cubes
- ➤ Exercise 3-9 | Cube Comprehension
- ➤ Exercise 4-10 | Slices
- ➤ Exercise 4-11 | My Pizzas, Your Pizzas
- ➤ Exercise 4-12 | More Loops
- ➤ Exercise 4-13 | Buffet
- ➤ Exercise 4-14 | PEP 8
- ➤ Exercise 4-15 | Code Review
π 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
πTrending Topics
π Connect With Us:
“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”— Only Python
π Follow Us And Stay Updated For Daily Updates
Comments
Post a Comment