Python Introductory Tutorial | Python Basic Grammar

identifier

  • The first character must be a letter of the alphabet or an underscore _.
  • The rest of the identifier consists of letters, numbers, and underscores.
  • Identifiers are case sensitive.

In Python 3, Chinese characters can be used as variable names, and non-ASCII identifiers are also allowed. By default, Python 3 source files are encoded in UTF-8 and all strings are unicode strings.

reserved words (keywords)

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 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']

input input and print output

input input

input waits for user input
Execute the following program and wait for user input after pressing the Enter key:

input("\n\n按下 enter 键后退出。")

In the above code, \n\n will output two new blank lines before the output of the result. Once the user presses the enter key, the program will exit.

print output

The default output of print is newline. If you want to achieve no newline, you need to add end="" at the end of the variable:

print('Hello world')
print('---------')
# 不换行输出
print( 'Hello ', end=" " )
print('python')

The execution result of the above example is:

Hello world
---------
Hello python

note

single line comment

Single-line comments in Python start with #, examples are as follows:

# 代码注释打印Hello World
print ("Hello World!") # 行尾注释。。。

Execute the above code, the output is:

Hello World!

multiline comment

Multi-line comments can use ' ' ' and " " ":


'''
注释内容1
注释内容2
'''
 
"""
注释内容1
注释内容2
"""
print ("Hello, World!")

Execute the above code, the output is:

Hello, Python!

Lines and indentation

The most distinctive feature of python is to use indentation to represent code blocks, without using curly braces {}.

The number of indented spaces is variable, but statements in the same code block must contain the same number of indented spaces. Examples are as follows:

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

The number of spaces in the indentation of the last line of the following code is inconsistent, which will cause a running error:

if True:
    print ("Answer")
    print ("True")
else:
    print ("Answer")
  print ("False")    # 缩进不一致,会导致运行错误

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

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

multi-line statement

Python usually writes a statement in one line, but if the statement is very long, we can use the backslash \ to implement a multi-line statement, for example:

total = item_one + \
        item_two + \
        item_three

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

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

blank line

Functions or class methods are separated by a blank line, indicating the beginning of a new code. The class and function entries are also separated by a blank line to highlight the beginning of the function entry.

Blank lines are not the same as code indentation, and blank lines are not part of Python syntax. No blank lines are inserted when writing, and the Python interpreter will run without errors. But the function of the blank line is to separate two pieces of code with different functions or meanings, which is convenient for future code maintenance or refactoring.

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

Display multiple statements on the same line

Python can use multiple statements on the same line, separated by semicolon; The following is a simple example:

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

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 like if, while, def, and class, the first line starts with a keyword and ends with a colon (:), and one or more lines of code after this line form a code group.

We refer to the first line and the following group of codes as a clause (clause).

Examples are as follows:

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

  • expression conditional expression
  • suite python code blocks
  • elif is equivalent to else if

import and from...import

Use import or from...import in python to 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 in a module, the format is: from somemodule import *

import sys
print('================Python import mode==========================')
print ('命令行参数为:')
for i in sys.argv:
    print (i)
print ('\n python 路径为',sys.path)
from sys import argv,path  #  导入特定的成员
 
print('================python from import===================================')
print('path:',path) # 因为已经导入path成员,所以此处引用时不需要加sys.path

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/132401287