![](/img/trans.png)
[英]How can I check a previous index when iterating through a for loop python
[英]How do I remove the previous question printed when iterating through a loop in python?
我试图删除每次我询问时打印的前一行,我尝试了许多不同的方法,例如'end="\r"和导入 os 以尝试清除屏幕,但都无法正常工作。 那么,我应该如何处理呢?
我正在使用 Python 3.8.6
这是我的代码。 下半部分的大部分内容在这里不相关,只有 cubeCalc() 中的所有内容
def cubeCalc(a):
listOfValues = ['height', 'width', 'depth']
listOfNo = []
if a == 1:
for i in range(len(listOfValues)):
listOfNo.append(int(input("Input the "+str(listOfValues[i])+"(cm): ")))
print("The volume is",listOfNo[0]*listOfNo[1]*listOfNo[2],"cm³")
print("The total surface area is",(listOfNo[0]*listOfNo[2])*6,"cm²")
elif a == 2:
pass
def pyramidCalc():
pass
#main
selection = int(input("Input your selection. 1 for cubes. 2 for pyramids: "))
if selection == 1:
whichDimension = int(input("Calculations for 3d (1) or 2d (2) shape?: "))
cubeCalc(whichDimension)
elif selection == 2:
pyramidCalc()
这是我运行时发生的情况:
这是我想要的粗略想象:
非常感谢您对我的代码的任何其他批评。 我不是很喜欢数学,所以如果我可以通过更好的计算来减少线条,请随时添加。
您可以在每次输入后清除屏幕:
import os
for i in range(len(listOfValues)):
listOfNo.append(int(input("Input the "+str(listOfValues[i])+"(cm): ")))
os.system('cls')
print("The volume is",listOfNo[0]*listOfNo[1]*listOfNo[2],"cm³")
print("The total surface area is",(listOfNo[0]*listOfNo[2])*6,"cm²")
如果您使用的是 Linux,请使用clear
而不是cls
。
我不认为print
是正确的工具。
您可以考虑将sys.stdout.write
与sys.stdout.flush
一起考虑。
例子:
import sys
import time
sys.stdout.write("first text\r")
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("second text")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.