Python技术咨询:如何打印-10到10(含两端)所有整数的立方?
How to Print Cubes of All Integers From -10 to 10 (Inclusive) in Python
Hey there! I see you're working through while loop exercises and stuck on this problem—no worries, let's break this down clearly. Since you're focused on while loops, I'll start with that approach, then also share a simpler for loop alternative for context.
Using a While Loop
This is probably what your lesson is expecting, since you're in the while loop section. Here's how to do it step by step:
- Initialize your starting number: We need to start at -10, so set a variable like
num = -10. - Set up the while loop condition: We want to keep running the loop as long as
numis less than or equal to 10 (to include the 10 at the end). - Calculate the cube: Use Python's exponent operator
**to computenum ** 3(this is the same as multiplying the number by itself three times:num * num * num). - Print the result: Output the original number and its cube, or just the cube—whatever the problem asks for.
- Increment the counter: Don't forget to add 1 to
numeach time the loop runs, otherwise you'll get an infinite loop!
Here's the full code:
num = -10 while num <= 10: cube = num ** 3 print(f"Number: {num}, Cube: {cube}") # Or just print(cube) if you only need the cube value num += 1
Alternative: Using a For Loop
If you ever want a more concise way (though your lesson is focused on while loops), you can use a for loop with range(). Note that range() is exclusive of the end value, so we need to use range(-10, 11) to include 10:
for num in range(-10, 11): cube = num ** 3 print(f"Number: {num}, Cube: {cube}")
Quick Notes
- Negative numbers cubed stay negative: e.g.,
-2 ** 3 = -8 - Zero cubed is zero:
0 **3 =0 - Positive numbers cubed stay positive:
5**3=125 - Always make sure your while loop has a way to exit—adding
num +=1is crucial here to avoid the loop running forever!
内容的提问来源于stack exchange,提问作者lop lop




