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.
- Open the
kdigit.pyfile in your preferred code editor. - Locate the
f(n, k)function definition, where the function name isfand it has two parametersnandk. The function should return the k-th digit from the right side of the integern. - 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.
- Locate the code at the bottom of the
kdigit.pyfile:
if __name__ == "__main__":
print(f(123456789, 3))
- Run the
kdigit.pyfile using the following command:
python3 kdigit.py
- 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.
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



