Python Forum

Full Version: Reverse a number
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi! So for my homework assignment, we have to reverse a four digit number.

# Python Class 2402
# Lesson 2 Problem 6
# Author: KitKatKarateIlluminati (491160)

FourDigit = int(input("Please enter a four digit number: "))

First = FourDigit % 10
Second = ((FourDigit % 100) - First)/10
Third = (FourDigit - (Second * 10 + First))/100
Fourth = (FourDigit - (First + Second * 10 + Third * 100))/1000

Reverse = Fourth + Third * 10 + Second * 100 + First * 1000
print(Reverse)
Can you guys please tell me why this is wrong?

Thanks in advance!
Big Grin
I think that the easiest way would be to convert int to a string, reverse it, construct a new string and convert it back to int. As you actually have a string as user input then you can skip conversion. Doesn't matter how many digits:

>>> num = 12345
>>> int(''.join((reversed(str(num)))))
54321
If you want to calculate, maybe have a look at builtin divmod()
First = FourDigit % 10
Second = ((FourDigit - First) % 100) /10
Third = ((FourDigit - (Second * 10 + First)) /100)%10
Fourth = (FourDigit - (First + Second * 10 + Third * 100))/1000
Or

>>> FourDigit='1234'
>>> FourDigit[::-1]
'4321'
Interesting operators and functions you should read more about:
  • % operator for rest of division
  • // operator for integer division
  • += operator for inline add
  • //= operator for inline integer division
  • math.log10 -> how many digits does a number have?
  • The inverse of math.log10 is 10 ** value
  • divmod, also good for days, hours, minutes, seconds, microseconds
    seconds = 13371232
    minutes, seconds = divmod(seconds, 60)
    hour, minutes = divmod(minutes, 60)
    days, hour = divmod(hour, 24)
    print("Days:", days, "Hours:", hour, "Minutes:", minutes, "Seconds", seconds)
  • reversed() vs. subscription reverse: [::-1]

I removed my solution.
You should do it mathematically.
You can do this :
num1 = input("Please enter a 4-digit number : ")
num2 = num1[::-1]
print(num2)
And output :
Output:
Please enter a 4-digit number : 1234 4321