Python code to extract and display the last two digits of a number.
Python code implementation without user defined functions & classes
Code:
# Python code to extract last two digits of a number
a = 23457
a_string = str(a)
a_length = len(a_string)
c = int(a_string[a_length - 2: a_length])
print("The last two digit for the number: ", a, " is: ", c)
Output:
The last two digit for the number: 23457 is: 57
Python Code Editor Online - Click to Expand
Python code implementation using function
In this code, we will pass the number to a function that will extract and return the last two digits of a number.
Code:
# Python code to extract last two digits of a number using Function
def last_2_digits(number):
a_string = str(a)
a_length = len(a_string)
c = a_string[a_length - 2: a_length]
return int(c)
a = 10938
print("The last two digit for the number: ", a, " is: ", last_2_digits(a))
Output:
The last two digit for the number: 10938 is: 38
Python Code Editor Online - Click to Expand
Python code implementation using Classes
In this code, we will implement a class that contains a function to return the last two digits of a number. We will create an object and will call the function using object.function(), the will return the reverse integer number.
Code:
# Python code to extract last two digits of a number using Classes
class Last_2_Digit_class(object):
def last_2_digits(self, number):
a_string = str(number)
a_length = len(a_string)
c = a_string[a_length - 2: a_length]
return int(c)
a = 6560234
#Create an Object
last_2 = Last_2_Digit_class()
#Call the function using Object
print("Last 2 digit for number: ", a, " is: ", last_2.last_2_digits(a))
Output:
Last 2 digit for number: 6560234 is: 34
Python Code Editor Online - Click to Expand
Enjoy Python Code By Pythonbaba 🙂