num = int(input("Please give me a number: "))
print(num)
thou = int((num // 1000))
print(thou)
hun = int((num // 100))
print(hun)
ten =int((num // 10))
print(ten)
one = int((num // 1))
print(one)
I tried this but it does not work and I’m stuck.
asked Sep 24, 2015 at 3:18
4
You might want to try something like following:
def get_pos_nums(num):
pos_nums = []
while num != 0:
pos_nums.append(num % 10)
num = num // 10
return pos_nums
And call this method as following.
>>> get_pos_nums(9876)
[6, 7, 8, 9]
The 0th
index will contain the units, 1st
index will contain tens, 2nd
index will contain hundreds and so on…
This function will fail with negative numbers. I leave the handling of negative numbers for you to figure out as an exercise.
answered Jun 28, 2018 at 0:28
Aaron SAaron S
4,9334 gold badges29 silver badges29 bronze badges
Like this?
a = str(input('Please give me a number: '))
for i in a[::-1]:
print(i)
Demo:
Please give me a number: 1324
4
2
3
1
So the first number is ones, next is tens, etc.
answered Sep 24, 2015 at 3:24
Remi GuanRemi Guan
21.4k17 gold badges63 silver badges87 bronze badges
1
num = 1234
thousands = num // 1000
hundreds = (num % 1000) // 100
tens = (num % 100) // 10
units = (num % 10)
print(thousands, hundreds, tens, units)
# expected output: 1 2 3 4
«//» in Python stands for integer division. It largely removes the fractional part from the floating-point number and returns an integer
For example:
4/3 = 1.333333
4//3 = 1
answered Jun 8, 2021 at 2:19
You could try splitting the number using this function:
def get_place_values(n):
return [int(value) * 10**place for place, value in enumerate(str(n)[::-1])]
For example:
get_place_values(342)
>>> [2, 40, 300]
Next, you could write a helper function:
def get_place_val_to_word(n):
n_str = str(n)
num_to_word = {
"0": "ones",
"1": "tens",
"2": "hundreds",
"3": "thousands"
}
return f"{n_str[0]} {num_to_word[str(n_str.count('0'))]}"
Then you can combine the two like so:
def print_place_values(n):
for value in get_place_values(n):
print(get_place_val_to_word(value))
For example:
num = int(input("Please give me a number: "))
# User enters 342
print_place_values(num)
>>> 2 ones
4 tens
3 hundreds
answered Jun 29, 2021 at 2:19
imakappaimakappa
1462 silver badges4 bronze badges
num=1234
digit_at_one_place=num%10
print(digit_at_one_place)
digits_at_tens_place=(num//10)%10
digits_at_hund_place=(num//100)%10
digits_at_thou_place=(num//1000)%10
print(digits_at_tens_place)
print(digits_at_hund_place)
print(digits_at_thou_place)
this does the job. it is simple to understand as well.
answered Nov 26, 2021 at 5:21
Please note that I took inspiration from the above answer by 6pack kid to get this code. All I added was a way to get the exact place value instead of just getting the digits segregated.
num = int(input("Enter Number: "))
c = 1
pos_nums = []
while num != 0:
z = num % 10
pos_nums.append(z *c)
num = num // 10
c = c*10
print(pos_nums)
Once you run this code, for the input of 12345 this is what will be the output:
Enter Number: 12345
[5, 40, 300, 2000, 10000]
This helped me in getting an answer to what I needed.
answered Aug 12, 2019 at 10:10
money = int(input("Enter amount: "))
thousand = int(money // 1000)
five_hundred = int(money % 1000 / 500)
two_hundred = int(money % 1000 % 500 / 200)
one_hundred = int(money % 1000 % 500 % 200 / 100)
fifty = int(money % 1000 % 500 % 200 % 100 / 50)
twenty = int(money % 1000 % 500 % 200 % 100 % 50 / 20)
ten = int(money % 1000 % 500 % 200 % 100 % 50 % 20 / 10)
five = int(money % 1000 % 500 % 200 % 100 % 50 % 20 % 10 / 5)
one = int(money % 1000 % 500 % 200 % 100 % 50 % 20 % 10 % 5 / 1)
if thousand >=1:
print ("P1000: " , thousand)
if five_hundred >= 1:
print ("P500: " , five_hundred)
if two_hundred >= 1:
print ("P200: " , two_hundred)
if one_hundred >= 1:
print ("P100: " , one_hundred)
if fifty >= 1:
print ("P50: " , fifty)
if twenty >= 1:
print ("P20: " , twenty)
if ten >= 1:
print ("P10: " , ten)
if five >= 1:
print ("P5: " , five)
if one >= 1:
print ("P1: " , one)
answered Feb 2, 2020 at 14:53
Quickest way:
num = str(input("Please give me a number: "))
print([int(i) for i in num[::-1]])
answered Jun 29, 2021 at 11:45
PCMPCM
2,8312 gold badges8 silver badges30 bronze badges
This will do it, doesn’t use strings at all and handles any integer passed for col
sensibly.
def tenscol(num: int, col: int):
ndigits = 1
while (num % (10**ndigits)) != num:
ndigits += 1
x = min(max(1, col), ndigits)
y = 10**max(0, x - 1)
return int(((num % 10**x) - (num % y)) / y)
usage:
print(tenscol(9785,-1))
print(tenscol(9785,1))
print(tenscol(9785,2))
print(tenscol(9785,3))
print(tenscol(9785,4))
print(tenscol(9785,99))
Output:
5
5
8
7
9
9
answered Nov 6, 2021 at 21:56
ChrisChris
2,1371 gold badge24 silver badges36 bronze badges
def get_pos(num,unit):
return int(abs(num)/unit)%10
So for «ones» unit is 1 while for «tens», unit is 10 and so forth.
It can handle any digit and even negative numbers effectively.
So given the number 256, to get the digit in the tens position you do
get_pos(256,10)
>> 5
answered Nov 12, 2021 at 22:04
I had to do this on many values of an array, and it’s not always in base 10 (normal counting — your tens, hundreds, thousands, etc.). So the reference is slightly different: 1=1st place (1s), 2=2nd place (10s), 3=3rd place (100s), 4=4th place (1000s). So your vectorized solution:
import numpy as np
def get_place(array, place):
return (array/10**(place-1)%10).astype(int)
Works fast and also works on arrays in different bases.
answered Apr 7, 2022 at 20:15
MattMatt
2,55212 silver badges36 bronze badges
# method 1
num = 1234
while num>0:
print(num%10)
num//=10
# method 2
num = 1234
print('Ones Place',num%10)
print('tens place',(num//10)%10)
print("hundred's place",(num//100)%10)
print("Thousand's place ",(num//1000)%10)
answered Dec 2, 2022 at 13:57
1
In Python, you can try this method to print any position of a number.
For example, if you want to print the 10 the position of a number,
Multiply the number position by 10, it will be 100,
Take modulo of the input by 100 and then divide it by 10.
Note: If the position get increased then the number of zeros in modulo and in divide also increases:
input = 1234
print(int(input % 100) / 10 )
Output:
3
Tomerikoo
18.1k16 gold badges45 silver badges60 bronze badges
answered Apr 26, 2021 at 16:50
1
So I saw what another users answer was and I tried it out and it didn’t quite work, Here’s what I did to fix the problem. By the way I used this to find the tenth place of a number
# Getting an input from the user
input = int(input())
# Finding the tenth place of the number
print(int(input % 100) // 10)
answered Jun 28, 2021 at 20:38
0 / 0 / 0 Регистрация: 20.10.2019 Сообщений: 12 |
|
1 |
|
Количество тысяч, сотен, десятков и единиц в числе01.12.2019, 19:30. Показов 38794. Ответов 7
Пожалуйста напишите программу, определяющую количество тысяч, сотен, десятков и единиц во введенном числе (диапазон от 1 до 999 999).
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
01.12.2019, 19:30 |
Ответы с готовыми решениями: В числе 4982 найти число тысяч, сотен, десятков и единиц
Найти в заданном трехзначном числе количество тысяч, десятков и единиц 7 |
814 / 526 / 214 Регистрация: 22.12.2017 Сообщений: 1,495 |
|
01.12.2019, 20:54 |
2 |
имеется ввиду 999т9с9д9е или 999999е999т…?
0 |
0 / 0 / 0 Регистрация: 20.10.2019 Сообщений: 12 |
|
01.12.2019, 22:07 [ТС] |
3 |
чтобы для числа 999999 программа выдавала: 999 тысяч, 9 сотен, 9 десятков, 9 единиц к примеру
0 |
codcw 814 / 526 / 214 Регистрация: 22.12.2017 Сообщений: 1,495 |
||||
01.12.2019, 23:26 |
4 |
|||
0 |
0 / 0 / 0 Регистрация: 20.10.2019 Сообщений: 12 |
|
03.12.2019, 21:53 [ТС] |
5 |
не работает
0 |
codcw 814 / 526 / 214 Регистрация: 22.12.2017 Сообщений: 1,495 |
||||
03.12.2019, 23:08 |
6 |
|||
упс
0 |
0 / 0 / 0 Регистрация: 20.10.2019 Сообщений: 12 |
|
16.12.2019, 00:11 [ТС] |
7 |
и это не работает
0 |
codcw 814 / 526 / 214 Регистрация: 22.12.2017 Сообщений: 1,495 |
||||
16.12.2019, 02:21 |
8 |
|||
что значит «не работает»? почему тогда у меня всё работает?
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
16.12.2019, 02:21 |
Помогаю со студенческими работами здесь
Я считываю файлы… Из четырехзначного числа получить: первое число — сумма тысяч и сотен, второе — десятков и единиц
Составьте программу, которая запрашивает колличество сотен, десятков и единиц в загаданном числе и выводит его полное название Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 8 |
Светило науки — 214 ответов — 0 раз оказано помощи
1. a = int(input())
print(‘Количестdо сотен равно’, a // 10 % 10, ‘Количество единиц равно’, a % 10)
2. Либо (более понятный способ):
a = int(input()) #ввод трёхзначного числа
a1 = a % 10 #количество единиц. Почему? На примере понятнее. Допустим введено число 123. Тогда остаток от деления на 10 — это 3. То есть последнее число, то есть количество единиц
a2 = a // 10 % 10 #количество сотен. Допустим введено число 123. Тогда сперва целочисленное деления, получается 12. Далее остаток от деления 12 на 10, он равен 2. Это и есть количество сотен
print(‘Количестdо сотен равно’, a1, ‘Количество единиц равно’, a2)
num = int(input("Please give me a number: "))
print(num)
thou = int((num // 1000))
print(thou)
hun = int((num // 100))
print(hun)
ten =int((num // 10))
print(ten)
one = int((num // 1))
print(one)
Я пробовал это, но это не работает, и я застрял.
13 ответов
Как это?
a = str(input('Please give me a number: '))
for i in a[::-1]:
print(i)
<Сильные> Демо:
Please give me a number: 1324
4
2
3
1
Итак, первое число — единицы, следующее — десятки и т. д.
6
Remi Guan
24 Сен 2015 в 06:24
Возможно, вы захотите попробовать что-то вроде следующего:
def get_pos_nums(num):
pos_nums = []
while num != 0:
pos_nums.append(num % 10)
num = num // 10
return pos_nums
И вызовите этот метод следующим образом.
>>> get_pos_nums(9876)
[6, 7, 8, 9]
Индекс 0th
будет содержать единицы, индекс 1st
будет содержать десятки, индекс 2nd
будет содержать сотни и так далее…
Эта функция не работает с отрицательными числами. Я оставляю вам обработку отрицательных чисел в качестве упражнения.
13
Aaron S
28 Июн 2018 в 03:28
num = 1234
thousands = num // 1000
hundreds = (num % 1000) // 100
tens = (num % 100) // 10
units = (num % 10)
print(thousands, hundreds, tens, units)
# expected output: 1 2 3 4
«//» в Python означает целочисленное деление. Он в значительной степени удаляет дробную часть из числа с плавающей запятой и возвращает целое число.
Например:
4/3 = 1.333333
4//3 = 1
3
user14665723user14665723
8 Июн 2021 в 05:19
Вы можете попробовать разделить число, используя эту функцию:
def get_place_values(n):
return [int(value) * 10**place for place, value in enumerate(str(n)[::-1])]
Например:
get_place_values(342)
>>> [2, 40, 300]
Далее вы можете написать вспомогательную функцию:
def get_place_val_to_word(n):
n_str = str(n)
num_to_word = {
"0": "ones",
"1": "tens",
"2": "hundreds",
"3": "thousands"
}
return f"{n_str[0]} {num_to_word[str(n_str.count('0'))]}"
Затем вы можете объединить их так:
def print_place_values(n):
for value in get_place_values(n):
print(get_place_val_to_word(value))
Например:
num = int(input("Please give me a number: "))
# User enters 342
print_place_values(num)
>>> 2 ones
4 tens
3 hundreds
1
imakappa
29 Июн 2021 в 05:25
Самый быстрый способ:
num = str(input("Please give me a number: "))
print([int(i) for i in num[::-1]])
0
PCM
29 Июн 2021 в 14:45
Это сделает это, вообще не использует строки и разумно обрабатывает любое целое число, переданное для col
.
def tenscol(num: int, col: int):
ndigits = 1
while (num % (10**ndigits)) != num:
ndigits += 1
x = min(max(1, col), ndigits)
y = 10**max(0, x - 1)
return int(((num % 10**x) - (num % y)) / y)
Применение:
print(tenscol(9785,-1))
print(tenscol(9785,1))
print(tenscol(9785,2))
print(tenscol(9785,3))
print(tenscol(9785,4))
print(tenscol(9785,99))
Выход:
5
5
8
7
9
9
0
Chris
7 Ноя 2021 в 00:56
num=1234
digit_at_one_place=num%10
print(digit_at_one_place)
digits_at_tens_place=(num//10)%10
digits_at_hund_place=(num//100)%10
digits_at_thou_place=(num//1000)%10
print(digits_at_tens_place)
print(digits_at_hund_place)
print(digits_at_thou_place)
Это делает работу. это также просто понять.
1
ladhee
26 Ноя 2021 в 08:21
В Python вы можете попробовать этот метод для печати любой позиции числа.
Например, если вы хотите напечатать 10 позицию числа, умножьте позицию числа на 10, это будет 100, возьмите модуль ввода на 100, а затем разделите его на 10.
Примечание. Если позиция увеличивается, количество нулей по модулю и при делении также увеличивается:
input = 1234
print(int(input % 100) / 10 )
Выход:
3
-1
Tomerikoo
26 Апр 2021 в 22:29
Итак, я увидел ответ другого пользователя и попробовал его, но он не совсем сработал. Вот что я сделал, чтобы решить проблему. Кстати, я использовал это, чтобы найти десятый разряд числа
# Getting an input from the user
input = int(input())
# Finding the tenth place of the number
print(int(input % 100) // 10)
-1
Jadon’s Shoes
31 Июл 2021 в 04:59
money = int(input("Enter amount: "))
thousand = int(money // 1000)
five_hundred = int(money % 1000 / 500)
two_hundred = int(money % 1000 % 500 / 200)
one_hundred = int(money % 1000 % 500 % 200 / 100)
fifty = int(money % 1000 % 500 % 200 % 100 / 50)
twenty = int(money % 1000 % 500 % 200 % 100 % 50 / 20)
ten = int(money % 1000 % 500 % 200 % 100 % 50 % 20 / 10)
five = int(money % 1000 % 500 % 200 % 100 % 50 % 20 % 10 / 5)
one = int(money % 1000 % 500 % 200 % 100 % 50 % 20 % 10 % 5 / 1)
if thousand >=1:
print ("P1000: " , thousand)
if five_hundred >= 1:
print ("P500: " , five_hundred)
if two_hundred >= 1:
print ("P200: " , two_hundred)
if one_hundred >= 1:
print ("P100: " , one_hundred)
if fifty >= 1:
print ("P50: " , fifty)
if twenty >= 1:
print ("P20: " , twenty)
if ten >= 1:
print ("P10: " , ten)
if five >= 1:
print ("P5: " , five)
if one >= 1:
print ("P1: " , one)
0
Bern P
2 Фев 2020 в 17:53
def get_pos(num,unit):
return int(abs(num)/unit)%10
Таким образом, единица измерения «единицы» равна 1, единица измерения «десятки» равна 10 и так далее.
Он может эффективно обрабатывать любые цифры и даже отрицательные числа.
Итак, учитывая число 256, чтобы получить цифру в позиции десятков, которую вы делаете
get_pos(256,10)
>> 5
0
dochenaj
13 Ноя 2021 в 01:16
Обратите внимание, что я черпал вдохновение из приведенного выше ответа 6pack kid, чтобы получить этот код. Все, что я добавил, — это способ получить точное значение места, а не просто разделить цифры.
num = int(input("Enter Number: "))
c = 1
pos_nums = []
while num != 0:
z = num % 10
pos_nums.append(z *c)
num = num // 10
c = c*10
print(pos_nums)
Как только вы запустите этот код, для ввода 12345 это будет то, что будет на выходе:
Enter Number: 12345
[5, 40, 300, 2000, 10000]
Это помогло мне получить ответ на то, что мне нужно.
0
Zoe stands with Ukraine
17 Авг 2019 в 17:53
Мне приходилось делать это для многих значений массива, и это не всегда в базе 10 (обычный счет — ваши десятки, сотни, тысячи и т. д.). Таким образом, ссылка немного отличается: 1 = 1 место (1 с), 2 = 2 место (10 с), 3 = 3 место (100 с), 4 = 4 место (1000 с). Итак, ваше векторизованное решение:
import numpy as np
def get_place(array, place):
return (array/10**(place-1)%10).astype(int)
Работает быстро, а также работает с массивами в разных базах.
0
Matt
7 Апр 2022 в 23:15
На чтение 3 мин Просмотров 787 Опубликовано 02.03.2023
Содержание
- Введение
- Длинный способ с циклом while
- Короткий способ циклом for
- Самый быстрый способ
- Заключение
Введение
В ходе статьи рассмотрим три вариации кода для определения количества разрядов в ведённом пользователем числе на языке программирования Python.
Длинный способ с циклом while
Дадим пользователю возможность ввести число:
n = int(input('Введите число: '))
Если было введено отрицательное число, нужно его сделать положительным. Для этого добавим его в модуль методом abs():
n = int(input('Введите число: '))
n = abs(n)
Добавим переменную count равную нулю:
n = int(input('Введите число: '))
n = abs(n)
count = 0
Создадим цикл while, который не закончится, пока n > 0. В цикле будем убирать последнюю цифру в переменной n, а к count прибавлять единицу:
n = int(input('Введите число: '))
n = abs(n)
count = 0
while n > 0:
n //= 10
count += 1
Осталось вывести результат:
n = int(input('Введите число: '))
n = abs(n)
count = 0
while n > 0:
n //= 10
count += 1
print(count)
# Введите число: 164832
# 6
Короткий способ циклом for
Обычно подобным не занимаются при помощи цикла for, но почему бы и нет. Как и в предыдущем способе даём пользователю возможность ввода числа, и добавляем его в модуль. Также создаём переменную count равную нулю:
n = abs(int(input('Введите число: ')))
count = 0
Создадим цикл for, в котором пройдёмся по количеству символов в переменной n. Внутри цикла прибавляем к count единицу:
n = abs(int(input('Введите число: ')))
count = 0
for i in range(len(str(n))):
count += 1
Выведем результат в консоль:
n = abs(int(input('Введите число: ')))
count = 0
for i in range(len(str(n))):
count += 1
print(count)
# Введите число: 111
# 3
Самый быстрый способ
Как и в предыдущих способах даём пользователю возможность ввода числа, и добавляем его в модуль:
n = abs(int(input('Введите число: ')))
Теперь в переменную count сохраним длину значения преобразованного в строковый тип данных в переменной n:
n = abs(int(input('Введите число: ')))
count = len(str(n))
Выведем результат:
n = abs(int(input('Введите число: ')))
count = len(str(n))
print(f'В числе {n} находится {count} разрядов.')
# Введите число: 17424312
# В числе 17424312 находится 8 разрядов.
Заключение
В ходе статьи мы с Вами разобрали целых 3 способа определить количество разрядов в числе в Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