简体   繁体   中英

Function returning 1 instead of the reverse of the Number

Hey I have this function in python3 , can anyone explain why it is giving 1 as output instead of the number as reverse

def reverse(a , rev):
    if a > 0:
        d =  a % 10
        rev = (rev * 10) + d
        reverse(a/10 , rev)

    return rev

b = input("Enter the Number")
x = reverse(b , 0)
print(x)

You need to:

  • use integer division ( // )
  • capture the value returned from the recursive call, and return it
  • convert the string input to number ( int() )

Corrected script:

def reverse(a, rev):
    if a > 0:
        d =  a % 10
        rev = (rev * 10) + d
        return reverse(a//10, rev)

    return rev

b = input("Enter the Number")
x = reverse(int(b), 0)
print(x)

I'm not sure why you're doing it like that. Seems like the following is easier

def rev(a):
   return int(str(a)[::-1])

Anyway, I believe you should use "//" instead of "/" for dividing without the rest in python 3?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM