![]() |
cant understand the logic behind shorthand form of operator - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: cant understand the logic behind shorthand form of operator (/thread-26977.html) |
cant understand the logic behind shorthand form of operator - pradeep_sn - May-20-2020 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) 2.Number=123 Reverse = 0 while(Number > 0): Reminder = Number %10 Reverse=Reverse*10 + Reminder Number = Number //10 print(Reverse)
RE: cant understand the logic behind shorthand form of operator - jefsummers - May-20-2020 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)
RE: cant understand the logic behind shorthand form of operator - buran - May-20-2020 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 + reminderis same as reminder = reminder * (10 + reminder)and reminder always stays 0 |