Last digit в питоне

Last digit в питоне

For example, the remainder of dividing 12345 by 10 is 5 .

Copied!
number = 12345 print(12345 - 1234 * 10) # 👉️ 5

Here are some more examples.

Copied!
number = 12345 print(82342 % 10) # 👉️ 2 print(248 % 10) # 👉️ 8 print(150 % 10) # 👉️ 0

# Get the last N digits of a Number in Python

You can also use the modulo operator to get the last N digits of a number.

The modulo operator in the example will return the last 2 digits of the number by calculating the remainder of dividing the number by 100.

Copied!
number = 123456 last_two = number % 100 print(last_two) # 👉️ 56 last_three = number % 1000 print(last_three) # 👉️ 456

The same approach can be used to get the last 3 digits of a number.

Copied!
number = 246810 # ✅ Get the last 3 digits of a number last_three = number % 1000 print(last_three) # 👉️ 810

If the number might be negative, use the abs() function to make sure you get the correct result.

Copied!
number = -123456 last_two = abs(number) % 100 print(last_two) # 👉️ 56

The abs function returns the absolute value of a number. In other words, if the number is positive, the number is returned, and if the number is negative, the negation of the number is returned.

Copied!
print(abs(-43)) # 👉️ 43 print(abs(43)) # 👉️ 43

The modulo (%) operator returns the remainder from the division of the first value by the second.

Copied!
print(10 % 2) # 👉️ 0 print(10 % 4) # 👉️ 2

If the value on the right-hand side is zero, the operator raises a ZeroDivisionError exception.

We used integers in the example, but the left and right-hand side values may also be floating-point numbers.

For example, the remainder of dividing 123456 by 100 is 56 .

Copied!
number = 123456 print(123456 - 1234 * 100) # 👉️ 56

Here are some more examples.

Copied!
# ✅ Get the last 2 digits of a number print(23484 % 100) # 👉️ 84 print(9590 % 100) # 👉️ 90 print(900 % 100) # 👉️ 0

And here is an example of getting the last three digits of a number.

The remainder of dividing 123456 by 1000 is 456 .

Copied!
print(123456 - 123*1000) # 👉️ 456

Here are some more examples.

Copied!
# ✅ Get the last 3 digits of a number print(123456 % 1000) # 👉️ 456 print(8523400 % 1000) # 👉️ 400 print(1523000 % 1000) # 👉️ 0

Alternatively, you can use string slicing.

# Get the last N digits of a Number using string slicing

This is a three-step process:

  1. Use the str() class to convert the number to a string.
  2. Use string slicing to get the last N characters of the string.
  3. Use the int() class to convert the result to an integer.
Copied!
number = 123456 # ✅ Get the last 2 digits of a number last_two = int(str(number)[-2:]) print(last_two) # 👉️ 56

The same approach can be used to get the last three digits of a number.

Copied!
number = 246810 # ✅ Get the last 3 digits of a number last_three = int(str(number)[-3:]) print(last_three) # 👉️ 810

We used the str() class to convert the integer to a string so we can use string slicing.

The syntax for string slicing is my_str[start:stop:step] .

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first character in a string has an index of 0 , and the last character has an index of -1 or len(my_str) — 1 .

Negative indices can be used to count backward.

The slice my_str[-2:] starts at the second to last character and goes to the end of the string.

Once we have the last 2 digits, we can use the int() class to convert the string to an integer.

Copied!
number = 123456 last_two = int(str(number)[-2:]) print(last_two) # 👉️ 56

Which approach you pick is a matter of personal preference. I’d go with using the modulo % operator because it’s quite intuitive and easy to read.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Как вывести последнюю цифру числа в python

Обложка для статьи

Для работы с числами в Python может потребоваться получить доступ к их отдельным цифрам. Одним из часто возникающих заданий является получение последней цифры числа. Это может понадобиться, например, для решения математических задач или для форматирования вывода данных. В этой статье мы рассмотрим несколько способов получения последней цифры числа в Python.

Получение последней цифры числа путём преобразование числа в строку

Получение последней цифры числа в Python можно выполнить, преобразовав число в строку и обратившись к последнему символу этой строки. Для преобразования числа в строку в Python можно использовать функцию str() . Далее, для получения длины строки, мы можем использовать функцию len() , и после обратиться к последнему элементу строки по его индексу (длина строки — 1, так как индексация идёт с 0):

number = 123456 string_number = str(number) last_digit = string_number[len(string_number)-1] print(last_digit)

В этом примере мы сначала преобразуем число в строку с помощью функции str(), а затем получаем длину строки с помощью функции len(). Мы используем длину строки для получения индекса последнего символа (который является последней цифрой числа) и сохраняем его в переменной last_digit. Наконец, мы выводим последнюю цифру числа с помощью функции print().

Приведённый ваше код можно упростить, если знать, что извлечь последний символ строки можно, используя отрицательный индекс -1 :

