Python Forum

Full Version: cant understand the logic behind shorthand form of operator
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I don't know why the output of these two programs is different
1.
Number=123
Reverse = 0    
while(Number > 0):    
    Reminder = Number %10    
    Reverse*=10 + Reminder    
    Number = Number //10   
print(Reverse)
Output:
0
2.
Number=123
Reverse = 0    
while(Number > 0):    
    Reminder = Number %10    
    Reverse=Reverse*10 + Reminder    
    Number = Number //10   
print(Reverse)
Output:
321
This gets a little deep, but you need to read about inplace operators in the Python docs. The problem is that the assignment to Reverse (btw - don't use capitals for the first letter in variable names, see PEP 8) occurs BEFORE the addition. So, it stays 0. If you then separate the operations it works.
Number=123
Reverse = 0    
while(Number > 0):    
    Reminder = Number %10    
    Reverse*=10
    Reverse+=Reminder
    print(Reverse)    
    Number = Number //10   
print(Reverse)
Output:
3 32 321 321
from the docs:
Quote:Unlike normal assignments, augmented assignments evaluate the left-hand side before evaluating the right-hand side. For example, a[i] += f(x) first looks-up a[i], then it evaluates f(x) and performs the addition, and lastly, it writes the result back to a[i].

so, in the first snippet:

reminder *= 10 + reminder
is same as
reminder = reminder * (10 + reminder)
and reminder always stays 0