Reputation: 1
I need to change the value of nValor
on the same line that I'm messing with cInText
the desired way of doing:
cText = "Something"
nValor = len(cText)-1
cInText = ""
while nValor >= 0:
cInText += cText[nValor -= 1]
print(cInText)
the unwanted way of doing:
cText = "Something"
nValor = len(cText)-1
cInText = ""
while nValor >= 0:
cInTexto += cTexto[nValor]
nValor -= 1
print(cInTexto)
Upvotes: 0
Views: 45
Reputation: 1055
Judging by your second excerpt it seems you ideally want post-decrement operator behaviour, but Python has neither pre- nor post-increment/decrement operators. See this question and answers for details.
You can, however, get desired behaviour by using multiple-target assignment like this:
cInText, nValor = cInText + cText[nValor], nValor - 1
First, right-hand side will be evaluated to a tuple of 2 elements, after which 2 comma-separated targets will be assigned to respective tuple elements.
If you want pre-decrement behaviour however (as suggested by your first example), since Python 3.8 you can use assignment expression (walrus assignment) like this:
cInText += cText[nValor := nValor - 1]
Here, value of expression nValor := nValor - 1
is just nValor - 1
, but as a side-effect this expression also assigns this value to nValor
, as desired.
Note that in your case post-decrement behaviour is needed if you want to reverse cInText
(otherwise, nValor
indexes will be incorrect and result in negative index on the last iteration). Also, if this is not a toy example and your original problem is to do a reverse, take a look at this question and answers.
Upvotes: 1