Home > Blockchain >  Python program to print the numbers from 10 to 100 which tens are bigger than their ones [duplicate]
Python program to print the numbers from 10 to 100 which tens are bigger than their ones [duplicate]

Time:10-05

I want to write a code that lets me print out any number in between 10 to 100 that tens are bigger than their ones. For example, 12. 12's ones(2) is bigger than its tens(1). I've written this far:

for I in range(10, 100):
  if I[1] > I[0]:
     print(I)

but I get the error: 'int' object is not subscriptable. Thank you for your time.

CodePudding user response:

You should convert the number to single digits:

for I in range(10, 100):
    digit = str(I)
    if digit[1] > digit[0]:
        print(digit)

that works fine for me

CodePudding user response:

You need to turn I to string before indexing it.

for I in range(10, 100):
  StrI = str(i)
  if StrI[1] > StrI[0]:
     print(I)

CodePudding user response:

You cannot access the digits of a number like a list. First you have to find the digits.

a = 12
b = a % 10       # 2
c = a // 10      # 1

If we were to implement it for your code, your code should be like this

for I in range(10, 100):
  if I%10 > I//10:
     print(I)

As the second method, you can convert the number to string and access its elements. Character-by-character comparison will also work (since sorting alphabetically and comparing digit values will give the same result).

for I in range(10, 100):
  s = str(I)
  if s[1] > s[0]:
     print(I)

CodePudding user response:

for I in range(10, 100):
x = str(I)
if x[1] > x[0]:
    print(x)

CodePudding user response:

Let's assume you are eager to find the numbers between 10 to 100 whose one's place value are greater than it's ten's place value - you have mistakenly written code number in between 10 to 100 that tens are bigger than their ones but have given example contrary to it.

We can approach this by looping between numbers and comparing those number's digit place by using str() built-in function.

for number in range(10, 100): 
  if str(number)[-1] > str(number)[-2]:   # if you want numbers whose ten's place value are greater than it's one's place value you can reverse the inequality (>) sign
    print(str(number))

This will work for number greater than 100 too.

CodePudding user response:

The reason this is not working is because range() returns an integer. The problem here is that the integer type is not iterable. So, your code needs to be like this

for I in range(10, 100):
      if str(I)[1] > str(I)[0]:
           print(I)

CodePudding user response:

for I in range(10, 100):
    if str(I)[1] > str(I)[0]:
        print(I)

CodePudding user response:

I think this solves your problem:

for i in range(10,100):
    if i % 10 > i // 10:
        print(i)

Note that this only works for this range of numbers

  • Related