![](/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.