YouTip LogoYouTip

Python3 Basic Syntax

Python3 Basic Syntax \\n\\n

Python3.x Python3 Basic Syntax

\\n\\n

Encoding

\\n

By default, Python3 source code files are encoded in UTF-8, and all strings are Unicode strings.

\\n

Of course, you can also specify a different encoding for the source code file:

\\n
# -*- coding: cp-1252 -*-
\\n

The 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; count and Count are 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
\\n\\n

Legal identifiers:

\\n
age = 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\\n

Illegal identifiers:

\\n
2nd_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\\n

Python 3 allows the use of Unicode characters as identifiers, so you can use Chinese as variable names; non-ASCII identifiers are also permitted.

\\n
Name = "Zhang San" # Legal\\nΟ€ = 3.14159 # Legal
\\n\\n

Test identifier legality:

\\n\\n

Example

\\n
def 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

\\n

Reserved 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:

\\n
>>> 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\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n
CategoryKeywordDescription
Logical ValuesTrueBoolean true value
FalseBoolean false value
NoneRepresents null or no value
Logical OperationsandLogical AND operation
orLogical OR operation
notLogical NOT operation
Conditional ControlifConditional judgment statement
elifElse if (abbreviation for else if)
elseElse branch
Loop ControlforIteration loop
whileConditional loop
breakExit the loop
continueSkip the remaining part of the current loop and enter the next iteration
Exception HandlingtryTry to execute a code block
exceptCatch exceptions
finallyCode block that executes whether an exception occurs or not
raiseRaise an exception
Function DefinitiondefDefine a function
returnReturn a value from a function
lambdaCreate an anonymous function
Classes and ObjectsclassDefine a class
delDelete an object reference
Module ImportimportImport a module
fromImport specific parts from a module
asCreate an alias for an imported module or object
ScopeglobalDeclare a global variable
nonlocalDeclare a non-local variable (used in nested functions)
Asynchronous ProgrammingasyncDeclare an asynchronous function
awaitWait for an asynchronous operation to complete
OthersassertAssertion, used to test if a condition is true
inCheck membership
isCheck object identity (whether it is the same object)
passEmpty statement, used as a placeholder
withContext manager, used for resource management
yieldReturn a value from a generator function
\\n\\n
\\n

For more Python reserved keywords reference: .

\\n
\\n\\n
\\n\\n

Comments

\\n

In Python, single-line comments start with #, as shown in the following example:

\\n\\n

Example (Python 3.0+)

\\n
print("Hello, Python!")
\\n

Execute the above code, the output is:

\\n
Hello, Python!
\\n\\n

Multi-line comments can use multiple # symbols, as well as triple quotes ''' and """:

\\n\\n

Example (Python 3.0+)

\\n
'''\\nThird comment\\nFourth comment\\n'''\\n"""\\nFifth comment\\nSixth comment\\n"""\\nprint("Hello, Python!")
\\n

Execute the above code, the output is:

\\n
Hello, Python!
\\n\\n
\\n\\n

Lines and Indentation

\\n

The most distinctive feature of Python is using indentation to denote code blocks, without the need for curly braces {}.

\\n

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\\n

Example (Python 3.0+)

\\n
if True:\\n    print("True")\\nelse:\\n    print("False")
\\n\\n

The following code has inconsistent indentation in the last line, which will cause a runtime error:

\\n\\n

Example

\\n
if True:\\n    print("Answer")\\n    print("True")\\nelse:\\n    print("Answer")\\n    print("False")  # Inconsistent indentation will cause runtime errors
\\n\\n

Due 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

\\n

Python 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:

\\n
total = item_one + \\n        item_two + \\n        item_three
\\n\\n

Example

\\n
item_one = 1\\nitem_two = 2\\nitem_three = 3\\ntotal = item_one + \\n        item_two + \\n        item_three\\nprint(total)  # Output is 6
\\n\\n

