简体   繁体   English

在while True循环内更​​改输出

[英]Changing the output inside a while True loop

I am very new in Python and I decided to make a game. 我是Python的新手,所以我决定做一个游戏。 I want a value to be output like this: 我希望这样输出一个值:

Heat: x #x would always be changing 热度:x #x总是在变化

For that I have the following block of code: 为此,我有以下代码块:

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

but all it does is spam "Heat: xHeat: xHeat: x" When it should be only one Heat bar What should I do? 但是它只是垃圾邮件“ Heat:xHeat:xHeat:x”当它仅是一个Heat bar时,我该怎么办?

You can use carriage return to send the cursor to the start of the line. 您可以使用回车键将光标发送到行的开头。

import sys

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

But this approach doesn't sound like you will be able to extend it into any sort of game. 但是这种方法听起来并不像您可以将其扩展到任何类型的游戏中。

You should look up the python curses library for complete control over the console output. 您应该查找python curses库,以完全控制控制台输出。

Also if the number of digits in your output changes then you might want to right-align the output so that you don't get any left-overs. 同样,如果输出中的位数发生变化,那么您可能希望将输出右对齐,这样就不会剩下任何余数。 This code demonstrates what happens if you go from a 2 digit number to a 1 digit number: 此代码演示了如果您从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()

In that code 'Heat' in the loop and it will be printed all the time: 在循环中的代码“ Heat”中,它将始终被打印:

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

In that code 'Heat' out of the loop and it will be printed once: 在该代码“ Heat”中,它会循环输出一次:

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

if you want more newlines use '\\n' char (strictly depends on OS). 如果您想要更多换行符,请使用'\\ n'char(严格取决于操作系统)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM