Lesson 3
Operations with Numbers
Moving On to Operations with Numbers

Welcome back! Now that you've learned how to work with numbers in Redis, it's time to build on that knowledge and explore some basic operations with these numbers. This lesson will show you how to perform operations like incrementing, decrementing, and modifying numeric values directly in Redis.

What You'll Learn

In this lesson, you will learn how to:

  1. Increment and decrement numeric values.
  2. Modify numeric values using operations such as increments by a floating point.

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) 9client.set('duration', 0) # Ensure 'duration' is set initially 10 11client.decr('count') 12client.incrbyfloat('completion_rate', 1.5) 13client.incr('duration') 14 15count = client.get('count') 16completion_rate = client.get('completion_rate') 17duration = client.get('duration') 18 19print(f"Course count: {count.decode('utf-8')}") 20print(f"Completion rate: {completion_rate.decode('utf-8')}") 21print(f"Duration: {duration.decode('utf-8')}")

Let's break it down:

  • After setting initial values for count, completion_rate, and duration, we perform various operations:
    • decr('count') decreases the value of count by 1. You can also provide a second argument to decr to decrement by a specific value: decr('count', 2) will decrement count by 2. Note, that decr can only be used on integer values.
    • incrbyfloat('completion_rate', 1.5) increments completion_rate by 1.5. Note, that this method can be used on integer and floating-point values.
    • incr('duration') increases the duration by 1. You can also provide second argument to incr to increment by a specific value: incr('duration', 5) will increment duration by 5. Note, that incr can only be used on integer values.
  • Finally, we retrieve and decode the values to display the updated state.
Why It Matters

Understanding how to perform operations with numbers in Redis is essential for real-world applications. Imagine you're building a learning management system: you would track user progress, completion rates, and time spent on courses. Redis makes it fast and easy to update these numbers in real-time.

By the end of this lesson, you'll be comfortable with basic numeric operations in Redis, preparing you for more advanced tasks. Ready to get started? Let's dive into the practice section and enhance your Redis skills!

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