number = 123456 last_digit = str(number)[-1] print(last_digit)

Использование арифметических операций для получения последней цифры

Для получения последней цифры числа можно использовать арифметические операции. Для этого можно использовать операцию остатка от деления % , которая возвращает остаток от деления двух чисел.

Например, чтобы получить последнюю цифру числа 123, можно выполнить следующую операцию:

Результатом будет число 3, которое является последней цифрой числа 123.

Такой подход является более простым и эффективным, чем преобразование числа в строку и использование индексации.

Однако, стоит учитывать, что если число отрицательное, то данный подход не сработает. В таком случае, можно использовать функцию abs() для получения модуля числа, а затем применить операцию % .

number = -12345 last_digit = abs(number) % 10 print(last_digit) # выводит 5

Источник

Python Get Last Digit of Int

Python Get Last Digit of Int | In this article, we will see how to get the last digit of an int in python. We will make use of various methods to find the last digit of an int. Let’s see an ordinary example first and then we can move forward and see different methods to do the same.

Python Get Last Digit of Int using the Modulus Operator

The modulus % operator can be used to find the remainder of a number and then return its last digit as the output. We will make use of this concept and see how to get the last digit of an int in python.

Example:
Find the last digit in the int 123

Code for Python get last digit of int 123:-

num = int(123) last_digit = num % 10 print("The last digit in %d = %d" % (num, last_digit))

We took the input int 123 and made use of the modulo. When it is divided by10, it returns the last digit of the number, in this case, it returned 3.

Let us see another example by taking input from the end-user,

num = int(input("Enter a number: ")) last_digit = num % 10 print("The last digit in %d = %d" % (num, last_digit))

Enter a number: 452679
The last digit in 452679 = 9

Enter a number: 89568674165
The last digit in 89568674165 = 5

Python Get Last Digit of Int using Strings

1) The number’s string form can be viewed.
2) Have the string’s last character.
3) Convert character to an int.

num = 12345 # string representation num_str = repr(num) # make use of the last string of the digit string last_digit_str = num_str[-1] # convert the last digit string to an int last_digit = int(last_digit_str) print(f"Last digit = ")

In short, we retrieve the string, get the last character, and change it back to an integer. For user input, we can write the same code as:-

Python get last digit of int using Strings by taking input from the user

num = int(input("Enter a number: ")) num_str = repr(num) last_digit_str = num_str[-1] last_digit = int(last_digit_str) print(f"Last digit = ")

Enter a number: 1023
Last digit = 3

Thus, we learned how to get the last digit of an int in python using two different methods. Both the methods are easy to understand and apply, we hope that you found them useful. Also see:- Find Shortest Word in List Python

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

How to Get the Last Digit of an Integer in Python?

In Python, you can get the last digit of an integer in the following ways:

Using Modulo Operator

You can use the modulo operator ( % ) to get the last digit of an integer in the following way:

  1. Convert number to absolute form;
  2. Get the last digit by calculating number % 10 ;
  3. Add negative sign to the last digit if integer was negative.

The modulo operator in Python won’t return the correct last digit for negative numbers because it performs floored division, and not truncated division. To get the correct result, you must convert the number to absolute form first (using abs() ), and then add the sign back.

def last_digit(num): last_digit_unsigned = abs(num) % 10 return -last_digit_unsigned if (num < 0) else last_digit_unsigned print(last_digit(0)) # 0 print(last_digit(1234)) # 4 print(last_digit(-1234)) # -4

As an alternative, you may use the following mathematical formula for calculating remainder correctly:

def last_digit(num): return num - (10 * int(num / 10)) print(last_digit(0)) # 0 print(last_digit(1234)) # 4 print(last_digit(-1234)) # -4

This performs truncated division (i.e. using the int() method, the fraction part is removed/truncated from the result of the division).

This works in the following way:

# num = 1234 # last_digit = 1234 - (10 * int(1234 / 10)) # last_digit = 1234 - (10 * int(123.4)) # last_digit = 1234 - (10 * 123) # last_digit = 1234 - 1230 # last_digit = 4

Converting to String and Retrieving Last Character

You could do the following:

  1. Convert the integer to a string;
  2. Get the last character of the string;
  3. Convert the string back to integer;
  4. Add negative sign to the last digit if integer was negative.
def last_digit(num): num_str = str(num) last_digit_unsigned = int(num_str[-1]) return -last_digit_unsigned if (num < 0) else last_digit_unsigned print(last_digit(0)) # 0 print(last_digit(1234)) # 4 print(last_digit(-1234)) # -4

When the integer is converted to a string, the sign is considered a character in the string and has no special meaning, which is why it is not added to the last digit. For this reason, the sign is added back once the last character is converted back to an integer.

Hope you found this post useful. It was published 05 Dec, 2022 . Please show your love and support by sharing this post.

Источник

Читайте также:  Auto link html page
Оцените статью