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-*-
The above definitions allow the use of character encodings in the Windows-1252 character set in the source file, corresponding to the languages Bulgarian, Barros, Macedonian, Russian, and Serbian.
Identifier
- The first character must be a letter in the alphabet or an underscore _.
- The other parts of the identifier are made up of letters, numbers, and underscores.
- Identifiers are case sensitive.
In Python 3, non-ASCII identifiers are also allowed.
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','inch',' 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 # First comment # a second comment " " Third Note IV " " """ Fifth note Sixth Comment """ 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:
if True: 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:
ifTrue:Print("Answer") Print("True")Else: Print("Answer") Print("False")#inconsistent indentation, resulting in a run error
The above program is not consistent due to indentation, after execution will appear similar to the following error:
" test.py ", line 6 print ("False") # indentation is inconsistent, resulting in a run error ^ 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:
Total = Item_one + + item_three
In [], {}, or () a multiline statement, you do not need to use a backslash (\), for example:
Total = ['item_one'item_two'item_three ' , ' Item_four ' ' item_five ']
numeric (number) type
There are four types of numbers in Python: integers, booleans, floating-point numbers, and complex numbers.
- int (integer), such as 1, has only one integer-type int, represented as a long integer, and no long in Python2.
- BOOL (Boolean), such as True.
- float (floating point), such as 1.23, 3E-2
- Complex (plural), such as 1 + 2j, 1.1 + 2.2j
Strings (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 ' \ '
- Backslashes can be used to escape, using R to allow backslashes to escape. such as R "This was a line with \ n \" will be displayed, not newline.
- The literal cascading string, such as "This" and "is" and "string", is automatically converted to this is string.
- Strings can be concatenated with the + operator and repeated with the * operator.
- There are two ways to index a string in Python, starting from left to right and starting at 0 from right to left with-1.
- The string in Python cannot be changed.
- Python does not have a separate character type, and one character is a string of length 1.
- The syntax for intercepting a string is as follows: variable [head subscript: tail subscript]
' string ' " This is a sentence. "" " This is a paragraph that can consist of multiple lines " ""
Instance
#!/usr/bin/python3Str=' ruNoob'Print(str)#Output StringPrint(Str[0:-1])#outputs all characters from the first to the penultimatePrint(Str[0])#The first character of the output stringPrint(Str[2:5])#outputs the characters from the third start to the fifthPrint(str[2:])#output all characters from the beginning of the thirdPrint(STR * 2)#output String two timesPrint(str +'Hello')#Connection StringPrint('------------------------------')Print('Hello\nrunoob')#Escape special characters with backslash (\) +nPrint(r'Hello\nrunoob')#Add an R to the string, representing the original string, without escaping
The output is:
runoobrunoornoonoobrunoobrunoobrunoob Hello ------------------------------hellorunoobhello\nrunoob
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/python3 input ("\ 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/python3 Import ' Runoob ' ' \ n ')
Execute the above code and the output is:
Runoob
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 expression: suiteelif expression: 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="a"y="b"#line break OutputPrint(x)Print(y)Print('---------')#No line break outputPrint(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 module
Import SYS Print ('================python import mode=========================='); Print (' command-line arguments are:') for inch sys.argv: Print (i) Print ('\ n python path is ', Sys.path)
Importing the Argv,path member of the SYS module
from Import # import a specific member Print ('================python from import===================================') Print ('path:'# because the path member has already been imported, so there is no need to add sys.path when referencing here
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 | - and arguments ( and corresponding environment variables): in as String (terminates option list)-D from parser (also pythondebug=x)-E : Ignore Environment variables (such as PYTHONPATH)-h print and exit[etc.]
Python Basic Syntax