Python Forum
cant understand the logic behind shorthand form of operator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
cant understand the logic behind shorthand form of operator
#1
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
Reply
#2
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
Reply
#3
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  If with For statement shorthand? kaega2 5 1,091 Sep-06-2022, 08:12 PM
Last Post: Gribouillis
  'namespace' shorthand for function arguments? shadowphile 5 2,586 Aug-11-2021, 09:02 PM
Last Post: shadowphile

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020