Strange corners of python3 (1): basic syntax

1.Print output

Python2 replaces spaces, Python3 uses end="". The default output of print is newline. If you want to achieve no newline, you need to add end="" at the end of the variable:

#!/usr/bin/python3

x="a"
y="b"
# 换行输出
print( x )
print( y )

print('---------')
# 不换行输出
print( x, end=" " )
print( y, end=" " )
print()

The execution result of the above example is:

a
b
---------
a b

2.py file start comment

The first line of comments can be omitted under Windows:

#!/usr/bin/python3

The first line of comment marks the path to python, telling the operating system to call the python interpreter under /usr/bin when executing the script.
In addition, there are the following forms (recommended writing):

#!/usr/bin/env python3

This usage first looks for the python installation path in the env (environment variable) setting, and then calls the interpreter program under the corresponding path to complete the operation.
Explain the first line of code #!/usr/bin/python3
This sentence only works under linux or unix systems. Under windows, no matter what you add to the code, you cannot directly run a script with a file name suffix of .py. Because the file name under Windows plays a decisive role in how the file is opened.

3. Python3 command line parameters

Python provides the getopt module to get command line arguments.
$ python test.py arg1 arg2 arg3
Python can also use sys.argv of sys to get command line arguments:
sys.argv is a list of command line arguments.
len(sys.argv) is the number of command line arguments.
Note: sys.argv[0] represents the script name.

example

The code of the test.py file is as follows:

#!/usr/bin/python3

import sys

print ('参数个数为:', len(sys.argv), '个参数。')
print ('参数列表:', str(sys.argv))

Execute the above code, the output result is:

$ python3 test.py arg1 arg2 arg3
参数个数为: 4 个参数。
参数列表: ['test.py', 'arg1', 'arg2', 'arg3']

4.dict(d) creates a dictionary. d must be a sequence (key, value) tuple

d2 = ((1,2),(4,5),(6,8))
#print(dict(d))  TypeError: cannot convert dictionary update sequence element #0 to a sequence
print(dict(d2)) #{1: 2, 4: 5, 6: 8}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324651025&siteId=291194637