0

So i got this code to check if a number is a palindrome and it works fine but i got a question on the usage of some operator in the while loop. The operator // that is used between the original variable and integer 10. What is it doing to the original p value , is it dividing or? Here is the code am using

def test_palindrome(p):
    o=p#store the original value of p in some variable
    reversed_number=0#declare reversed_number and init to zero
    while(p>0):
        rem=p%10#Get the remainder of argument and ten
        reversed_number=reversed_number*10+rem
        p=p//10#This is the operator whose function is in question, am not sure if its dividing
    if(reversed_number==o):#do comparison with original input and return 
        print(f"{o} is a palindrome")
    else:
        print(f"{o} is not a palindrome")
test_palindrome(number)

1 Answers1

1

// means floor division. Floor division will always give you the integer floor of the result

Your program first starts with checking if p>0. Lets say p = 1001.

1001 // 10 = 100 whereas 1001/10 = 100.1

If you used p/10 instead of p//10. p would never be less than 0. A decimal: 0.1 (example) would always exist. Therefore, the conditon p>0 would always be true, breaking your program.


As mentioned in the comments, this post may be of use.

Jacques
  • 927
  • 9
  • 18
  • 1
    Thanks for the explanation i was just wondering what the operator means –  Mar 25 '21 at 16:00
  • @CoderTimothy No problem, thought it would be of use to include what it means in terms of your program as well. – Jacques Mar 25 '21 at 16:03