Python3 Basic Syntax

Encoding

By default, Python3 source files use theUTF-8encoding, and all strings are unicode strings.

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

# -*- coding: cp-1252 -*-

The above definition allows the source file to use characters from the Windows-1252 character set, suitable for Bulgarian, Belarusian, Macedonian, Russian, and Serbian.


Identifiers

  • The first character must be a letter (a-z, A-Z) or an underscore_ 。
  • The other parts of an identifier consist of letters, digits, and underscores.
  • Identifiers are case-sensitive; count and Count are different identifiers.
  • Identifiers have no hard length limit, but it is recommended to keep them concise (generally no more than 20 characters).
  • Reserved keywords are prohibited; for example, if, for, and class cannot be used as identifiers.

Valid identifiers:

age = 25                # 普通变量名,最常见
user_name = "Alice"     # 用下划线连接单词,清晰易读
_total = 100            # 下划线开头通常表示“内部使用”或“私有”
MAX_SIZE = 1024         # 全大写通常表示“常量”(固定不变的值)
calculate_area()        # 函数名,动词+名词
StudentInfo             # 类名,首字母大写(驼峰命名法)
__private_var           # 双下划线开头,有特殊含义

Invalid identifiers:

2nd_place = "silver"    # 错误:以数字开头
user-name = "Bob"       # 错误:包含连字符
class = "Math"          # 错误:使用关键字
$price = 9.99          # 错误:包含特殊字符
for = "loop"           # 错误:使用关键字

Python 3 allows Unicode characters as identifiers, so Chinese can be used for variable names; non-ASCII identifiers are also allowed.

姓名 = "张三"  # 合法
π = 3.14159   # 合法

Test whether an identifier is valid:

Example

def is_valid_identifier(name):
    try:
        exec(f"{name} = None")
        return True
    except:
        return False

print(is_valid_identifier("2var"))  # False
print(is_valid_identifier("var2"))  # True

Python Reserved Keywords

Reserved words are keywords; we cannot use them as any identifier name. Python's standard library provides a keyword module that can output all keywords of the current version:

>>> import keyword
>>> keyword.kwlist
['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']
>>> 
CategoryKeywordDescription
Boolean valuesTrueBoolean true value
FalseBoolean false value
NoneRepresents empty or no value
Logical operationsandLogical AND operation
orLogical OR operation
notLogical NOT operation
Conditional controlifConditional statement
elifOtherwise if (abbreviation of else if)
elseOtherwise branch
Loop controlforIteration loop
whileConditional loop
breakBreak out of the loop
continueSkip the rest of the current loop and go to the next iteration
Exception handlingtryTry to execute a code block
exceptCatch an exception
finallyCode block that executes whether or not an exception occurs
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 a specific part from a module
asCreate an alias for an imported module or object
ScopeglobalDeclare a global variable
nonlocalDeclare a nonlocal variable (used in nested functions)
Asynchronous programmingasyncDeclare an async function
awaitWait for an async operation to complete
OthersassertAssert, used to test whether 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

More Python reserved keyword reference:https://www.example.com/python3/python3-keyword.html。


Comments

In Python, single-line comments start with#and are written as follows:

Example (Python 3.0+)

#!/usr/bin/python3 # First comment print ("Hello, Python!") # Second comment

Executing the above code, the output is:

Hello, Python!

Multi-line comments can use multiple#hash signs, and also'''and""":

Example (Python 3.0+)

#!/usr/bin/python3 # First comment # Second comment '''Third comment Fourth comment''' """Fifth comment Sixth comment""" print ("Hello, Python!")

Executing the above code, the output is:

Hello, Python!

Lines and Indentation

The most distinctive feature of Python is using indentation to represent code blocks; no curly braces are needed.{} 。

The number of spaces in indentation is variable, but statements in the same code block must contain the same number of indentation spaces. Example:

Example (Python 3.0+)

if True: print ("True") else: print ("False")

In the following code, the last line of statements has inconsistent indentation, which will cause a runtime error:

Example

if True:
    print ("Answer")
    print ("True")
else:
    print ("Answer")
  print ("False")    # Inconsistent indentation will cause a runtime error

Due to inconsistent indentation, the above program will produce an error similar to the following after execution:

 File "test.py", line 6
    print ("False")    # 缩进不一致,会导致运行错误
                                      ^
IndentationError: unindent does not match any outer indentation level

Multi-line Statements

Python usually writes 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 + \
        item_two + \
        item_three

Example

item_one = 1
item_two = 2
item_three = 3
total = item_one + \
        item_two + \
        item_three
print(total) # Output is 6

Multi-line statements inside [], {}, or () do not need a backslash\, for example:

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

Number Types

