×

How to clear screen in Python?

How to clear screen in python

There are times when we execute our program and it results in an unexpected output. The obtained result can contain some kind of garbage values (this happens generally when we don't initialize the value of our variable to zero) or the output might give a result in the data type we don't expect from it.

So, whenever you encounter a situation like this you feel that you should once again come to a clear working space and start everything from the beginning.

In this article, we will discuss how we can clear our screen in python when we are stuck in problems as described at the beginning.

We have two ways of implementing the same-

  1. Using a shortcut key to clear the screen.
  2. Using a python script to clear screen

Let us have a look at the first method-

The first way to clear the screen in Python is using the shortcut key ‘Ctrl + I’.

The second way is that we can define a cls function and call it when required-

 def cls():
 print(“\n”*100) 

The above cls() function can be called anywhere in our program as per our need.

Python also provides various features from different modules that can make our work much easier. Let us see how do they work-

To clear the commands in Windows and Linux we will use-

For Windows

 import os
 os.system(“CLS”) 

For Linux

 import os
 os.system(“clear”) 

Now let us have a look at how the same can be implemented using Python script

 # import os module  
 from the os import system, name  
 # For displaying output for a specific time import sleep 
 from time import sleep  
 # definition of clear function 
 def clear():  
     # for windows  
     if name == 'nt':  
         _ = system('cls')  
     # for mac and linux(the os.name is 'posix')  
     else:  
         _ = system('clear')  
 # printing the message in the output 
 print('Tutorials and Example\n'*5)  
 # specifying sleep time after the output is displayed   
 sleep(10)  
 # calling the clear function  
 clear()   

INPUT-

How to clear screen in Python

OUTPUT-

How to clear screen in Python

Let us understand each part of the above program here-

  1. os module– The os module in Python helps in accessing and manipulating the files and directories present in our system.
  2. system package- The sys module in Python provides different kinds of functions and variables that can manipulate the Python runtime environment
  3. time module- The time module provides functions that can be used with time-related programs.
  4. sleep – The sleep function suspends the execution of a particular thread for a certain time.
  5. using underscore- The underscore variable is used because the last output is stored in it.

Now we will look at some Python programs so that you have a good hands-on language.

 p=int(input("Enter the principal: "))
 r=int(input("Enter the rate: "))
 t=int(input("Enter the time: "))
 si=p*r*t/100
 print("The value for simple interest is {}".format(si)) 
  • Python program to calculate the volume of a cylinder.
 pi=3.14
 r=int(input("Enter the value of radius: "))
 h=int(input("Enter the value of height: "))
 vol=pi*pow(r,2)*h
 print("Volume of cylinder is {}".format(vol)) 
  • Python program to perform addition, subtraction, division, and multiplication.
 num1=float(input("Enter number1: "))
 num2=float(input("Enter number2: "))
 add=num1+num2
 subt=num1-num2
 mult=num1*num2
 div=num1/num2
 print("Addition of two float numbers is {}".format(add))
 print("Subtraction of two float numbers is {}".format(subt))
 print("Multiplication of two float numbers is {}".format(mult))
 print("Division of two float numbers is {}".format(div)) 
  • Python program to calculate the area of a circle.
 pi=3.14
 r=int(input("Enter the value of radius: "))
 area=pi*r*r
 print("Area of circle is {}".format(area)) 
  • Python program to find the greatest of three numbers.
 a=int(input("Enter the value of 1st number: "))
 b=int(input("Enter the value of 2nd number: "))
 c=int(input("Enter the value of 3rd number: "))
 if(a>b and a>c):
     print("{} is greatest".format(a))
 elif(b>a and b>c):
     print("{} is greatest".format(b))
 else:
     print("{} is greatest".format(c)) 
  • Python program to understand type conversion.
 x=input("Enter the first number: ")
 y=input("Enter the second number: ")
 print(x+y)                #result is addition of two strings
 x=int(input("Enter the first number: "))
 y=int(input("Enter the second number: "))
 print(x+y)                 #result is addition of two numbers 
  • Python program to calculate distance between two points.
 x1=int(input("Enter the x-coordinate of first point: "))
 y1=int(input("Enter the y-coordinate of first point: "))
 x2=int(input("Enter the x-coordinate of second point: "))
 y2=int(input("Enter the x-coordinate of second point: "))
 dist=((x2-x1)**2+(y2-y1)**2)**0.5
 print("The calculated distance is {}".format(dist)) 

Related Topics

Python min() function

Python min() function returns you the minimum value element in an iterable. We can also use this function to determine the smallest value among various arguments passed to this function. We...

4 minutes read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Python program to check whether a given number is prime or not

Python program to check whether a given number is prime or not A positive integer greater than 1 is called a prime number if it is divisible by one and number...

1 minute read.

Python Typing Module

An Introduction to the Typing Module The typing module is introduced in Python version 3.5 and used to provide hinting method types in order to support static type checkers and linters...

10 minutes read.

Python String join() method

Python String join() method The String.join() method in Python concatenates each element of an iterable (such as list, string and tuple) to the given string and returns the concatenated string. Syntax string.join(seq) Parameter Seq: This...

1 minute read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

Python program to count and display vowels in a string

Python program to count and display vowels in a string This python program counts the vowels in a string and displays them on the screen. We can do this in several...

2 minutes read.

Cross Validation in Sklearn

Data scientists can benefit from cross-validation in machine learning in two key ways: it can assist in minimising the amount of data needed and ensure the artificial intelligence model is...

14 minutes read.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

Filter List in Python

Python: Python is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programming...

3 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

Python Validator

Validator  The validator is a library available in the python programming language. The library in python consists of all the related modules which can be imported to perform the required operation....

3 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

Python hasattr() function

Python hasattr() function The hasattr() function in Python returns a Boolean value ‘True’ if the given object has the specified attribute, else it returns False. Syntax hasattr(object, name) Parameter object: it is a required parameter which represents an object. attribute:...

1 minute read.

Python for Loop Increment

Introduction In general, loops are employed for sequential traversal. It belongs to the definite iteration category. Definite iterations imply that the number of iterations is explicitly set in advance.  In this article,...

4 minutes read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.