Python programming entry - Detailed basic grammar (classical)

Today small to give us the Python programming entry - Detailed basic grammar. Tips: bright spot in the final!

Python programming entry - Detailed basic grammar (classical)

 

First, the basic concept

1. built-in variable types:

Python is a variable type, and will force a check variable types. Built-in variable types are the following:

#floating point

float_number = 2.3

#plural

complex_number = 1 + 5j

# Integer

integer_number = 1

#list sequence

sample_list = [2,52,36,'abc']

# Nesting

sample_nest = [(2,4,6),{5:7,9:11,'key':[2,5]},6]

#dictionary dictionary

sample_dic = {"key":value, 5:10}

#tuple read-only sequence

sample_tuple = (3,9,"ab")

As can be seen from the above example, Python variables need to be declared, may be directly assigned to the variable.

2. String

python declare a string normally has three ways, '', '' and '' '' '', which results when three methods declared common string is exactly the same, except that the string itself present in quotes case, for example as follows:

word = 'good'

sentence = "hello world"

paragraph = '''good noon:"nice to meet you."'''

python using the single-line comments begin with #.

#!/usr/bin/python

# First comment

print "Hello, world!"; # second comment

Above output: hello, Python !. Comments can be the end of the statement or expression lines.

Multi-line comments can be three marks, such as:

'''This is a comment.

This is a comment, too.

This is a comment, too.

I said that already.'''

Escapes'';

NATURAL string, character string before the addition by r or R. The r "this is a line with" is displayed, not wrap.

python allow processing unicode string, prefix u or U, such as u "this is an unicode string".

3.Python identifier

In python, the identifier letters, numbers or underlines.

In python, all identifiers can include letters, numbers, and the underscore (_), but can not start with a number.

python identifier is case sensitive.

Identifiers beginning with an underscore have a special significance. Single underline to begin (the _foo) representative of the class can not directly access attributes, accessed through the interface provided by class, not the introduction "from xxx import *";

Starting with a double underscore (__foo) private members of the representative class; see (__foo__) on behalf of python is double-underlined in particular the beginning and end of the specific identification method, such as __init __ () representative of the class constructor.

4.Python reserved characters

The following list shows the reserved words in Python. These words can not be used to retain a constant or variable, or any other identifier names.

All Python keywords contain only lowercase letters.

Python programming entry - Detailed basic grammar (classical)

 

Python programming entry - Detailed basic grammar (classical)

 

5. line breaks and indentation

Learning Python and the biggest difference is in other languages, the Python code blocks without using braces ({}) to control classes, functions, and other logic judgment. python most unique is to use indentation to write modules.

The number of spaces to indent is variable, but all of the code block statement must contain the same number of spaces to indent, this must be strictly enforced. As follows:

if True:

print "True"

else:

print "False"

Above, and if the same number of spaces indentation else's. The following code will be given:

if True:

print "Answer"

print "True"

else:

print "Answer"

print "False"

python semicolon; a logical line end flag, but generally each of the actual physical row write only a logical line, avoid using semicolons. Such writing easy to read. Note: Do not mix spaces and tabs to indent, because they can not work properly when across different platforms.

The plurality of physical lines in a logical line can be written using the line connector, as follows:

= "peter is

writing this article"

Second, the operator of the expression

1. Operator its usage

Python programming entry - Detailed basic grammar (classical)

 

Python programming entry - Detailed basic grammar (classical)

 

Python programming entry - Detailed basic grammar (classical)

 

2. Operator Priority (from low to high)

Python programming entry - Detailed basic grammar (classical)

 

Python programming entry - Detailed basic grammar (classical)

 

III. Control Flow

1. Conditional statements

1.1 if statement

Program in the example of execution if statement

= input("a:")

= input("b:")

if(a > b):

print a, " > ", b

if else语句:

= input("a:")

= input("b:")

if(a > b):

print a, " > ", b

else:

print a, " < ", b

1.2 if…elif…else语句

例子:根据输入的分数,输出分数等级:

score = raw_input("score:")

score=int(score)

if(score >= 90) and (score <= 100):

print "A"

elif(score >= 80) and (score < 90):

print "B"

elif(score >= 60) and (score < 80):

print "C"

else:

print "D"

raw_input() 读取输入值。

Python programming entry - Detailed basic grammar (classical)

 

1.3 if语句的嵌套

编写条件语句时,应该尽量避免使用嵌套语句。嵌套语句不便于阅读,而且可能会忽略一些可能性。

= -1

= 99

if(x >= 0):

if(x > 0): #嵌套的if语句

= 1

else:

= 0

else:

= -1

print "y =", y

1.4 实现switch语句的功能

