What does a comma do in a python assignment

前端 未结 3 913
遇见更好的自我
遇见更好的自我 2021-01-27 08:10

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

相关标签:
3条回答
  • 2021-01-27 08:41

    You should have two values for each variables.

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

    I am sure your method is returning two values.

    0 讨论(0)
  • 2021-01-27 08:44

    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].

    0 讨论(0)
  • 2021-01-27 08:52

    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.

    0 讨论(0)
提交回复
热议问题