How to clear Python shell?

Python provides a python shell which is used to execute a single Python command and display the result. It is also called REPL. REPL stands for Read, Evaluate, Print and Loop. The command is read, then evaluated, afterwards the result is printed and looped back to read the next command.

Sometimes after executing so many commands and getting haphazard output or having executed some unnecessary commands, we may need to clear the python shell. If the shell is not cleared, we will need to scroll the screen too many times which is inefficient. Thus, it is required to clear the python shell.

The commands used to clear the terminal or Python shell are cls and clear.

In Windows

import os

In Linux

import os

Let us suppose, we need to show some output for few seconds and then we want to clear the shell. The following code serves the purpose.

  • Import os and sleep

  • Define a function where the commands to clear the shell are specified, cls for windows and clear for linux.

  • Print some output

  • Let the screen sleep for few seconds

  • Call the function to clear the screen


from os import system, name
from time import sleep
def clear():
   # for windows
   if name == 'nt':
      _ = system('cls')

   # for mac and linux
   _ = system('clear')

print(“Hi Learner!!”)