Как найти разряд десятков в питоне

Разряд десятков на Python

Опубликовано: 07.11.2020Рубрика: Snakify Python

Условие: Дано целое число. Выведите его десятизначную (разряд десятков) цифру.

Решение:

# Read an integer:
num = int(input())
# Read a float:
# b = float(input())
# Print a value:
print((num % 100) // 10)

Пояснение:

  1. Первым делом надо считать целое число и записать его в переменную
  2. Затем сначала найти остаток от деления на 100 и его целочисленно (без остатка) поделить на 10.

Тренировочное задание по программированию: Вторая справа цифра (одна из задачек ))

Тренировочное задание по программированию: Вторая справа цифра

Дано натуральное число. Найдите цифру, стоящую в разряде десятков в его десятичной записи (вторую справа цифру).

Формат ввода

Вводится единственное число.

Формат вывода

Выведите ответ на задачу.

вначале не понимал, что не так, но после дружеского пинка разобрался )).

nnn = int(input())

k = 1

n = (nnn // 10 ** k) % 10

print(n)

Популярные сообщения из этого блога

Задание по программированию: Узник замка Иф

Задание по программированию: Узник замка Иф За многие годы заточения узник замка Иф проделал в стене прямоугольное отверстие размером D×E. Замок Иф сложен из кирпичей, размером A×B×C. Определите, сможет ли узник выбрасывать кирпичи в море через это отверстие, если стороны кирпича должны быть параллельны сторонам отверстия. Формат ввода Программа получает на вход числа A,B,C,D,E. Формат вывода Программа должна вывести слово YES или NO. Примеры Тест 1 Входные данные: 1 1 1 1 1 Вывод программы: YES Тест 2 Входные данные: 2 2 2 1 1 Вывод программы: NO решение: a = int(input()) b = int(input()) c = int(input()) d = int(input()) e = int(input()) if a <= d and b <= e or a <= e and b <= d:     print(“YES”) elif c <= d and b <= e or c <= e and b <= d:     print(“YES”) elif c <= d and a <= e or c <= e and a <= d:     print(“YES”) else:     print(”

Тренировочное задание по программированию: Симметричное число* (ещё одна интересная задачка ))

Дано четырехзначное число. Определите, является ли его десятичная запись симметричной. Если число симметричное, то выведите 1, иначе выведите любое другое целое число. Число может иметь меньше четырех знаков, тогда нужно считать, что его десятичная запись дополняется слева незначащими нулями. Формат ввода Вводится единственное число. Формат вывода Выведите ответ на задачу. Примеры Тест 1 Входные данные: 2002 Вывод программы: 1 Решение nnn = int(input()) k1 = 1 k2 = 2 k3 = 3 n3 = (nnn // 10 ** k1) % 10 n2 = (nnn // 10 ** k2) % 10 n1 = (nnn // 10 ** k3) % 10 n4 = (nnn % 10 ** k1) if n1 == n4 and n2 == n3:     print(1) else:     print(2)

Victor Surozhtsev

Просветленный

(28028)


3 года назад

По-моему тоже тут не вполне чёткое условие. Что такое “число десятков”? Цифра второго разряда в десятичной записи натурального числа? Тогда так:

print(int(input(‘n = ?b’))//10%10)

А если их полное количество, тогда немного по другому:

print(int(input(‘n = ?b’))//10)

No NameУченик (106)

3 года назад

У чувака выше комментарием дал ответ
Пользователь вводит четырёхзначное число. Программа должна вывести 1, если оно является симметричным, иначе — любое другое число. сможешь?

Студворк — интернет-сервис помощи студентам

Дано натуральное число. Найдите цифру, стоящую в разряде десятков в его десятичной записи (вторую справа цифру или 0, если число меньше 10).

Замечание

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

Формат ввода

Вводится единственное число.

Формат вывода

Выведите ответ на задачу.

Примеры
Ввод:
73
Вывод:
7

Написал код к этой задаче, но где-то ошибся. Просьба знающим подсказать, где я накосячил.

Python
1
2
3
4
5
num = int(input())
if num < 10:
    print(num)
else:
    print(num // 10 % 10)
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.

Brian Tompsett - 汤莱恩's user avatar

asked Sep 24, 2015 at 3:18

Johan's user avatar

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 S's user avatar

Aaron SAaron S

4,9034 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 Guan's user avatar

Remi GuanRemi Guan

21.3k17 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

imakappa's user avatar

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

ladhee's user avatar

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.

Zoe stands with Ukraine's user avatar

answered Aug 12, 2019 at 10:10

akshay karhade's user avatar

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

Bern P's user avatar

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

PCM's user avatar

PCMPCM

2,8212 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

Chris's user avatar

ChrisChris

2,1381 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

dochenaj's user avatar

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

Matt's user avatar

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

riyazahamad03's user avatar

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's user avatar

Tomerikoo

18.1k16 gold badges45 silver badges60 bronze badges

answered Apr 26, 2021 at 16:50

DHINESHKUMAR D's user avatar

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

Jadon's Shoes's user avatar

Добавить комментарий