You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_height to hold the original input value, so it never gets modified throughout the code.
  • We use current_height as 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:12:03