How to clear the screen in command line mode on Python?

For each option chosen by the user, I would like to clear the screen. I did this:

import os
     clear = lambda: os.system('cls') #on Windows System
     entry = input("Clear the window ? Y/N ")
     if entry == "Y":
            clear()

But it doesn’t work

1 Like

Your code looks ok, except the indentations, but I assume that this is problem with the formatting in the post, not with the code itself.

This code should not work in the Codecademy environment because Codecademy uses Linux based system in the containers that execute the code submitted by the users. So to make it work in the Codecademy environment you would have to change the command from cls to clear.

But the better solution to this problem is to write code that will work in both Windows and Linux, right? We can achieve this by checking the os.name property:

import os

clear = lambda: os.system('cls' if os.name=='nt' else 'clear')

entry = input("Clear the window ? Y/N ")
if entry == "Y":
  clear()

If this still does not work and you are sure that you run this script in the Windows environment you have to open the Python shell and execute this code:

import os
os.system('cls')

this should result in some sort of error, post the error message here and we will try to solve this problem :slight_smile:

2 Likes

It doesn’t work. When I execute the code above, when I put "Y’, It creates a second window (on the first window which executes the code) whose content is empty and which disappear automatically without emptying the first window

Hm, this does not sound like a behaviour of a normal shell, this should definitely work in PowerShell, CMD prompt and in the bash of the WSL environment. So my guess is that you use Python IDLE.

And because Python IDLE is not a normal shell it does not act like a normal shell :slight_smile: So you are limited to what the IDLE developers implemented. And from my quick research it looks like this feature is not available currently, but its implementation was heavily discussed over the past ten years :slight_smile: Here is a issue report -> https://bugs.python.org/issue6143.

You still have some options! You can change the execution environment to PowerShell or CMD. Or you can install extension for the IDLE that is linked in the issue I mentioned earlier (file named ClearWindow.py). It was written almost ten years ago so I am not sure if it will work or if that is a good idea, but it is still an option, I think.