Coding
By default, Python 3 source files are encoded in UTF-8 , and all strings are Unicode strings. Of course you can also specify a different encoding for the source file:
#-*-coding:cp-1252-*-
Identifier
- The first character must be a letter in the alphabet or an underscore ' _ '.
- The other parts of the identifier are composed of letters, numbers, and underscores.
- Identifiers are case sensitive.
In Python 3, non--ascii identifiers are allowed as well.
Python reserved word
Reserved words are keywords, and we cannot use them as any identifier names. Python's standard library provides a keyword module that can output all the keywords for the current version:
>>> ImportKeyword>>>Keyword.Kwlist[' 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 ']
Comments
The single-line comment in Python begins with # , with the following example:
#!/usr/bin/python3# first comment print("Hello, python!" )# A second comment
Execute the above code and the output is:
Hello,Python!
Multiline comments can be in multiple # numbers, plus " and " ":
#!/usr/bin/python3 # The first comment # The second note, "The third note," "" "," "," "" "," "The sixth Note," " print(" Hello, python! " )
Execute the above code and the output is:
Hello,Python!
Line and indent
Python's most distinctive feature is the use of indentation to represent blocks of code, without the need to use curly braces {}.
The number of spaces to indent is variable, but the statement of the same code block must contain the same number of indentation spaces. Examples are as follows:
IfTrue: print("True")else: print("False")
The following code does not match the number of spaces in the last line of the statement, resulting in a run error:
if true : print ( "Answer" ) print ( "True" ) else: print ( "Answer" print ( " False ") # indentation inconsistent, resulting in a run error
The above program is not consistent due to indentation, after execution will appear similar to the following error:
File"test.py",6print("False")# indentation inconsistent, resulting in a run error ^Indentationerror :not match no outer indentation level
Multi-line statements
Python is usually a line to complete a statement, but if the statement is long, we can use a backslash (\) to implement a multiline statement, for example:
=+ + item_three
In [], {}, or () a multiline statement, you do not need to use a backslash (\), for example:
=[' Item_one ',' Item_two ',' Item_three ',' Item_four ',' item_ Five ']
Data type
There are four types of Python: integers, long integers, floating-point numbers, and complex numbers.
- int (integer), such as 1
- Long (Long Integer), a larger integer than
- float (floating point), such as 1.23, 3E-2
- Complex (plural), such as 1 + 2j, 1.1 + 2.2j
String
- The single and double quotation marks in Python are used exactly the same.
- Use the quotation marks ("' or" ") to specify a multiline string.
- Escape character ' \ '
- Natural string, by adding R or R before the string. such as R "This was a line with \ n \" will be displayed, not newline.
- Python allows processing of Unicode strings, prefixed with u or u, such as u "This is a Unicode string".
- The string is immutable.
- The literal cascading string, such as "This" and "is" and "string", is automatically converted to this is string.
=' string '= 'This is a sentence. "=" "This is a paragraph that can consist of multiple lines " ""
Blank Line
A blank line separates between functions or methods of a class, representing the beginning of a new piece of code. The class and function entries are also separated by a line of blank lines to highlight the beginning of the function entry.
Blank lines are different from code indentation, and empty lines are not part of the Python syntax. When you write without inserting a blank line, the Python interpreter runs without errors. However, the purpose of a blank line is to separate the code of two different functions or meanings, which facilitates the maintenance or refactoring of future code.
Remember: blank lines are also part of your program code.
Wait for user input
Executing the following program will wait for user input after pressing ENTER:
#!/usr/bin/python3input("\ n \ nthe exit after pressing the ENTER key.") ")
In the above code, "\ n" will output two new blank lines before the result output. Once the user presses the ENTER key, the program exits.
Show multiple statements on the same line
Python can use multiple statements in the same row, with semicolons (;) split between statements, and here's a simple example:
#!/usr/bin/python3import sys; =' Runoob '; sys. StdOut. Write(+' \ n ')
Execute the above code and the output is:
Runoob7
Multiple statements form a code group
Indenting the same set of statements constitutes a block of code, which we call the code group.
Compound statements such as if, while, Def, and class, the first line begins with a keyword, ends with a colon (:), and one or more lines of code after that line form the code group.
We refer to the first line and the following code group as a clause (clause).
The following example:
If: Suiteelif:else: Suite
Print output
The print default output is newline, and if you want to implement no newline, add end= ""to the end of the variable:
#!/usr/bin/python3X=AY="B"# line break outputPrint(X)print ( y ) print ( '---------' < Span class= "com" ># does not wrap output print ( X, end= ") print ( y , end= "" print ()
The result of the above instance execution is:
AB---------a b
Import and From...import
Import the appropriate modules in Python using Import or from...import.
Import the entire module (somemodule) in the format: import somemodule
Import a function from a module in the format: from somemodule import somefunction
Import multiple functions from a module in the format: from somemodule import Firstfunc, Secondfunc, Thirdfunc
Import all functions in a module in the format: from somemodule import *
Importing the SYS moduleImport Sys Print(‘================python Import mode==========================‘);Print (‘The command line arguments are:‘) for i in sys argv: print (i) print ( ' \n python path is ' ,sys. Path Importing the Argv,path member of the SYS moduleFrom Sys import argv< Span class= "Hl-code" >,path # import specific members Span class= "Hl-code" > print ( ' ================python from Import=================================== print ( Span class= "hl-quotes" > ' path: ,path) # because the path member has already been imported, So you don't need to add Sys.path Command-line arguments
Many programs can perform some operations to see some basic information, and Python can use the-H parameter to view the Help information for each parameter:
$ python-Husage:Python[Option] ... [-C-CMD| -M MoD|File| -] [Arg] ...Options andArguments(andcorresponding environment variables):-C-CMD:Program passedInch As String (Terminates option list)-D:Debug outputFrom parser (also pythondebug= x) -e : Ignore environment variables (such as Pythonpath) - h : printthis help message and Exit[ Etc. /span>
Python basic syntax