简体   繁体   中英

How do I remove the previous question printed when iterating through a loop in python?

I'm trying to remove the previous line that prints every time I ask, I've tried many different methods such as 'end="\r" and importing os to try clear the screen, but both fail to work. So, how should I approach this?

I'm using Python 3.8.6

Here is my code. Most of the bottom half isn't relevant here, only everything in 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()

Here is what happens when I run:

Here is a rough imagining of what I'd like:

Any other critique you may have of my code is much appreciated. I am not very math inclined so if I could cut down on lines in anyway with better calculations, feel free to add.

You can clear your screen after each input:

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²")

Use clear instead of cls if you're on Linux.

I don't think print is the right tool for that.

You could consider sys.stdout.write along with sys.stdout.flush instead.

Example:

import sys
import time
sys.stdout.write("first text\r")
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("second text")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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