Paws, Claws, and Code: 6 Must-Know Python Examples
International Cat Day (8 August) is a purrfect occasion to combine our love for felines with the power of data science and Python programming. If you're a cat owner – or have any knowledge of Cats – I'm sure you'll be aware that they're known for their quirky behaviours like seemingly attacking anything that moves (or at least just staring at them, if they're as lazy as one of my cats…), devouring food, and sleeping for long hours.
In this article, we will explore these charming characteristics through 6 simple Python code examples for beginners, progressing from simple examples to more advanced concepts like object-oriented programming, GUI development, and unit testing that are frequently used in practice by experienced software developers.
Rest assured that Python will not eat your cat
The examples are designed to be simple and accessible for beginners, but they also form the basis of important concepts often used in real-world applications:
- Attacking Moving Objects (basic function with time pauses)
- Eating Habits (function with optional inputs)
- Sleep Patterns (Object-Oriented Programming and type hints)
- Analysing Cat Data with Pandas and Matplotlib
- Creating a Cat GUI with Tkinter
- Unit Testing Cat Behaviours
But what is this so-called Python? Will it eat my cat?
Python is a versatile and beginner-friendly programming language known for its readability and simplicity. It is widely used in various fields, including web development, Data Science, artificial intelligence, research, and automation.
And no, rest assured that Python will not eat your cat (although non-digital pythons might).
Intriguingly, the Python name was not directly inspired by the reptile, but rather by the British comedy series ‘Monty Python'. According to the Python FAQs:
When he began implementing Python, Guido van Rossum was also reading the published scripts from "Monty Python's Flying Circus", a BBC comedy series from the 1970s. Van Rossum thought he needed a name that was short, unique, and slightly mysterious, so he decided to call the language Python.
What do I need to get started?
To run the examples in this article, you can either use an online service, or you need to have Python installed on your computer.
One of the best online Python services is Google Colab, where you can create notebooks where code can be run in individual cells that can each display their own output. This makes it very easy to run small pieces of code, debug, and experiment. However, note that you will not be able to run the example showing a GUI with Tkinter, since Colab does not supported GUIs.
For use on your own PC, you can download and install Python from the official website. You can find some more information on how to install Python here.
I also recommend an Integrated Development Environment (IDE) such as VSCode or PyCharm. I will not stoke the debate on which one is best…suffice to say that both are good in their own ways!
Additionally, you will need the following Python packages that are already included with the Python standard library:
random
time
tkinter
unittest
And you will also need the following packages which are not already included:
pandas
matplotlib
You can install the additional packages using pip
:
pip install pandas matplotlib
Using a Virtual Environment [optional]
A virtual environment is a tool that helps to keep dependencies required by different projects in separate places, by creating a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages. This is especially useful when working on multiple projects that have different dependencies or when sharing projects with others, since it ensures that your projects are isolated and that dependencies do not clash between projects.
Platforms like Anaconda, which is commonly used for scientific applications and data science, provide easy management of virtual environments, but you can also create and manage them using the built-in venv
module in Python.
To create a virtual environment with venv
, use the following commands:
# Create a virtual environment named 'myenv'. You can give another name if you want
python -m venv myenv
# Activate the virtual environment
# On Windows
myenvScriptsactivate
# On Unix or MacOS
source myenv/bin/activate
# Install our required packages within the virtual environment
pip install pandas matplotlib
Let's now have a look at the interesting part – code examples inspired by our furry friends!
1. Attacking Moving Objects
Cats have an instinct to pounce on things that move. Let's simulate this behaviour using a basic Python script that mimics a cat's reaction to a moving object.
import random
import time
def simulate_cat_attack():
print("Cat is watching...")
time.sleep(1)
for _ in range(5):
move = random.choice(['left', 'right', 'up', 'down'])
print(f"Object moves {move}")
time.sleep(0.5)
if move in ['left', 'right']:
print("Cat attacks!")
break
else:
print("Cat waits...")
simulate_cat_attack()
In this example, we define a function called simulate_cat_attack()
, where we use the random
module to simulate the object's movement by randomly selecting one of four movements. The time
module is also used to add pauses, making the simulation just a-bit more realistic. The cat attacks when the object moves left or right, and just waits to pounce otherwise. In this example, the object makes five moves.
Also note the use of f-strings (e.g. in print(f"Object nmoves {move}")
for text formatting and display when variables (move
in this case) are used.
To run the code, the function simply needs to be called, as in the last line in the snippet above.
2. Eating Habits
Cats love to eat, and they have specific preferences. Let's create a simple function that simulates a cat eating different foods, demonstrating list manipulation, control flow in Python, and optional function inputs.
def cat_feeding(cat_favourites = ['fish', 'chicken']):
foods = ['fish', 'chicken', 'beef', 'milk']
for food in foods:
if food in cat_favourites:
print(f"Cat is happily eating {food}!")
else:
print(f"Cat sniffs and walks away from {food}.")
cat_feeding()
Here, we define two lists: one for available foods and another for the cat's favourite foods. The cat_favourites
list is an optional function input, allowing us to customise the cat's preferences when calling the function. The for
loop iterates through the foods, and the if-else
statement checks if the food is a favourite, simulating the cat's eating behaviour.
Also note that we have now defined an input to the function, cat_favourites
. This allows us to define a list of the cat's favourite foods when calling the function. However, note that there already is a list of favourite foods; this is a default list, that will be used even if we do not manually define the list ourselves when calling the function.
If you want to force a user to provide a list of favourite foods, simply do not define the list (so the function definition would read cat_feeding(cat_favourites):
.
But might it be a-bit tricky to know what type cat_favourites
is supposed to be? Should it be just a string of text, a list, or something else? In this example, it's fairly easy to infer that it should be a list, but it gets trickier when the number of variables increases and the operations are more complex. Step in type hints…
3. Sleep Patterns (Object-Oriented Programming)
Cats spend a significant portion of their lives sleeping. We'll now use object-oriented programming to model a cat's sleep patterns, demonstrating the power of classes and objects in Python, along with type hints.
A class in Python is a blueprint for creating objects. Objects are instances of classes that can have attributes (data) and methods (functions) to represent and manipulate that data. Classes are used to model real-world entities by bundling data and behaviour together, making code more organised, reusable, and easier to understand.
class Cat:
def __init__(self, name: str, age: int):
self.name: str = name
self.age: int = age
self.sleep_hours: int = 0
def sleep(self, hours: int) -> None:
self.sleep_hours += hours
print(f"{self.name} sleeps for {hours} hours. Total sleep: {self.sleep_hours} hours.")
def status(self) -> None:
if self.sleep_hours < 12:
print(f"{self.name} is still sleepy.")
else:
print(f"{self.name} is well-rested.")
# Creating a Cat object
my_cat = Cat("Whiskers", 2)
# Simulating sleep patterns
my_cat.sleep(5)
my_cat.status()
my_cat.sleep(8)
my_cat.status()
In this example:
- We define a
Cat
class with attributes for the cat's name, age, and total sleep hours. - The
__init__
method is a special method called a constructor, which is used to initialize the object's attributes when it is created. In this way, the behaviour and state are encapsulated within a class. - The
sleep
method adds hours to the cat's total sleep, and thestatus
method checks if the cat is well-rested (defined as having slept for 12 hors or more).
We also use what are known as type hints, to specify the types of the variables and the return types of the methods. These are not mandatory in Python, but are good practice to make it clear what type each variable should be for whoever is modifying the code. For instance hours:int
makes it clear that the variable hours
should be an int
(an integer, also known as a whole number).
4. Analysing Cat Data with Pandas and Matplotlib
Now, let's analyse some cat data using the Pandas library, a powerful tool for data manipulation and analysis. We'll create a DataFrame to store and analyse data about different cats' favourite foods and sleep hours, and visualize the sleep patterns using Matplotlib.
import pandas as pd
import matplotlib.pyplot as plt
# Creating a DataFrame with cat data
data = {
'Cat': ['Whiskers', 'Mittens', 'Shadow', 'Luna'],
'Favourite Food': ['fish', 'chicken', 'milk', 'beef'],
'Sleep Hours': [15, 10, 12, 18]
}
df = pd.DataFrame(data)
# Displaying the DataFrame
print(df)
# Analysing the data
average_sleep = df['Sleep Hours'].mean()
favorite_food_counts = df['Favourite Food'].value_counts()
print(f"nAverage Sleep Hours: {average_sleep}")
print("nFavourite Food Counts:")
print(favorite_food_counts)
# Plotting the sleep hours
plt.figure(figsize=(10, 6))
plt.bar(df['Cat'], df['Sleep Hours'], color='skyblue')
plt.xlabel('Cat')
plt.ylabel('Sleep Hours')
plt.title('Sleep Hours of Different Cats')
plt.show()
In this example, we create a DataFrame (essentially a table) to store information about different cats. We then calculate the average sleep hours and count the occurrences of each favourite food, demonstrating basic data analysis using Pandas. Many more functions are available, making Pandas one of the most widely-used tools by data scientists.

We also use Matplotlib to create a bar chart that visualises the sleep hours of different cats:

5. Creating a Cat GUI with Tkinter
Let's now create a simple Graphical User Interface (GUI) using Tkinter to display a cat's status. This example demonstrates how to build a basic, interactive GUI in Python.
import tkinter as tk
class CatApp:
def __init__(self, root: tk.Tk):
self.root = root
self.root.title("Cat Status")
self.label = tk.Label(root, text="Cat Name:")
self.label.pack()
self.cat_name = tk.Entry(root)
self.cat_name.pack()
self.status_button = tk.Button(root, text="Get Status", command=self.show_status)
self.status_button.pack()
self.status_label = tk.Label(root, text="")
self.status_label.pack()
def show_status(self) -> None:
name = self.cat_name.get()
if not name:
self.status_label.config(text="Please enter a cat name.")
return
# Simulating status (note: in a real application, this could be more complex)
sleep_hours = random.randint(5, 20)
status = "well-rested" if sleep_hours >= 12 else "still sleepy"
self.status_label.config(text=f"{name} is {status} (Slept {sleep_hours} hours).")
root = tk.Tk()
app = CatApp(root)
root.mainloop()
In this example, we create a Tkinter application with an entry field for the cat's name and a button to display the cat's status based on simulated sleep hours (where a random number between 5 and 20 is chosen, which is then used to determine if the cat is still sleepy or not based on the number of hours it has slept).

If we wanted to, we also could have used the Cat
class we defined earlier, but I decided to keep it simple here. Feel free to try it out yourself!
6. Unit Testing Cat Behaviours
Unit testing is essential to ensure our code works as expected. This is a more advanced concept, but a very important one nevertheless.
Unit tests are small, isolated tests that check individual parts of our code (known as the "units"), such as functions, methods or classes, to make sure they behave as intended and produce the correct results.
Let's create unit tests for our Cat
class using the unittest
module in Python:
import unittest
from io import StringIO
import sys
class TestCat(unittest.TestCase):
def setUp(self):
self.cat = Cat("Whiskers", 2)
def test_initial_sleep_hours(self):
self.assertEqual(self.cat.sleep_hours, 0, "Initial sleep hours should be 0")
def test_sleep(self):
sleep_hours = 5
self.cat.sleep(sleep_hours)
self.assertEqual(self.cat.sleep_hours, sleep_hours, f"Sleep hours should be {sleep_hours} after sleeping for {sleep_hours} hours")
def test_status_sleepy(self):
sleep_hours = 5
self.cat.sleep(sleep_hours)
captured_output = StringIO() # Create StringIO object
sys.stdout = captured_output # Redirect stdout.
self.cat.status() # Call function.
sys.stdout = sys.__stdout__ # Reset redirect.
self.assertIn("still sleepy", captured_output.getvalue().strip(), f"Cat should be still sleepy after {sleep_hours} hours of sleep")
def test_status_well_rested(self):
sleep_hours = 12
self.cat.sleep(sleep_hours)
captured_output = StringIO() # Create StringIO object
sys.stdout = captured_output # Redirect stdout.
self.cat.status() # Call function.
sys.stdout = sys.__stdout__ # Reset redirect.
self.assertIn("well-rested", captured_output.getvalue().strip(), f"Cat should be well-rested after {sleep_hours} hours of sleep")
if __name__ == '__main__':
unittest.main(argv=[''], exit=False)
In this example, we use the unittest
module to create unit tests for our Cat
class. We test the following methods to ensure they behave as expected:
- The initial number of sleep hours (to ensure that they start from zero)
- The
sleep
method, to ensure that the counting is being done correctly - The
status
method, to ensure that the method outputs the correction both when the cat is still sleepy (slept for less than 12 hours), and when it is well-rested (slept for 12 hours or more).

Finally, note how the use of variables and f-strings for text formatting and display make it a doddle to generalise your code. In this case, we defined sleep_hours
to be used (1) as a function input and (2) as part of the error message output, instead of hard-coding a specific value (requiring us to change the value in 2–3 locations depending on the unit test).
Conclusion
International Cat Day is a fantastic opportunity to learn a-bit of Python by exploring cat behaviours.
From simple scripts that simulate a cat's reaction to moving objects and eating habits, to advanced concepts like object-oriented programming, data analysis with Pandas, GUI development with Tkinter, and unit testing, we can use these examples to celebrate our feline friends while honing our coding skills.
While fairly simply, these examples span quite an important set of functionalities and good practices in Python.
Happy International Cat Day, and happy coding!
✒️ Do you have any thoughts about this article? Please feel free to post a note, comment, or message me directly on LinkedIn!