This question already has answers here:
What exactly does += do?
(17 answers)
Why does += behave unexpectedly on lists?
(9 answers)
Closed 5 years ago.
I am trying to follow the example in this post, and it was going smoothly until I ran into the lines of code with -= and += calls.
I believe this might be some sort of misprint in expressions that are supposed to update the object on the RHS of = according to some condition.
Unfortunately, interpreting this expression is key in getting what the code is doing, and guessing defeats the purpose.
Do these fragments of code or operators make any sense?
What was intended by the author?
x -= y, x += y and so forth are a shorthand way of writing x = x - y and x = x + y respectively.
These are shorthands.
a -= b
means
a = a -b
The meaning of += should be fathomable now.
But, it seems that you might have gotten some Exception. In that case, feel free to post it, and your code.
Related
This question already has answers here:
Recursive function in simple english [duplicate]
(6 answers)
Closed 11 months ago.
I was making some exercise to train myself and the exercise asked me to do a program that calculates fractals, very simple, i've done in about 1-2 minutes and it work, but looking at his solution it return x multiplicated by the function itself? how does this run? I know maybe it's a stupid question but i think it might be useful.
def fract(x):
if x == 0:
return 1
return x * fract(x - 1)
print(fract(int(input())))
Here's a walk through of whats going on.
First, you call fract(int(input())). The input method gets a response from the user and parses that to an int. and then calls fract on that int.
Say we enter 3. So our print statement evaluates to fract(3).
fract(3) returns 3 * fract(2)
fract(2) is called and that returns 2 * fract(1)
fract(1) is called and that returns 1
So putting it altogether and substituting function calls for what they return we get fract(3) returns 3 * (2 * (1)).
This question already has answers here:
How to reuse an expression in a comprehension expression?
(2 answers)
Closed 2 years ago.
I have a code that looks like this:
x = ["hello","world","if"]
test = [len(word) for word in x if len(word)>4]
print(test)
in my original code "len" is much complicated function, is there a way to do the calcualtion of len only once?
in a traditional for loop it can be done like this:
test = []
for word in x:
temp= len(word)
if temp > 4:
test.append(temp)
can you please advise how to achieve the same result without using a traditional for loop.
Thanks
You can use := operator (in case of Python 3.8+):
def my_len(s):
# ...other complicated computations...
return len(s)
x = ["hello","world","if"]
test = [l for word in x if (l:=my_len(word))>4]
print(test)
Note: don't overwrite default built-in functions, in this case len(). Other functions may depend on it.
This question already has answers here:
"+=" causing SyntaxError in Python
(6 answers)
Closed 3 years ago.
I am trying to execute exec('global expression_result; expression_result = %s' % "a += 2") in python.
It is giving me SyntaxError. I have already declared the variables a and expression_result.
In ipython, I have also tried i = (a += 2) this is also giving the SyntaxError
How to evaluate these kinds of expressions and get the result?
First, you should not use exec or eval. There is almost never a need for either of these functions.
Second, an assignment (e.g., a+=2) is not an expression in Python (unlike C, C++, or Java). It does not have a value and cannot be printed or further assigned. You can split your code into two assignments, as advised by other commenters:
a += 2
i = a
You can't do it with the += sign.
But if you write it full it works.
i = a = a + 2
so drop i = a += 2 which is basically the shortcut for i = a = a + 2
As noted by the other answers, a += 2 is not an expression in Python, so it cannot be written where an expression is expected (e.g. the right-hand-side of another assignment).
If you do want to write an assignment as an expression, this is possible since Python 3.8 using the walrus operator, but you can only use it for simple assignments, not compound assignments:
expression_result = (a := a + 2)
I recreated your code and also, got a syntax error, any way you can use two lines?:
i = a
i += 2
Are you looking for this:
a+=2
i=a
This question already has answers here:
Behaviour of increment and decrement operators in Python
(11 answers)
Closed 4 years ago.
a = 90
z =0
z =a+1
print(z)
# I want do the both steps in one step but I am getting syntax error
a = 90
z = a++
print(z)
**error
z = a++**
^
SyntaxError:
invalid syntax
Can anyone explain why? And how to do the increment using ++?
a++ does not support in python. Such as integers are immutable in python. z = a++ is invalid syntax. you can use a++ as a += 1.
a = 90
a+= 1
z = a
print(z)
I don't believe there is x++ inpython. I know how it is used, and how it adds one to a number, but python does not support this. So instead you should use x+=1. That's fixing your syntax error. But for your question about doing it in one step, do this:
a = 90
z = a + 1
This works, but using x++ is not supported in python and is not more effective tha simply adding one to a and assigning it to z.
This question already has answers here:
Why does += behave unexpectedly on lists?
(9 answers)
Closed 6 years ago.
I don't understand why these functions give different results; I thought that s+= and s=s+ were equivalent:
def foo(s):
s += ['hi']
def foo2(s):
s = s + ['hi']
But the first modifies the list s and the second does not. Could someone help me clarifying this?
x+= y is same as x = x + y only for immutable types. For mutable types, the option exists to alter the object in-place. So for lists, += is the same as list.extend() followed by a re-bind of the name.
Read: Augmented Assignment Statements and Why does += behave unexpectedly on lists? for more information.
Use list.append because if you say s = s +['hi'] then s just point to another object, but if you use .append() then the same list is being changed