SoFunction
Updated on 2024-11-21

Example analysis of the three roles of commas in Python

This example article describes the three roles of commas in Python. Shared for your reference. The specific analysis is as follows:

Recently, I've been working on python, and I ran into a comma problem that I haven't been able to figure out, but I finally got it today.

1. The use of commas in parameter passing:

There's not much to say about this case, but there's nothing to understand about the commas between the parameters when passing formal or real parameters.

For example def abc(a,b) or abc(1,2)

2. The use of commas in type conversion Mainly tuple conversion

Example.

>>> a=11
>>> b=(a)
>>> b
11
>>> b=(a,)
>>> b
(11,)
>>> b=(a,22)
>>> b
(11, 22)
>>> b=(a,22,)
>>> b
(11, 22)

As you can see from this, a comma is needed to convert to a tuple type only when there is only one element in the b-tuple.

3. A good use of commas in the output statement print.

Example.

>>> for i in range(0,5):
...   print i
...
0
1
2
3
4
>>> for i in range(0,5):
...   print i,
...
0 1 2 3 4

Obviously, the print statement defaults to a linefeed, and with a comma, the linefeed becomes a space.

I hope that what I have described in this article will help you in your Python programming.