Multi-line statements within [], {}, or () do not require the use of backslash , for example:

\\n
total = ['item_one', 'item_two', 'item_three', 'item_four', 'item_five']
\\n\\n
\\n\\n

Number Types

\\n

In 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
\\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 r can make backslash not escape. For example, r"this is a line with n" will display n, not a newline.
  • \\n
  • Literal string concatenation, such as "this " "is " "string" will be automatically converted to this 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], where start (inclusive) is the starting index of the slice, and end (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
\\n\\n
word = 'Strings'\\nsentence = "This is a sentence."\\nparagraph = """This is a paragraph,\\nCan consist of multiple lines"""
\\n\\n

Example (Python 3.0+)

\\n
str='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\\n

Here, r refers to raw, i.e., raw string, which will automatically escape backslashes. For example:

\\n
>>> print('n')  # Output a blank line\\n\\n>>> print(r'n')  # Output n\\nn\\n>>>
\\n\\n

The output of the above example:

\\n
123456789\\n12345678\\n1\\n345\\n3456789\\n24\\n123456789123456789\\n123456789Hello\\n------------------------------\\nhello\\n \\nhellontutorial
\\n\\n
\\n\\n

Blank Lines

\\n

Functions 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.

\\n

Blank 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.

\\n

Remember: blank lines are also part of the program code.

\\n\\n
\\n\\n

Waiting for User Input

\\n

Executing the following program will wait for user input after pressing the Enter key:

\\n\\n

Example (Python 3.0+)

\\n
input("nn Press enter key to exit.")
\\n

In 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
\\n\\n

Display Multiple Statements on the Same Line

\\n

Python can use multiple statements on the same line, separated by semicolons ;. Here is a simple example:

\\n\\n

Example (Python 3.0+)

\\n
import sys; x = ''; sys.stdout.write(x + 'n')
\\n

Executing the above code using a script, the output is:

\\n
\\n\\n

Executing in an interactive command line, the output is:

\\n
>>> import sys; x = ''; sys.stdout.write(x + 'n')\\n\\n7
\\n

Here, 7 represents the character count; has 6 characters, and n represents one character, totaling 7 characters.

\\n\\n
>>> 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

\\n

A group of statements with the same indentation forms a code block, which we call a code group.

\\n

Compound 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.

\\n

We refer to the first line and the subsequent code group as a clause.

\\n\\n

As shown in the following example:

\\n
if expression :\\n   suite\\nelif expression :\\n   suite\\nelse :\\n   suite
\\n\\n
\\n\\n

print Output

\\n

The default output of print is with a newline; to avoid newline, add end="" at the end of the variable:

\\n\\n

Example (Python 3.0+)

\\n
x="a"\\ny="b"\\nprint(x)\\nprint(y)\\nprint('---------')\\nprint(x, end="")\\nprint(y, end="")\\nprint()
\\n

The execution result of the above example is:

\\n
a\\nb\\n---------\\na b
\\n\\n
\\n

For more content, refer to: Python2 and Python3 print without newline

\\n
\\n\\n
\\n\\n

import and from...import

\\n

In Python, use import or from...import to import the corresponding modules.

\\n

To import the entire module (somemodule), the format is: import somemodule

\\n

To import a specific function from a module, the format is: from somemodule import somefunction

\\n

To import multiple functions from a module, the format is: from somemodule import firstfunc, secondfunc, thirdfunc

\\n

To import all functions from a module, the format is: from somemodule import *

\\n\\n
# 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

For more content, refer to: Main differences between Python import and from … import

\\n
\\n\\n
\\n\\n

Command Line Arguments

\\n

Many programs can perform operations to view some basic information; Python can use the -h parameter to view help information for various parameters:

\\n
$ 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\\n

When using scripts to execute Python, we can receive command line input parameters; for specific usage, refer to Python 3 Command Line Arguments.

\\n\\n
← Os ReadlinkOs Read β†’