【问题标题】:Changing the output inside a while True loop在 while True 循环内更改输出
【发布时间】:2015-09-30 03:14:14
【问题描述】:

我是 Python 的新手,我决定制作一个游戏。 我希望像这样输出一个值:

热量:x #x 总是在变化

为此,我有以下代码块:

while True:
   print("Heat: {}".format(Heat))

但它所做的只是垃圾邮件“Heat:xHeat:xHeat:x” 当它应该只有一个加热条时 我该怎么办?

【问题讨论】:

  • 那你为什么要把它放在一个无限循环中?
  • reset() print("Welcome to RM 1") print("请选择一个新难度") new=input("请输入一个介于 1 和 3 之间的值:") setDifficulty(new) # start clear() h="Heat: {}".format(Heat) #Loop while True: time.sleep(getDifficulty()/0.5) print(h)
  • @n0fares maroun 提供了答案
  • 我希望 Heat 一直在变化,这就是为什么我把它放在一个无限循环中。但我的问题是如何将“Heat:”放在那里而不将其移动到任何地方,然后添加其相应的值,该值会有所不同

标签: python string while-loop


【解决方案1】:

您可以使用回车将光标发送到行首。

import sys

while True:
    sys.stdout.write("\rHeat: {}".format(Heat))
    sys.stdout.flush()

但这种方法听起来你无法将其扩展到任何类型的游戏中。

您应该查找 python curses 库以完全控制控制台输出。

此外,如果输出中的位数发生变化,那么您可能需要右对齐输出,以免出现任何剩余。此代码演示了如果您从 2 位数字变为 1 位数字会发生什么:

import sys
import time

for heat in reversed(range(5, 12)):
    time.sleep(0.5)

    sys.stdout.write("\rHeat: {:>5}".format(heat))
    sys.stdout.flush()

【讨论】:

    【解决方案2】:

    在循环中的那个代码'Heat'中,它会一直被打印出来:

    Heat = 0
    while True:
        Heat +=1
        print ('Heat: {heat}'.format(heat=Heat))
    

    在该代码中'Heat'退出循环,它将被打印一次:

    Heat = 0
    print ('Heat:')
    while True:
        Heat +=1
        print ('{heat}'.format(heat=Heat))
    

    如果您想要更多换行符,请使用 '\n' 字符(严格取决于操作系统)。

    【讨论】:

    • 我也会试试那个。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2021-06-09
    • 2013-09-28
    • 2016-02-13
    • 2021-11-29
    • 1970-01-01
    相关资源
    最近更新 更多