What does a comma do in a python assignment

2020-05-06 14:03发布

I have basic knowledge in c++ and I got an assignment to read a code it python and rewrite it in c++. I'm not familiar with python so I'm sorry for any newbie Q :).

In the code I see:

before,err = TG.quad(fnx, -N/2, -x)
before_n = before/all

inTime, err = TG.quad(fnx, -x,left)
inTime_n= inTime/all

in the first line, are 'before' and 'err' 2 vars who are assigned to the value from the left?

when I try to run an example for myself:

b,a= 5
print (a,b)

I get the error

"TypeError: 'int' object is not iterable",

what am I missing?

标签: python
3条回答
We Are One
2楼-- · 2020-05-06 14:47

You should have two values for each variables.

b,a= 5,5
print (a,b)

I am sure your method is returning two values.

查看更多
▲ chillily
3楼-- · 2020-05-06 14:52

Short answer:

It is simply a shorter way of assigning variables.

a, b = 1, 2

Is the same as:

a = 1
b = 2

More technical: As TigerhawkT3 says, they are not exactly the same. For example in:

a = 0
b = 1

a, b = b, a

a is 1 and b is 0, Exchanging the values of a and b. This is different from

a = b
b = a

Where a and b are 1.

On the other hand, if we do:

x = [0, 1]
i = 0
i, x[i] = 1, 2

x is [0, 2]. First assign i, then x[i].

查看更多
SAY GOODBYE
4楼-- · 2020-05-06 14:55

This is covered in the official Python tutorial, under Data Structures > Tuples and Sequences:

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

>>> x, y, z = t

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.

Note this portion:

Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence.

The statement before,err = TG.quad(fnx, -N/2, -x) fulfills this requirement, but b,a = 5 does not.

查看更多
登录 后发表回答