how to resolve this "inf" problem with python code


i have a problem with this python code for inverting a Number
like Nb = 358 —> inv = 853
but in the end i got ‘inf’ msg from the prog , and its runs normally in C language

def envers(Nb):
 inv = 0
 cond = True
 while cond:
    s = Nb % 10
    inv = (inv*10)+ s
    Nb = Nb/10
    if Nb == 0:
        cond = False
 return inv

data = int(input("give num"))
res = envers(data)
Asked By: Abdelhak Mez



This is likely much easier to do via string manipulation, which has a friendly and simple syntax (which are a major reason to choose to use Python)

>>> int(input("enter a number to reverse: ")[::-1])
enter a number to reverse: 1234

How this works

  • input() returns a string
  • strings are iterable and [::-1] is used to reverse it
  • finally convert to an int

Add error checking to taste (for example to to ensure you really received a number)

Answered By: ti7

When you set

Nb = Nb / 10

Nb becomes a float (say 1 -> 0.1) and will be able to keep being divided until it reaches a certain limit.

By that point, your inv value will reach python’s limits and become ‘inf’.

Replacing this line with

Nb = Nb // 10

using Python’s builtin integer division will fix the issue.

Answered By: yanjunk

Here is a simple implementation for a numerical approach:

def envers(Nb):
    out = 0
    while Nb>0:
        Nb, r = divmod(Nb, 10)
        out = 10*out + r
    return out

# 4321

# 853

# 201

Without divmod:

def envers(Nb):
    out = 0
    while Nb>0:
        r = Nb % 10
        Nb //= 10
        out = 10*out + r
    return out
Answered By: mozway
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.