Why is this i = (a += 2) giving SyntaxError in Python? [duplicate] - python

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

Related

python 3.7 single line for comprehension [duplicate]

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.

+= and -= expressions in Python (?) [duplicate]

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.

Ternary Conversion in Python not working well. Why? [duplicate]

This question already has answers here:
Convert decimal to ternary(base3) in python
(3 answers)
Closed 6 years ago.
I've tried to make a ternary calculator on Python, with some other functions like hex, bin, and oct with the built-in functions. There isn't one for ternary so I built one.
def ternary(n):
e = n/3
q = n%3
e = n/3
q = e%3
return q
i = int(input("May you please give me a number: "))
print("Binary "+bin(i))
print("Octal "+oct(i))
print("Hexadecimal "+hex(i))
print("Ternary "+ternary(i))
enter code here
But it doesn't work. Why? Where is the problem?
There are a couple of mistakes in your code which others have pointed out in the comments, but I'll reiterate them
You are using regular division when you want to use integer division (in Python 3).
You are returning an integer from your function whereas bin, oct, and hex all return strings.
In addition, your ternary function is incorrect, even with the errors fixed. The best way to write a function for base conversion on your own is with recursion.
def ternary(n):
if n == 0:
return ''
else:
e = n//3
q = n%3
return ternary(e) + str(q)

Why is this python code giving me a syntax error? [duplicate]

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 6 years ago.
n = [3, 5, 7]
def double_list(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x
print double_list(x)
The double_list call on the last line is giving me a SyntaxError.
In Python 3, the print syntax has been changed in order to bring more consistency with the rest of the Python syntax, which uses the brackets notation to call a function.
You must always do print(....) with the brackets, hence the SyntaxError.
print(double_list(x))
However, I do not see the rest of your code, so maybe you also have another iterable called x.
Otherwise you must also replace x by n, to avoid getting a NameError this time.
What is x in double_list(x), and why do you think it has that value?
Did you mean double_list(n)?

How to use a string as a name of array in python, so that this can be used in for-loops [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 7 years ago.
Let's say
t1=loadtxt("t\\1.txt")
t2=loadtxt("t\\2.txt")
Assume inside 1.txt is
1 2 3
4 5 6
Assume also inside 2.txt is
1 2 3
4 5 6
#
t1[0,0]=1
t1[0,1]=2
t1[0,2]=3
t2[0,0]=1
t2[0,1]=2
t2[0,2]=3
st=0
for i in range(2):
for j in range(3):
a='t'+str(i+1)
st=st+a
I got "TypeError: string indices must be integers"
What I want this piece of code to do is
st=t1[0,0]+t1[0,1]+t1[0,2]+t2[0,0]+t2[0,1]+t2[0,2]
Then how to fulfill this goal?
How to represent the array name with regular numbers in for loop? Instead of summing each value one by one.
Well you could either use a dictionary with all your t's or use the exec built in function. Python 2.x looks like this:
t1 = [1,2,3]
t2 = [1,2,3]
st=0
for i in range(2):
for j in range(3):
exec "a = t"+str(i+1)+"["+str(j)+"]"
st+=a
print st
In Python 3.x you want to use () for the built in functions. Makes the code look like this:
t1 = [1,2,3]
t2 = [1,2,3]
st=0
for i in range(2):
for j in range(3):
exec("a = t"+str(i+1)+"["+str(j)+"]")
st+=a
print(st)
The exec function will take a string and act like it was a normal line of code and execute it. This way you can assemble your command and let the interpreter do the rest. (Using String Formatting instead of connecting the string with + might be a better approach though)
There are ways to do what you want (see link in the comment to your question), but why bother when you can simply do:
st = 0
for t in (t1,t2):
for i in range(3):
st += t[0,i]

Categories