python中没有switch特殊字,Python可以通过字典实现switch语句的功能。

实现方法分两步。首先,定义一个字典。字典是由键值对组成的集合。其次,调用字典的get()获取相应的表达式。

from __future__ import division

= 1

= 2

operator = "/"

result = {

"+" : x + y,

"-" : x - y,

"*" : x * y,

"/" : x / y

}

print result.get(operator)

输出为0.5;

另一种使用switch分支语句的方案是创建一个switch类,处理程序的流程。

a) 创建一个switch类,该类继承自Python的祖先类object。调用构造函数init( )初始化需要匹配的字符串,并需要定义两个成员变量value和fall。Value用于存放需要匹配的字符串,fall用于记录是否匹配成功,初始值为false,标识匹配不成功。如果匹配成功,程序往后执行。

b) 定义一个match( )方法,该方法用于用于匹配case子句。这里需要考虑三种情况:首先是匹配成功的情况,其次是匹配失败的默认case子句,最后是case子句中没有使用break中断的情况。

c) 重写__iter__( )方法,定义该方法后才能使switch类用于循环语句中。__iter__( )调用match( )方法进行匹配。通过yield保留字,使函数可以在循环中迭代。此外,调用StopIteration异常中断循环。

d) 编写调用代码,在for…in…循环中使用switch类。

#!/usr/bin/python

# -*- coding: UTF-8 -*-

class switch(object):

def __init__(self, value): # 初始化需要匹配的值value

self.value = value

self.fall = False # 如果匹配到的case语句中没有break,则fall为true。

def __iter__(self):

yield self.match # 调用match方法 返回一个生成器

raise StopIteration # StopIteration 异常来判断for循环是否结束

def match(self, *args): # 模拟case子句的方法

if self.fall or not args: # 如果fall为true,则继续执行下面的case子句

# 或case子句没有匹配项,则流转到默认分支。

return True

elif self.value in args: # 匹配成功

self.fall = True

return True

else: # 匹配失败

return False

operator = "+"

= 1

= 2

for case in switch(operator): # switch只能用于for in循环中

if case('+'):

print x + y

break

if case('-'):

print x - y

break

if case('*'):

print x * y

break

if case('/'):

print x / y

break

if case(): # 默认分支

print ""

2.while...语句

只要在一个条件为真的情况下,while语句允许你重复执行一块语句。while语句是所谓 循环 语句的一个例子。while语句有一个可选的else从句。

while True:

pass

else:

pass

#else语句可选,当while为False时,else语句被执行。 pass是空语句。

3.for 循环

for i in range(0, 5):

print i

else:

pass

# 打印0到4

注:当for循环结束后执行else语句;range(a, b)返回一个序列,从a开始到b为止,但不包括b,range默认步长为1,可以指定步长,range(0,10,2);

Python programming entry - Detailed basic grammar (classical)

 

四、函数

函数通过def定义。def关键字后跟函数的标识符名称,然后跟一对圆括号,括号之内可以包含一些变量名,该行以冒号结尾;接下来是一块语句,即函数体。

def sumOf(a, b):

return a + b

4.1 局部变量

在函数内定义的变量与函数外具有相同名称的其他变量没有任何关系,即变量名称对于函数来说是局部的。这称为变量的作用域。global语句, 为定义在函数外的变量赋值时使用global语句。

def func():

global x

print "x is ", x

= 1

= 3

func()

print x

以上代码,输出的结果为:

3

1

4.2 默认参数

通过使用默认参数可以使函数的一些参数是‘可选的’。

def say(msg, times = 1):

print msg * times

say("peter")

say("peter", 3)

Note: Only those parameters parameter end of the table can have default parameter values that can not function when declaring formal parameters, the first statement has shaped the default parameter value then the statement is no default value parameter, just because assigned to parameter and values are assigned according to the position.

4.3 Key parameters

If a function has many parameters, but now want to specify only part of them, you can assign these parameters by name (called 'key parameters').

Pros: do not have to worry about the order parameter of the function is now even easier; assuming that other parameters have default values, you can only give those parameters we want the assignment.

def func(a, b=2, c=3):

print "a is %s, b is %s, c is %s" % (a, b, c)

func(1) #输出a is 1, b is 2, c is 3

func(1, 5) #输出a is 1, b is 5, c is 3

func(1, c = 10) #输出a is 1, b is 2, c is 10

func(c = 20, a = 30) #输出a is 30, b is 2, c is 20

4.3 return statement

The return statement is used to return from a function, i.e., out of a function. Return value from a function.

No return value return statement is equivalent to return None. None means that no particular type anything.

Guess you like

Origin blog.csdn.net/java276582434/article/details/91384135