Lesson 2
Working with Numbers
Working with Numbers

Welcome back to our Redis course! Now that you know how to connect to a Redis server, it's time to move forward and explore how to work with numbers in Redis. This unit builds on our previous lesson, so make sure you're comfortable with establishing a connection to a Redis server.

What You'll Learn

In this lesson, you will learn how to:

  1. Set numeric values in Redis.
  2. Retrieve and decode numeric values.

Here's the code snippet that we'll be working with:

Python
1import redis 2 3# Connect to Redis 4client = redis.Redis(host='localhost', port=6379, db=0) 5 6# Setting and getting string values 7client.set('count', 5) 8client.set('completion_rate', 95.5) 9 10count = client.get('count') 11completion_rate = client.get('completion_rate') 12 13print(f"Course count: {count}, Completion rate: {completion_rate}") 14 15count = count.decode('utf-8') 16completion_rate = completion_rate.decode('utf-8') 17 18print(f"Course count: {count}") 19print(f"Completion rate: {completion_rate}")

Let's break down the code:

  • Just like in the previous lesson, we first import the redis module and establish a connection to the Redis server.
  • We use the set method to store the numeric values: count with a value of 5 and completion_rate with a value of 95.5. We retrieve these values using the get method and then decode them from bytes to strings using decode('utf-8'). Note that the return type of the get method is a bytes string, and we need to decode it to get the actual value.
Why It Matters

Working with numbers in Redis is crucial because many real-world applications involve numeric data. From tracking user statistics to monitoring system performance, managing numbers in Redis allows you to perform a variety of useful operations efficiently. By mastering these basic operations with numbers, you'll be well-prepared to tackle more complex tasks and optimize your applications.

Ready to dive in? Let's move on to the practice section and get hands-on experience working with numbers in Redis!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.