gpt4 book ai didi

python - 在同一行连续输入

转载 作者:行者123 更新时间:2023-12-04 15:08:47 24 4
gpt4 key购买 nike

我做了一个循环,让用户输入数字,直到他输入“13”,然后循环就会中断。

while True:
number = int(input())
if number == 13:
print("goodbye")
break

当我运行这个程序时,它看起来像这样:

1
2
3
13
goodbye

但我希望输入在同一行中继续,每当我这样输入时:

1 2 3 13
goodbye

我该怎么做?

最佳答案

一个相对简单的方法是:

import os
prompt = ''
while True:
number = input(prompt)
os.system('cls')
# prompt += number + ' ' #If you want the control input to be printed, keep this, remove the other
if int(number) == 13:
print(prompt)
print('goodbye')
break
prompt += number + ' ' # add this line before the if starts, if you want to keep 13
os.system('cls')

输出:

1 2 3 4
goodbye

注意,这不会像您希望的那样在注释中打印 13。但是,如果你想保留它,你可以将它移到 if 条件开始之前的行。

这适用于 Windows 命令提示符,不能保证不同的 IDLEs/iPython 等。

注意:这将清除控制台中的所有行,并重写它们。这适用于您的特定问题,但如果之前也打印过其他内容,则可能不理想。如果你想避免这种情况,你必须将 sys.stdout 重定向到 file。或某种 string buffer在你点击这部分代码之前,然后恢复 stdout 并将缓冲区的内容作为文本存储在上面使用的 prompt 变量中。

关于python - 在同一行连续输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65609782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com