Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Basic Syntax

Python3 Basic Syntax

Encoding

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

You can of course specify a different encoding for the source file:


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

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


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 in identifiers, so Chinese characters can be used as variable names; non-ASCII identifiers are permitted.

姓名 = "张三"  # 合法
π = 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 and cannot be used 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']
>>> 
Category The keyword Description
Logical values True Boolean true value
False Boolean false value
None Represents an empty or absent value
Logical operations and Logical AND operation
or Logical OR operation
not Logical NOT operation
Conditional control if Conditional statement
elif Else if (abbreviation of else if)
else Else branch
Loop control for Iteration loop
while Conditional loop
break Break out of loop
continue Skip the rest of the current loop and move to the next iteration
Exception handling try Try to execute a block of code
except Catching an Exception
finally A block of code that executes whether or not an exception occurs
raise Throwing an Exception
Function definition def Defining a function
return Return a value from a function
lambda Create an anonymous function
Classes and objects class Define a class
del Delete an object reference
Module import import Import the module
from Import specific parts from a module
as Create an alias for an imported module or object
Scope global Declare a global variable
nonlocal Declare a nonlocal variable (for nested functions)
Asynchronous programming async Declare an asynchronous function
await Wait for an asynchronous operation to complete
Others assert Assertion, used to test whether a condition is true
in Check membership
is Check object identity (whether it is the same object)
pass Empty statement used as a placeholder
with Context manager for resource management
yield Return a value from a generator function

For more Python reserved keywords, see:https://www.runoob.com/python3/python3-keyword.html。


Notes

Single-line comments in Python start with # , as shown below:

Example (Python 3.0+)

#!/usr/bin/python3

The first comment

print

(

"

Hello, Python!

"

)

The second comment

The output of the code above is:


Hello, Python!

Multi-line comments can use multiple # signs, as well as ''' and """:

Example (Python 3.0+)

#!/usr/bin/python3

The first comment

The second comment

'''

Third comment Fourth comment

'''

"""

Fifth comment Sixth comment

"""

print

(

"

Hello, Python!

"

)

The output of the code above is:


Hello, Python!

Lines and indentation

Python's most distinctive feature is using indentation to represent code blocks instead of braces {} .

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

Example (Python 3.0+)

if

True

:

print

(

"

True

"

)

else

:

print

(

"

False

"

)

The following code has an inconsistent number of indentation spaces on the last line, which causes a runtime error:

Example

if

True

:

   

print

(

"Answer"

)

   

print

(

"True"

)

else

:

   

print

(

"Answer"

)

 

print

(

"False"

)

   

Inconsistent indentation causes a runtime error

The program above, due to inconsistent indentation, produces an error similar to the following when executed:


 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 split it across multiple lines, 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

)

The output is 6

For multi-line statements inside [], {}, or (), no backslash is needed, for example:


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

Number types

Python has four numeric types: integer, boolean, float, and complex.


Strings


word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""

Example (Python 3.0+)

#!/usr/bin/python3

str

=

'

123456789

'

print

(

str

)

Output the string

print

(

str

[

0

:-

1

]

)

Output all characters from the first to the second-to-last

print

(

str

[

0

]

)

Output the first character of the string

print

(

str

[

2

:

5

]

)

Output characters from the third up to but not including the sixth

print

(

str

[

2

:

]

)

Output all characters starting from the third

print

(

str

[

1

:

5

:

2

]

)

Output every other character from the second to the fifth (step 2)

print

(

str

2

)

Output the string twice

print

(

str

'

Hello

'

)

Concatenating Strings

print

(

'


'

)

print

(

'

hello

\n

runoob

'

)

Use a backslash followed by n to escape special characters

print

(

r

'

hello

\n

runoob

'

)

Prefixing a string with r makes it a raw string, so no escaping occurs

Here r stands for raw, i.e. a raw string, which escapes backslashes automatically, for example:

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

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

The example above produces the following output:


123456789
12345678
1
345
3456789
24
123456789123456789
123456789你好
------------------------------
hello
runoob
hello\nrunoob

Blank lines

Blank lines separate functions or methods of a class, marking the start of a new section of code. A single blank line also separates the class and function entry to highlight the start of the function entry.

Blank lines differ from indentation: they are not part of Python's syntax. Omitting them will not cause the interpreter to fail. However, blank lines serve to separate two sections of code with different functions or meanings, making later maintenance or refactoring easier.

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


Waiting for user input

Running the program below will wait for user input after the Enter key is pressed:

Example (Python 3.0+)

#!/usr/bin/python3

input

(

"

\n

\n

Press the enter key to exit.

"

)

In the code above, \n\n outputs two new blank lines before the result. Once the user presses the enter key, the program exits.


Multiple statements on one line

Python can place multiple statements on the same line, separated by semicolons ; , as shown in this simple example:

Example (Python 3.0+)

#!/usr/bin/python3

import

sys

;

x

=

'

runoob

'

;

sys

.

stdout

.

write

(

x

'

\n

'

)

Running the code above as a script produces:


runoob

Running it in the interactive shell produces:


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

Here 7 is the number of characters,runoob has 6 characters,\n represents one character, adding up to 7 characters.

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

Multiple statements form a code group

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

For compound statements such as if, while, def, and class, the first line starts with a keyword and ends with a colon ( : ); one or more following lines form the code group.

We call the header line together with the following code group a clause.

The following example:


if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

print output

print Output ends with a newline by default; to avoid the newline, add end="" at the end of the variable:

Example (Python 3.0+)

#!/usr/bin/python3

x

=

"

a

"

y

=

"

b

"

Output with a newline

print

(

x

)

print

(

y

)

print

(

'


'

)

Output without a newline

print

(

x

,

end

=

"

"

)

print

(

y

,

end

=

"

"

)

print

(

)

The example above produces:


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

For more information, refer to:print without a newline in Python2 and Python3


import and from...import

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

To import the whole module (somemodule), use: import somemodule

To import a function from a module, use: from somemodule import somefunction

To import several functions from a module, use: from somemodule import firstfunc, secondfunc, thirdfunc

To import all functions from a module, use: from somemodule import *

Import the sys module

import

sys

print

(

'

================Python import mode==========================

'

)

print

(

'

The command-line arguments are:

'

)

for

i

in

sys

.

argv

:

print

(

i

)

print

(

'

\n

The python path is

'

,

sys

.

path

)

Import the argv and path members of the sys module

from

sys

import

argv

,

path

Import specific members

print

(

'

================python from import===================================

'

)

print

(

'

path:

'

,

path

)

Since the path member has already been imported, there is no need to write sys.path when referencing it here

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


Command-Line Arguments

Many programs can perform operations to view basic information; Python can use the -h parameter to view help 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 running Python in script form, we can receive arguments entered on the command line; see Python 3 command-line arguments。