Typewriter Animation Using Python

Typewriter like animation using Python for beginners.

typewriter.gif

In today’s digital landscape, captivating user experiences have become paramount for websites and applications. One design element that has gained popularity is the typewriter animation, which adds a touch of nostalgia and visual appeal to textual content. While you may have come across numerous websites utilizing this animation that elegantly reveal text as if it were being typed out right before your eyes. These websites basically use JavaScript and CSS. Have you ever wondered if it’s possible to achieve the same effect using Python? Well, you’re in for a treat🎉. You can achieve the the same animated effect using Python!

Now, you might be thinking, “Wait a minute, can Python really do that?” Absolutely! While typewriter animations are often associated with JavaScript and CSS, Python has its own tricks up its sleeve to bring text to life. In this tutorial, we’ll unravel the secrets behind creating engaging typewriter animations, and we’ll do it all within the friendly confines of your Python console. So, let’s begin.

By the end of this tutorial you’ll be able to do this.

console-typewriter-effect.gif

Understanding The Concept:

Before we jump into the code, let’s understand the concept behind the typewriter animation. The typewriter effect involves printing characters one by one to simulate the appearance of a typewriter typing. To create this effect, we’ll use a loop to iterate over each character in a sentence and print them with a delay between each character. We’ll also delete the printed characters one by one to simulate backspacing.

We’ll need two modules for this animation: time and sys. The time module will allow us to introduce delays, while the sys module will enable us to control the console output. Import these modules by adding the following lines of code at the beginning of your Python file:

import sys
import time

Creating the Typewriter Effect Function:

Next, let’s define a function called typewriter_effect that will handle the typewriter animation. This function takes three parameters: sentence (the sentence to display), type_delay (the delay between typing each character), and delete_delay (the delay between deleting each character).

def typewriter_effect(sentence, type_delay, delete_delay):
    # Loop through each character and print the sentence
    for char in sentence:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(type_delay)

    time.sleep(1)

In the typewriter_effect function, we use a for loop to iterate over each character in the sentence. For each character, we perform the following actions:

  • sys.stdout.write(char) : This writes the character to the console, creating the effect of typing out the sentence gradually.
  • sys.stdout.flush(): This forces the immediate display of the character on the console.
  • time.sleep(type_delay): This introduces a delay, specified by the type_delay parameter, between typing each character, controlling the speed of the animation.

Once the loop finishes typing out the entire sentence, we introduce a pause of 1 second using time.sleep(1). This gives a brief pause after printing the sentence before starting the deletion process.

 # Loop to delete the sentence
     for _ in sentence:
        sys.stdout.write('\b \b')
        sys.stdout.flush()
        time.sleep(delete_delay)

Next, we initiate another loop in the same function to delete the sentence we just typed. For each character in the sentence, we perform the following actions:

  • sys.stdout.write('\b \b'): This writes a backspace character, followed by a space, and then another backspace. This effectively erases the character from the console.
  • sys.stdout.flush(): This forces the immediate deletion of the character from the console.
  • time.sleep(delete_delay): This introduces a delay, specified by the delete_delay parameter, between deleting each character, controlling the speed of the deletion animation.

Configuring the Animation:

Now that we have the typewriter effect function, let’s configure the animation. Create a list called sentences and add the sentences you want to display in the typewriter effect. For example:

sentences = [
    "Hello, Reader! How are You?",
    "This is a console based typewriter effect.",
    "Using Python it simulates the appearance of a typewriter."
]

Additionally, define two variables: type_delay and delete_delay. These variables control the speed of typing and deletion, respectively. For example:

type_delay = 0.05  # Typing speed (in seconds)
delete_delay = 0.01  # Deleting speed (in seconds)

Feel free to adjust these values to achieve the desired typing and deletion speed.

Implementing the Animation Loop:

To make the animation continuous, we’ll create a loop that iterates over each sentence in the sentences list and calls the typewriter_effect function. After printing each sentence, we'll use print('\r', end='') to print a carriage return and overwrite the sentence, giving the appearance of a continuous animation. Add the following code snippet:

while True:
    # Iterate over each sentence in the list
    for sentence in sentences:
        typewriter_effect(sentence, type_delay, delete_delay)  # Call the typewriter_effect function

        # Print a carriage return to overwrite the sentence and
        # start the next iteration with a clean console output
        print('\r', end='')

Save the Python file with an appropriate name, such as “typewriter_animation.py”. Open your command prompt or terminal, navigate to the directory where the file is saved, and execute the script by typing python typewriter_animation.py and pressing Enter.

iron-man-voila.gif

You will see the typewriter animation in action, as the sentences are printed and then deleted one by one. The animation will continue indefinitely until you manually terminate the script by pressing Ctrl+C.

I wonder what Alexandru-Ioan Plesoiu will think about this console based typewriter animation. If you are reading this do share your thoughts.

Full Source Code:

import time
import sys

# Function to create the typewriter effect
def typewriter_effect(sentence, type_delay, delete_delay):
    # Loop through each character in the sentence
    for char in sentence:

        # Write, display and delay
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(type_delay)

    # Pause after printing the entire sentence
    time.sleep(1)

    # Loop to delete the sentence
    for _ in sentence:
        # Write backspace, space, delete and delay
        sys.stdout.write('\b \b')
        sys.stdout.flush()
        time.sleep(delete_delay)

# List of sentences to display in typewriter effect
sentences = [
    "Hello, Reader! How are You?",
    "This is a console based typewriter effect.",
    "Using Python it simulates the appearance of a typewriter."
]

# Typing and Deleting speed in seconds
type_delay = 0.05
delete_delay = 0.01

while True:
    # Iterate over each sentence in the list
    for sentence in sentences:

        # Call the typewriter_effect function
        typewriter_effect(sentence, type_delay, delete_delay)

        # Print a carriage return to overwrite the sentence and
        # start the next iteration with a clean console output
        print('\r', end='')

Feel free to customize the typewriter animation to suit your preferences. You can add more sentences to the sentences list, adjust the typing and deletion speeds by modifying the type_delay and delete_delay variables, or even explore additional features like user input for dynamic sentences.

Conclusion:

🎉 Congratulations on creating a typewriter animation in Python! Congratulations! Thank you for taking the time to read the entire article! I truly appreciate your dedication and interest😊. If you found this tutorial helpful, please share it with others. 💡

Keep coding and spreading the joy of programming! ✨

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics