Python中如何在while循环结束后将变量重置为初始值?
Fixing Your Hash Tree Stump Alignment
Got it, let's fix that tree stump issue! The problem here is that you're modifying the original Height variable directly in your while loop—by the time the loop finishes, it's been decremented all the way to 0, which is why your stump isn't centered properly under the tree.
The Solution: Preserve the Initial Height
The easiest way to fix this is to store the original height value in a separate variable before you start modifying it in the loop. This keeps the initial value intact so you can use it to calculate the correct spacing for the stump.
Here's the corrected code:
# Store the original height in a separate variable initial_height = int(input("Enter height of tree: ")) current_height = initial_height hashes = 1 # Use current_height for the loop so initial_height stays unchanged while current_height > 0: print(' ' * (current_height - 1) + "#" * hashes) current_height -= 1 hashes += 2 # Now use the original initial_height to center the stump print(" " * (initial_height - 1) + "#")
What Changed?
- We added
initial_heightto hold the original input value, so it never gets modified throughout the code. - We use
current_heightas the loop counter, which gets decremented as before—this doesn't affect the original height value. - For the stump, we calculate spacing using
initial_height - 1, which centers it perfectly under the tree (matching the spacing of the topmost hash line).
This approach keeps your code clean and easy to read, while ensuring the stump is aligned correctly every time.
内容的提问来源于stack exchange,提问作者Stergios
相关产品推荐
相关产品推荐

