Python3 basic syntax (4), python3 basic syntax
1, encoding
By default, the Python 3 source code fileUTF-8Encoding. All strings are unicode strings. Of course, you can also specify different codes for the source code file:
1 # -*- coding: cp-1252 -*-
2, identifier
- The first character must be a letter or underscore '_' in the alphabet '_'.
- Other parts of an identifier are composed of letters, numbers, and underscores.
- The identifier is case sensitive.
- Reserved Words cannot be used.
- Identifier definition should be meaningful
In Python 3, non-ASCII identifiers are also allowed.
3. Reserved Words
Reserved Words are keywords. We cannot use them as any identifier names. The standard Python Library provides a keyword module that can output all the keywords of the current version:
1 >>> import keyword2 >>> keyword.kwlist3 ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
4. Comment
(1. in Python, a single line comment starts with #. The example is as follows:
1 #! /Usr/bin/python32 3 # first comment 4 print ("Hello, Python! ") # Second comment
Run the above Code and the output result is:
1 Hello, Python!
(2) multi-line comment, "commented content" Or '''commented content ''', for example:
1 print ("-----------------------") 2 name = "lhm" 3 name2 = name 4 print (name, name2) 5 name = "lbh" 6 print (name, name2) 7 print ("---------------------") 8 ''' 9 print ("3X4 =", 3*4) 10 x = 411 y = 312 z = x * y13 print ("X * Y =", z) 14''' 15 print (1*2*3) 16 17 "18 print (" Hello Python, I Love Tiananmen, Beijing! ") 19 print (" multi-line comment ") 20" 21 print ("-----------------------")
The output result is as follows:
1 -----------------------2 lhm lhm3 lbh lhm4 -----------------------5 3X4= 126 X*Y= 127 68 -----------------------
5. Lines and indentation
The most distinctive feature of python is that it uses indentation to represent code blocks without braces ({}).
The number of indented spaces is variable, but the statement of the same code block must contain the same number of indented spaces (it is recommended that the statement indent four space keys, but not one tab key ). Example:
1 if True:2 print ("True")3 else:4 print ("False")
The following code does not match the number of spaces in the last line of the statement, causing a running error:
1 if True: 2 print ("Answer") 3 print ("True") 4 else: 5 print ("Answer") 6 print ("False") # inconsistent indentation, will cause a running error
Because the indentation of the above program is inconsistent, an error similar to the following will occur after execution:
File "test. py", line 6 print ("False") # inconsistent indentation may cause a running error ^ IndentationError: unindent does not match any outer indentation level6. Multi-line statements
Python usually writes a statement in one line, but if the statement is long, we can use a backslash (\) to implement multiple statements. For example:
1 total = item_one + \2 item_two + \3 item_three
Multi-line statements in [], {}, or () do not need to use a backslash (\). For example:
1 total = ['item_one', 'item_two', 'item_three',2 'item_four', 'item_five']
7. Data Type
Please pay attention to the following articles.
8, string
- In python, single quotes and double quotes are identical.
- You can use three quotation marks (''' or ") to specify a multi-line string.
- Escape Character '\'
- Natural string, by adding r or R before the string. For example, if r "this is a line with \ n", \ n is displayed, not a line break.
- Python allows you to process unicode strings with the prefix u or U, such as u "this is an unicode string ".
- The string is unchangeable.
- Cascade strings literally. For example, "this" "is" "string" is automatically converted to this is string.
Example:
1 word = 'string' 2 sentence = "this is a sentence. "3 paragraph =" "This is a paragraph, 4 can be composed of multiple lines """
9. Empty rows
Functions or methods of classes are separated by blank lines, indicating the beginning of a new code. The class and function entry are also separated by a blank line to highlight the beginning of the function entry.
Unlike code indentation, empty lines are not part of Python syntax. No blank lines are inserted during writing, and the Python interpreter runs without errors. However, empty lines are used to separate two sections of code with different functions or meanings to facilitate code maintenance or reconstruction in the future.
Remember:Empty lines are part of the program code.
10. Output
Useprint()Add a string to the brackets to output the specified text to the screen. For example, output'hello, world', Use the code to implement the following:
1 >>> print('hello, world')
print()The function can also accept multiple strings, with a comma",Separated to form a string of output:
1 >>> print('The quick brown fox', 'jumps over', 'the lazy dog')2 The quick brown fox jumps over the lazy dog
print()Each string is printed in sequence, and a comma (,) is used to output a space. Therefore, the output string is combined as follows:
print()You can also print an integer or calculate the result:
1 >>> print(300)2 3003 >>> print(100 + 200)4 300
Therefore, we can100 + 200The results are printed more beautifully:
1 >>> print('100 + 200 =', 100 + 200)2 100 + 200 = 300
Note that100 + 200, The Python interpreter automatically calculates the result.300,,'100 + 200 ='It is a string, not a mathematical formula. Python regards it as a string. Please explain the printed result on your own.
Print by default, the output is a line feed. If you do not need to implement a line feed, you need to add end = "" at the end of the variable "":
1 #! /Usr/bin/python3 2 3 x = "a" 4 y = "B" 5 # wrap output 6 print (x) 7 print (y) 8 9 print ('---------') 10 # output 11 print (x, end = "") 12 print (y, end = ") 13 print () without wrapping ()
The execution result of the above instance is:
1 a2 b3 ---------4 a b
11. Enter
Now you can useprint()Output the desired result. However, what should I do if I want a user to input some characters from the computer? Python providesinput()Allows you to input strings and put them in a variable. For example, enter the User Name:
1 >>> name = input()2 Michael
When you entername = input()Press enter, and the Python interactive command line will be waiting for your input. In this case, you can enter any character and press enter to complete the input.
After the input is complete, no prompt is displayed, and the Python interactive command line returns>>>Status. So where did we get the entered content? The answer is to store itnameVariable. You can directly enternameView variable content:
1 >>> name2 'Michael'
12. Multiple statements are displayed in the same row.
Python can use multiple statements in the same line and use semicolons (;) to separate them. The following is a simple example:
#!/usr/bin/python3import sys; x = 'runoob'; sys.stdout.write(x + '\n')
Run the preceding code and enter the following result:
1 runoob
13. Multiple statements form a code group
A group of statements with the same indentation constitute a code block, which we call a code group.
For a composite statement such as if, while, def, and class, the first line starts with a keyword and ends with a colon (:). One or more lines of code after the row form a code group.
We call the first line and the subsequent code group a clause ).
Example:
1 if expression : 2 suite3 elif expression : 4 suite 5 else : 6 suite
14. import and from... import
Use import or from... import in python to import the corresponding module.
Import the entire module (somemodule) in the format of import somemodule
Import a function from a module in the format of from somemodule import somefunction
Import multiple functions from a module in the format of from somemodule import firstfunc, secondfunc, thirdfunc
Import all functions in a module in the format of: from somemodule import *
Import sys module
1 import sys2 print ('======================== Python import mode ====================== ============ '); 3 print ('COMMAND line parameter: ') 4 for I in sys. argv: 5 print (I) 6 print ('\ n python path is', sys. path)
Imports argv and path of the sys module.
1 from sys import argv, path # import a specific Member 2 3 print ('====================== python from import ========== =========================== ') 4 print ('path: ', path) # because the path member has been imported, sys is not required for reference here. path
15. Command Line Parameters
Many programs can execute some operations to view some basic information. Python can use the-h parameter to view the help information of each parameter:
$ python -husage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...Options and arguments (and corresponding environment variables):-c cmd : program passed in as string (terminates option list)-d : debug output from parser (also PYTHONDEBUG=x)-E : ignore environment variables (such as PYTHONPATH)-h : print this help message and exit[ etc. ]
When we use scripts to execute Python, we can receive parameters input by the command line. For details, refer to Python 3 command line parameters.