Extract Rightmost Digit in Python

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to write a function that returns the k-th digit from the right side of an integer. This is a common programming problem that tests your ability to manipulate and extract data from integers.

👀 Preview

$ python3 kdigit.py
## f(123456789, 3)
7

ðŸŽŊ Tasks

In this project, you will learn:

  • How to define a function with two parameters
  • How to convert an integer to a string and access individual characters
  • How to return the desired digit from the right side of the integer

🏆 Achievements

After completing this project, you will be able to:

  • Implement a function that extracts a specific digit from an integer
  • Understand how to work with integers and strings in Python
  • Apply your problem-solving skills to a real-world programming problem

Implement the f(n, k) Function

In this step, you will implement the f(n, k) function in the kdigit.py file.

  1. Open the kdigit.py file in your preferred code editor.
  2. Locate the f(n, k) function definition, where the function name is f and it has two parameters n and k. The function should return the k-th digit from the right side of the integer n.
  3. Inside the function, add the following code to get the k-th digit from the right side of the integer n:
## Convert n to a string
n_str = str(n)

## Get the k-th digit from the right
k_digit = int(n_str[-k])

return k_digit

The complete f(n, k) function should look like this:

def f(n, k):
    """
    Return the k-th digit of the integer n from the right.

    Args:
        n (int): The integer.
        k (int): The position of the digit from the right.

    Returns:
        int: The k-th digit from the right.

    """
    ## Convert n to a string
    n_str = str(n)

    ## Get the k-th digit from the right
    k_digit = int(n_str[-k])

    return k_digit

Test the f(n, k) Function

In this step, you will test the f(n, k) function to ensure it works as expected.

  1. Locate the code at the bottom of the kdigit.py file:
if __name__ == "__main__":
    print(f(123456789, 3))
  1. Run the kdigit.py file using the following command:
python3 kdigit.py
  1. The output should be:
7

This means that the f(n, k) function is working correctly and returning the 3rd digit from the right side of the integer 123456789.

Congratulations! You have successfully completed the project.

âœĻ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like