I have been trying to write a program to reverse a number in Python, but it dosen't work as expected whereas only assigning the condition to a variable, it makes the code work fine. Please explain why this happens or whether this is a bug.
I am using Python 3.10.4. The codes are given below.
This one does not work as I guess the problem is in while loop and its condition.
num2 = int(input("Enter the number to be reversed: "))
c = 0
rev = 0
while c!=len(str(num2)):
n = num2
rev=rev*10 n
num2=num2//10
c =1
print("The reversed number is:",rev)
Output:
Enter the number to be reversed: 1568
The reversed number is: 86
This one does work as expected just by assigning a part of condition to a variable
num2 = int(input("Enter the number to be reversed: "))
c = 0
rev = 0
length = len(str(num2))
while c!=length:
n = num2
rev=rev*10 n
num2=num2//10
c =1
print("The reversed number is:",rev)
Output:
Enter the number to be reversed: 1568
The reversed number is: 8651
CodePudding user response:
The condition in the while
loop is evaluated again in each iteration. Because your first version evaluates the current length of num2
and you change the value inside the loop, you have a bug. Change the code so it uses a different variable (initialized as a copy of num2
) inside the loop if you prefer this formulation for some reason; but the second version of the code is IMHO clearer as well as correct.
However, notice also that Python already knows how to reverse a string.
rev_num = int(str(num2)[::-1])
CodePudding user response:
I think you can also use simple string slicing to achive the same result
num_to_rev = 1568
rev_num = str(num_to_rev)[::-1]
print(rev_num)