Joe
Joe

Reputation: 23

Runtime Error in Python code for reversing a number using a function

I am getting a Runtime Error saying:

ValueError: invalid literal for int() with base 10: 'intreverse(368)'

What could be the solution for this problem?

This is my code:

def intreverse(n):
    rev=0
    dig=0
    while(n>=0):
        dig=n%10
        rev=rev*10+dig
        n=n//10
n=int(input("enter the number:"))
rev=intreverse(n)
print("Reverse is",rev)

Upvotes: 1

Views: 501

Answers (2)

helcode
helcode

Reputation: 2048

You want to reverse an integer (ex. intreverse(123) = 321)

Your function have two issues,

  1. No return value (your function always returns None)
  2. The while loop enters an infinite run (intreverse(123) returns 321000...0 because n=n//10 will never break the condition n>=0 for any positive n)

Hence, I would fix the above two problems by re-writing your function as per the following,

def intreverse(n):
    rev=0
    dig=0
    while(n > 0):
        dig = n%10
        rev = rev*10 + dig
        n = n//10
    return rev

n=int(input("enter the number:"))
rev=intreverse(n)
print("Reverse is",rev)

Limitations: Above code will fail to reverse a number with zeros in its least-significant place (as in case-2 below)

  1. intreverse(123001) will return 100321 which is OK
  2. intreverse(123000) will return 321

If case-2 (above) is of interest to you, then I would recommend to cast the integer into a string & reverse the string as per the following code.

def gen_intreverse(n):
    s = str(n)
    rev = ''
    for letter in s:
        rev = letter + rev
    return rev

Or you can simply use the [::-1] modifier as per the following

def gen_intreverse(n):
    s = str(n)
    return s[::-1]

Upvotes: 2

ShellBox Nut
ShellBox Nut

Reputation: 56

def gen_intreverse(n):
    return str(n)[::-1]

will return reversed string. intreverse(123001) will return "100321" if you want int value. just int() to output value.

Upvotes: 0

Related Questions