1-2 python basic grammar

Python3 basic grammar

coding

By default, Python 3 source files to  UTF-8  encoding, all strings are unicode string. Of course, you can also specify a different encoding for the source file:

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

Above definition allows the use of Windows-1252 character set encoding in the source file, the corresponding language suitable for the Bulgarian, White Rose, Macedonian, Russian, Serbian.


Identifier

  • The first character must be an alphabet letter or an underscore _.
  • Other partial identifiers from the letters, numbers and underscores.
  • Identifiers are case sensitive.

In Python 3, non-ASCII identifiers are also allowed up.


python reserved words

That is a reserved word keywords, we can not use them as any identifier name. Python's standard library module provides a keyword, you can output the current version of all keywords:

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', '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']

Note

Single-line comments in Python  #  beginning examples are as follows:

实例(Python 3.0+)
#!/usr/bin/python3
 
# 第一个注释
print ("Hello, Python!") # 第二个注释

Execution code above, the output is:

Hello, Python!

Multi-line comments can be multiple  No, there  '' '  and  "" " :

实例(Python 3.0+)
#!/usr/bin/python3
 
# 第一个注释
# 第二个注释
 
'''
第三注释
第四注释
'''
 
"""
第五注释
第六注释
"""
print ("Hello, Python!")

Execution code above, the output is:

Hello, Python!

Line with the indentation

python most characteristic is the use of code blocks to represent indentation, without using braces {}.

Indent number of spaces is variable, but with a block of statements must contain the same number of spaces indented. Examples are as follows:

实例(Python 3.0+)
if True:
    print ("True")
else:
    print ("False")

The number of spaces to indent the following code number of the last line of the statement is inconsistent, it can result in a runtime error:

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

Due to the above procedure is inconsistent indentation, similar to the following error occurs after the execution:

File "test.py", Line 6 
    Print ( "False") # indentation inconsistencies can cause a runtime error 
                                      ^ 
IndentationError: the Unindent does not match the any Outer Indentation Level

Multi-line statement

Python is usually a one liner statement, but if the statement is very long, we can use a backslash (\) to implement multi-line statements, such as:

total = item_one + \
        item_two + \
        item_three

In [], {}, or () statement in a plurality of rows, without using a backslash (\), for example:

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

Number (Number) Type

python digital There are four types: integer, boolean, floating point and complex.

  • int  (integer), such as 1, only one integer type, int, long integer expressed without python2 of Long.
  • BOOL  (Boolean), such as True.
  • a float  (floating-point), as 1.23,3E-2
  • Complex  (complex), such as 1 + 2j, 1.1 + 2.2j

String (String)

  • python single and double quotation marks using the same.
  • Tris quotation marks ( '' 'or' '') can specify a multi-line string.
  • Escapes'\'
  • Can be used to escape the backslash, backslash escapes allow the use of r can not occur. . The r "this is a line with \ n" is \ n will be displayed, not wrap.
  • Literally cascading strings, such as "this" "is" "string" will be automatically converted to this is string.
  • Operator + strings can be connected together, with the * operator repeats.
  • Python strings two indexing methods, starting with 0 from left to right, right to left to begin -1.
  • The string can not be changed in Python.
  • Python is no separate character type is a character string of length 1.
  • Taken string syntax is as follows: Variable [the header: Tail index: step]
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""
实例(Python 3.0+)
#!/usr/bin/python3
 
str='Runoob'
 
print(str)                 # 输出字符串
print(str[0:-1])           # 输出第一个到倒数第二个的所有字符
print(str[0])              # 输出字符串第一个字符
print(str[2:5])            # 输出从第三个开始到第五个的字符
print(str[2:])             # 输出从第三个开始的后的所有字符
print(str * 2)             # 输出字符串两次
print(str + '你好')        # 连接字符串
 
print('------------------------------')
 
print('hello\nrunoob')      # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob')     # 在字符串前面添加一个 r,表示原始字符串,不会发生转义

where r refers to raw, i.e. raw string.

The output is:

Runoob 
Runoo 
R 
forehead 
noob 
RunoobRunoob 
Runoob你好
------------------------------ 
hello 
runoob 
hello \ nrunoob

Blank line

Separated by a blank line between the function or class method, it indicates start a new code. Also separated by a blank line between the class and the function entry, function entry to highlight start.

Blank lines of code indentation with a different part of the blank line is not a Python syntax. Do not insert a blank line when writing, Python interpreter to run it will not go wrong. However, the role that the partition blank line meaning two different functions or code to facilitate future maintenance or reconstructed code.

Remember: part of the program is also empty line of code.


Waiting for user input

Perform the following procedure after pressing the Enter key will wait for user input:

实例(Python 3.0+)
#!/usr/bin/python3
 
input("\n\n按下 enter 键后退出。")

 

 

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


Display multiple statements on the same line

Python can be used in the same row multiple statements, statements using a semicolon (;) is divided, the following is a simple example:

实例(Python 3.0+)
#!/usr/bin/python3
 
import sys; x = 'runoob'; sys.stdout.write(x + '\n')

Use the above script execution code output is:

runoob

Using an interactive command line, output is:

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

7 here represents the number of characters.


A plurality of code groups constituting statements

Indent the same set of statements constituting a code block, we call code group.

Like compound statements such as if, while, def and class, the first line to start with keywords, a colon (:) end, following the line of code constitutes one or more lines of code groups.

We will be the first line and the following code group called a clause (clause).

Following examples:

if expression : 
   suite
elif expression : 
   suite 
else : 
   suite

Print output

The default print output is the new line, if you want to achieve does not need to wrap at the end of variable plus  End = "" :

实例(Python 3.0+)
#!/usr/bin/python3
 
x="a"
y="b"
# 换行输出
print( x )
print( y )
 
print('---------')
# 不换行输出
print( x, end=" " )
print( y, end=" " )
print()

The above examples Implementation of the results:

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

import 与 from...import

In the python with the import or to import from ... import corresponding module.

The entire module (somemodule) introducing the format: import somemodule

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

Import function from a plurality of modules, the format is: from somemodule import firstfunc, secondfunc, thirdfunc

All function in a module import the format: from somemodule import *

Import module sys

import sys
print('================Python import mode==========================');
print ('命令行参数为:')
for i in sys.argv:
    print (i)
print ('\n python 路径为',sys.path)

Import sys module's argv, path member 

from sys import argv,path  #  导入特定的成员
 
print('================python from import===================================')
print('path:',path) # 因为已经导入path成员,所以此处引用时不需要加sys.path

Command line parameters

Many programs can perform some operations to view some basic information, Python can use the -h parameter to view the 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. ]

We used when executing Python script form, may receive a command line parameter, and may be used in particular with reference to  Python 3 command line parameters .

Guess you like

Origin blog.csdn.net/u012717715/article/details/91537794