Python has four types of numbers: integers, booleans, floats, and complex numbers.

  • int(Integer), such as 1; there is only one integer type, int, represented as a long integer, without the Long type in Python 2.
  • bool(Boolean), such as True.
  • float(Float), such as 1.23, 3E-2
  • complex(Complex) - 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

String

  • In Python, single quotes'and double quotes"are used exactly the same.
  • Using triple quotes ('''or""") can specify a multi-line string.
  • Escape Character\。
  • Backslashes can be used for escaping; usingrcan prevent the backslash from escaping. For example,r"this is a line with \n"Then\nwill be displayed, not a line break.
  • Concatenate strings literally, such as"this " "is " "string"will be automatically converted tothis is string。
  • Strings can be concatenated using the+operator, and repeated using the*operator.
  • Strings in Python have two indexing methods: from left to right starting at0, and from right to left starting at-1.
  • Strings in Python cannot be changed.
  • Python has no separate character type; a character is just a string of length 1.
  • String Slicingstr[start:end], where start (inclusive) is the index where the slice begins, and end (exclusive) is the index where the slice ends.
  • String slicing can include a step parameter, step, with the following syntax:str[start:end:step]
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""

Example (Python 3.0+)

#!/usr/bin/python3 str='123456789' print(str) # Outputs the string print(str[0:-1]) # Outputs all characters from the first to the second to last print(str[0]) # Outputs the first character of the string print(str[2:5]) # Outputs characters from the third to the sixth (exclusive) print(str[2:]) # Outputs all characters starting from the third print(str[1:5:2]) # Output every other character from the second to the fifth (step size 2) print(str * 2) # Output the string twice print(str + 'Hello') # Concatenate strings print('------------------------------') print('hello\nexample') # Use backslash (\)+n to escape special characters print(r'hello\nexample') # Add an r before the string to indicate a raw string, so no escaping will occur

Here r stands for raw, i.e., raw string, which will automatically escape backslashes, for example:

>>> print('\n')       # 输出空行

>>> print(r'\n')      # 输出 \n
\n
>>>

The output of the above example is:

123456789
12345678
1
345
3456789
24
123456789123456789
123456789你好
------------------------------
hello
example
hello\nexample

Blank Lines

Use blank lines between functions or between class methods to indicate the start of a new block of code. Also use a blank line between the class and function entries to highlight the start of the function entry.

Blank lines are different from code indentation. Blank lines are not part of Python syntax. If you do not insert blank lines, 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, making future code maintenance or refactoring easier.

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


Waiting for User Input

After executing the following program and pressing the Enter key, it will wait for user input:

Example (Python 3.0+)

#!/usr/bin/python3 input("\n\nExit after pressing the Enter key.")

In the above code,\n\ntwo new blank lines will be output before the result is output. Once the user presses theenterkey, the program will exit.


Multiple Statements on the Same Line

Python can use multiple statements on the same line, with semicolons between statements;as separators. The following is a simple example:

Example (Python 3.0+)

#!/usr/bin/python3 import sys; x = 'example'; sys.stdout.write(x + '\n')

Using a script to execute the above code, the output is:

example

Using the interactive command line to execute, the output is:

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

Here 7 indicates the number of characters,examplethere are 6 characters,\nrepresenting one character, adding up to7characters.

>>> import sys
>>> sys.stdout.write(" hi ")    # hi 前后各有 1 个空格
 hi 4

Multiple Statements Form a Code Group

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

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 a code group.

We call the first line and the following code group a clause.

The following is an example:

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

print Output

printBy default, output is line-broken. To achieve no line break, you need to add at the end of the variableend="":

Example (Python 3.0+)

#!/usr/bin/python3 x="a" y="b" # Newline output print( x ) print( y ) print('---------') # Non-newline output print( x, end=" " ) print( y, end=" " ) print()

The execution result of the above example is:

a
b
---------
a b

For more information, see:Python2 and Python3 print without newline


import and from...import

In Python, useimportorfrom...importto import the corresponding module.

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

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

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

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

Import the sys module

import sys print('================Python import mode==========================') print ('Command line arguments are:') for i in sys.argv: print (i) print ('\npython path is',sys.path)

Import the argv, path members of the sys module

from sys import argv,path # Import specific members print('================python from import===================================') print('path:',path) # Because the path member has already been imported, sys.path is not needed when referencing here

For more information, refer to:The main difference between Python import and from … import


Command-line Arguments

Many programs can perform some operations to view basic information. Python can use the -h parameter to view help information for each parameter:

$ python -h
usage: 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 executing Python in script form, you can receive command line input parameters. For specific usage, refer toPython 3 Command Line Arguments。

Other Extensions