Home > database >  Why to use temporary variable to hold the input number while checking palindrome
Why to use temporary variable to hold the input number while checking palindrome

Time:08-07

Below is the python program that checks whether the given input is a palindrome.

num=int(input("Enter number:"))
temp = num
reverse=0
while(num>0):
    digit=num
    reverse=(reverse*10) digit
    num=num//10
if reverse == temp:
    print("Palindrome")
else:
    print("Not Palindrome")

When I replace 'temp' as 'num' in 'if condition'( if reverse == num: ), the output will be wrong.

num=int(input("Enter number:"))
reverse=0
while(num>0):
    digit=num
    reverse=(reverse*10) digit
    num=num//10
if reverse == num:
    print("Palindrome")
else:
    print("Not Palindrome")

Why does it return the output as "Not Palindrome"? Why do we use temporary variable to hold the input 'num'?

CodePudding user response:

Because you are changing this variable in a cycle here num=num//10 and after cycle compare changed variable:

for more understandable add prints:

num=int(input("Enter number:"))
temp = num
reverse=0
while(num>0):
    digit=num
    reverse=(reverse*10) digit
    num=num//10
    print(f'{num=}, {reverse=}, {temp=}')
if reverse == temp:
    print("Palindrome")
else:
    print("Not Palindrome")

CodePudding user response:

In the while loop, check the line

num=num//10

num is divided by 10 and replaces the old value of num. So num is getting updated in each loop.

Say you start with 4554 as the input, which is the initial value of num, but this will change in each loop into 455, then 45, then 4 and finally 0, at which point the loops ends.

So, the value of num is lost in the process of finding the digits. To be able to preserve the initial value, num is saved in temp.

You will almost always get "Not Palindrome" if you try with you try to use num instead of temp in the conditional, because num at this point will always be zero. If your initial value is zero, you would get "Palindrome".

CodePudding user response:

This is because the num variable is not the original number, as it has been modified in the while loop:

num=num//10

the num variable has been worked with and reduced down to <= 0 as the while loop repeats itself until condition of num >0 is met.

Using temp variable to store the original number is needed to compare the reverse variable with at the end, to check if the reversed number matches the original number.

  • Related