0
0
PythonHow-ToBeginner · 3 min read

How to Clear Screen in Python: Simple Methods Explained

To clear the screen in Python, use os.system('cls') on Windows or os.system('clear') on macOS/Linux. Import the os module first to run these commands that clear the terminal window.
📐

Syntax

Use the os.system() function to run a command in the terminal. The command 'cls' clears the screen on Windows, while 'clear' works on macOS and Linux.

  • import os: Imports the module to run system commands.
  • os.system('cls'): Clears screen on Windows.
  • os.system('clear'): Clears screen on macOS/Linux.
python
import os

# For Windows
os.system('cls')

# For macOS/Linux
os.system('clear')
💻

Example

This example shows how to clear the screen depending on the operating system detected by Python. It prints a message, waits for user input, then clears the screen.

python
import os
import platform
import time

print('Hello! The screen will clear in 3 seconds...')
time.sleep(3)

if platform.system() == 'Windows':
    os.system('cls')
else:
    os.system('clear')

print('Screen cleared!')
Output
Hello! The screen will clear in 3 seconds... Screen cleared!
⚠️

Common Pitfalls

Many beginners forget to import the os module before calling os.system(). Also, using cls on macOS/Linux or clear on Windows will not work. Another mistake is expecting this to clear the screen in all environments; it works only in terminal/console windows.

python
import os

# Wrong: Using 'cls' on Linux or macOS
os.system('cls')  # This will not clear screen on macOS/Linux

# Correct: Check OS before clearing
import platform
if platform.system() == 'Windows':
    os.system('cls')
else:
    os.system('clear')
📊

Quick Reference

Summary tips for clearing screen in Python:

  • Always import os before using os.system().
  • Use 'cls' command on Windows.
  • Use 'clear' command on macOS and Linux.
  • Check the operating system with platform.system() for cross-platform code.
  • This method works only in terminal or command prompt, not in some IDE consoles.

Key Takeaways

Use os.system('cls') for Windows and os.system('clear') for macOS/Linux to clear the screen.
Always import the os module before calling os.system().
Check the operating system with platform.system() for cross-platform compatibility.
This method clears the terminal screen but may not work in some IDE consoles.
Avoid using the wrong command for your operating system to ensure the screen clears properly.