Python3.x Python3 Basic Syntax
\\n\\nEncoding
\\nBy default, Python3 source code files are encoded in UTF-8, and all strings are Unicode strings.
\\nOf course, you can also specify a different encoding for the source code file:
\\n# -*- coding: cp-1252 -*-\\nThe above definition allows the use of Windows-1252 character set encoding in the source file, suitable for languages such as Bulgarian, Belarusian, Macedonian, Russian, and Serbian.
\\n\\n\\n\\n
Identifiers
\\n- \\n
- The first character must be a letter (a-z, A-Z) or an underscore _. \\n
- The rest of the identifier consists of letters, digits, and underscores. \\n
- Identifiers are case-sensitive;
countandCountare different identifiers. \\n - There is no hard limit on identifier length, but it is recommended to keep them concise (generally no more than 20 characters). \\n
- Reserved keywords such as
if,for,class, etc., cannot be used as identifiers. \\n
Legal identifiers:
\\nage = 25 # Ordinary variable name, most common\\nuser_name = "Alice" # Use underscores to connect words, clear and readable\\n_total = 100 # Underscore prefix usually indicatesβInternally usedβorβPrivateβ\\nMAX_SIZE = 1024 # All caps usually indicatesβConstantsβοΌFixed value)\\ncalculate_area() # Function name, verb+Noun\\nStudentInfo # Class name, capitalized first letter (CamelCase)\\n__private_var # Double underscore prefix has special meaning\\n\\nIllegal identifiers:
\\n2nd_place = "silver" # Error: Starts with a number\\nuser-name = "Bob" # Error: Contains hyphens\\nclass = "Math" # Error: Using keywords\\n$price = 9.99 # Error: Contains special characters\\nfor = "loop" # Error: Using keywords\\n\\nPython 3 allows the use of Unicode characters as identifiers, so you can use Chinese as variable names; non-ASCII identifiers are also permitted.
\\nName = "Zhang San" # Legal\\nΟ = 3.14159 # Legal\\n\\nTest identifier legality:
\\n\\nExample
\\ndef is_valid_identifier(name):\\n try:\\n exec(f"{name} = None")\\n return True\\n except:\\n return False\\n\\nprint(is_valid_identifier("2var")) # False\\nprint(is_valid_identifier("var2")) # True\\n\\n\\n\\n
Python Reserved Keywords
\\nReserved words, i.e., keywords, cannot be used as any identifier name. Python's standard library provides a keyword module that can output all keywords for the current version:
>>> import keyword\\n>>> keyword.kwlist\\n['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']\\n>>> \\n\\n| Category | \\nKeyword | \\nDescription | \\n
|---|---|---|
| Logical Values | \\nTrue | \\nBoolean true value | \\n
| \\n | False | \\nBoolean false value | \\n
| \\n | None | \\nRepresents null or no value | \\n
| Logical Operations | \\nand | \\nLogical AND operation | \\n
| \\n | or | \\nLogical OR operation | \\n
| \\n | not | \\nLogical NOT operation | \\n
| Conditional Control | \\nif | \\nConditional judgment statement | \\n
| \\n | elif | \\nElse if (abbreviation for else if) | \\n
| \\n | else | \\nElse branch | \\n
| Loop Control | \\nfor | \\nIteration loop | \\n
| \\n | while | \\nConditional loop | \\n
| \\n | break | \\nExit the loop | \\n
| \\n | continue | \\nSkip the remaining part of the current loop and enter the next iteration | \\n
| Exception Handling | \\ntry | \\nTry to execute a code block | \\n
| \\n | except | \\nCatch exceptions | \\n
| \\n | finally | \\nCode block that executes whether an exception occurs or not | \\n
| \\n | raise | \\nRaise an exception | \\n
| Function Definition | \\ndef | \\nDefine a function | \\n
| \\n | return | \\nReturn a value from a function | \\n
| \\n | lambda | \\nCreate an anonymous function | \\n
| Classes and Objects | \\nclass | \\nDefine a class | \\n
| \\n | del | \\nDelete an object reference | \\n
| Module Import | \\nimport | \\nImport a module | \\n
| \\n | from | \\nImport specific parts from a module | \\n
| \\n | as | \\nCreate an alias for an imported module or object | \\n
| Scope | \\nglobal | \\nDeclare a global variable | \\n
| \\n | nonlocal | \\nDeclare a non-local variable (used in nested functions) | \\n
| Asynchronous Programming | \\nasync | \\nDeclare an asynchronous function | \\n
| \\n | await | \\nWait for an asynchronous operation to complete | \\n
| Others | \\nassert | \\nAssertion, used to test if a condition is true | \\n
| \\n | in | \\nCheck membership | \\n
| \\n | is | \\nCheck object identity (whether it is the same object) | \\n
| \\n | pass | \\nEmpty statement, used as a placeholder | \\n
| \\n | with | \\nContext manager, used for resource management | \\n
| \\n | yield | \\nReturn a value from a generator function | \\n
\\n\\n\\nFor more Python reserved keywords reference: .
\\n
\\n\\n
Comments
\\nIn Python, single-line comments start with #, as shown in the following example:
\\n\\nExample (Python 3.0+)
\\nprint("Hello, Python!")\\nExecute the above code, the output is:
\\nHello, Python!\\n\\nMulti-line comments can use multiple # symbols, as well as triple quotes ''' and """:
Example (Python 3.0+)
\\n'''\\nThird comment\\nFourth comment\\n'''\\n"""\\nFifth comment\\nSixth comment\\n"""\\nprint("Hello, Python!")\\nExecute the above code, the output is:
\\nHello, Python!\\n\\n\\n\\n
Lines and Indentation
\\nThe most distinctive feature of Python is using indentation to denote code blocks, without the need for curly braces {}.
The number of spaces for indentation is variable, but statements within the same code block must contain the same number of indentation spaces. Example:
\\n\\nExample (Python 3.0+)
\\nif True:\\n print("True")\\nelse:\\n print("False")\\n\\nThe following code has inconsistent indentation in the last line, which will cause a runtime error:
\\n\\nExample
\\nif True:\\n print("Answer")\\n print("True")\\nelse:\\n print("Answer")\\n print("False") # Inconsistent indentation will cause runtime errors\\n\\nDue to inconsistent indentation, the above program will produce an error similar to the following when executed:
\\n File "test.py", line 6\\n print ("False") # Inconsistent indentation will cause runtime errors\\n ^\\nIndentationError: unindent does not match any outer indentation level\\n\\n\\n\\n
Multi-Line Statements
\\nPython usually completes one statement per line, but if a statement is very long, we can use a backslash to implement multi-line statements, for example:
total = item_one + \\n item_two + \\n item_three\\n\\nExample
\\nitem_one = 1\\nitem_two = 2\\nitem_three = 3\\ntotal = item_one + \\n item_two + \\n item_three\\nprint(total) # Output is 6\\n\\nMulti-line statements within [], {}, or () do not require the use of backslash , for example:
total = ['item_one', 'item_two', 'item_three', 'item_four', 'item_five']\\n\\n\\n\\n
Number Types
\\nIn Python, numbers have four types: integers, booleans, floating-point numbers, and complex numbers.
\\n- \\n
- int (integer), such as 1, there is only one integer type int, represented as long integer, without Long as in Python 2. \\n
- bool (boolean), such as True. \\n
- float (floating-point number), such as 1.23, 3E-2. \\n
- complex (complex number) - complex numbers consist of a real part and an imaginary part, in the form a + bj, where a is the real part, b is the imaginary part, and j represents the imaginary unit. For example, 1 + 2j, 1.1 + 2.2j. \\n
\\n\\n
Strings
\\n- \\n
- In Python, single quotes
'and double quotes"are used in exactly the same way. \\n - Triple quotes (
'''or""") can specify a multi-line string. \\n - Escape character
.\\n - Backslash can be used for escaping; using
rcan make backslash not escape. For example,r"this is a line with n"will displayn, not a newline. \\n - Literal string concatenation, such as
"this " "is " "string"will be automatically converted tothis is string. \\n - Strings can be concatenated together using the
+operator and repeated with the*operator. \\n - In Python, strings have two indexing methods: from left to right starting at 0, and from right to left starting at -1. \\n
- Strings in Python are immutable. \\n
- Python does not have a separate character type; a character is a string of length 1. \\n
- String slicing
str[start:end], wherestart(inclusive) is the starting index of the slice, andend(exclusive) is the ending index of the slice. \\n - String slicing can add a step parameter, with the following syntax:
str[start:end:step]. \\n
word = 'Strings'\\nsentence = "This is a sentence."\\nparagraph = """This is a paragraph,\\nCan consist of multiple lines"""\\n\\nExample (Python 3.0+)
\\nstr='123456789'\\nprint(str)\\nprint(str[0:-1])\\nprint(str)\\nprint(str[2:5])\\nprint(str[2:])\\nprint(str[1:5:2])\\nprint(str * 2)\\nprint(str + 'Hello')\\nprint('------------------------------')\\nprint('hellon ')\\nprint(r'hellon ')\\n\\nHere, r refers to raw, i.e., raw string, which will automatically escape backslashes. For example:
>>> print('n') # Output a blank line\\n\\n>>> print(r'n') # Output n\\nn\\n>>>\\n\\nThe output of the above example:
\\n123456789\\n12345678\\n1\\n345\\n3456789\\n24\\n123456789123456789\\n123456789Hello\\n------------------------------\\nhello\\n \\nhellontutorial\\n\\n\\n\\n
Blank Lines
\\nFunctions or class methods are separated by blank lines to indicate the beginning of a new code block. Classes and function entries are also separated by a blank line to highlight the start of the function entry.
\\nBlank lines are different from code indentation; blank lines are not part of Python syntax. If blank lines are not inserted when writing, the Python interpreter will still run without errors. However, the purpose of blank lines is to separate two pieces of code with different functions or meanings, facilitating future code maintenance or refactoring.
\\nRemember: blank lines are also part of the program code.
\\n\\n\\n\\n
Waiting for User Input
\\nExecuting the following program will wait for user input after pressing the Enter key:
\\n\\nExample (Python 3.0+)
\\ninput("nn Press enter key to exit.")\\nIn the above code, nn will output two new blank lines before the result output. Once the user presses the Enter key, the program will exit.
\\n\\n
Display Multiple Statements on the Same Line
\\nPython can use multiple statements on the same line, separated by semicolons ;. Here is a simple example:
Example (Python 3.0+)
\\nimport sys; x = ''; sys.stdout.write(x + 'n')\\nExecuting the above code using a script, the output is:
\\n\\n\\nExecuting in an interactive command line, the output is:
\\n>>> import sys; x = ''; sys.stdout.write(x + 'n')\\n\\n7\\nHere, 7 represents the character count; has 6 characters, and n represents one character, totaling 7 characters.
>>> import sys\\n>>> sys.stdout.write(" hi ") # hi One space before and after each\\n hi\\n4\\n\\n\\n\\n
Multiple Statements Form a Code Group
\\nA group of statements with the same indentation forms a code block, which we call a code group.
\\nCompound statements like if, while, def, and class start with a keyword on the first line and end with a colon (:). One or more lines of code after that line form the code group.
We refer to the first line and the subsequent code group as a clause.
\\n\\nAs shown in the following example:
\\nif expression :\\n suite\\nelif expression :\\n suite\\nelse :\\n suite\\n\\n\\n\\n
print Output
\\nThe default output of print is with a newline; to avoid newline, add end="" at the end of the variable:
Example (Python 3.0+)
\\nx="a"\\ny="b"\\nprint(x)\\nprint(y)\\nprint('---------')\\nprint(x, end="")\\nprint(y, end="")\\nprint()\\nThe execution result of the above example is:
\\na\\nb\\n---------\\na b\\n\\n\\n\\n\\nFor more content, refer to: Python2 and Python3 print without newline
\\n
\\n\\n
import and from...import
\\nIn Python, use import or from...import to import the corresponding modules.
To import the entire module (somemodule), the format is: import somemodule
To import a specific function from a module, the format is: from somemodule import somefunction
To import multiple functions from a module, the format is: from somemodule import firstfunc, secondfunc, thirdfunc
To import all functions from a module, the format is: from somemodule import *
# Import sys module\\nimport sys\\n\\nprint('================Python import mode==========================')\\nprint('Command line arguments are:')\\nfor i in sys.argv:\\n print(i)\\nprint('n python Path is',sys.path)\\n\\n# Import sys module's argv,path Member\\nfrom sys import argv,path\\n\\nprint('================python from import===================================')\\nprint('path:',path)\\n\\n\\n\\n\\nFor more content, refer to: Main differences between Python import and from β¦ import
\\n
\\n\\n
Command Line Arguments
\\nMany programs can perform operations to view some basic information; Python can use the -h parameter to view help information for various parameters:
$ python -h\\nusage: python ... [-c cmd | -m mod | file | -] ...\\nOptions and arguments (and corresponding environment variables):\\n-c cmd : program passed in as string (terminates option list)\\n-d : debug output from parser (also PYTHONDEBUG=x)\\n-E : ignore environment variables (such as PYTHONPATH)\\n-h : print this help message and exit\\n[ etc. ]\\n\\nWhen using scripts to execute Python, we can receive command line input parameters; for specific usage, refer to Python 3 Command Line Arguments.
\\n\\n
YouTip