In this blog post we will revisit two of the key python functions: print() and input() in order to improve the user experience of our Python programs.
As you know, the print() function in Python is used to output a message on screen, whereas the input() instruction displays a message/question on screen and retrieves a user input that the user will type using their keyboard.
Our aim is to improve the display of text on the screen by adding a typing effect/delay.
To do so we will need to import two libraries: time and sys. We will then create two new functions called typingPrint() and typingInput() as follows:
import time,sys def typingPrint(text): for character in text: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) def typingInput(text): for character in text: sys.stdout.write(character) sys.stdout.flush() time.sleep(0.05) value = input() return value
We will then be able to use these two functions in our program instead of the usual print() and input() functions.
Finally, to improve the user experience further, we have also created a clearScreen() function which relies on importing the os library. This function can be used at anytime to clear the screen from previous outputs and inputs. It’s ideal when creating menu based systems, splash screes, quiz based games, two player games and so on… Here is the code for our clearScreen() subroutine.
import os def clearScreen(): os.system("clear")
Let’s see how to use our functions in small text-based program: