Getting Started with Python explain basic grammar

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

## int

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: Python installer learning and learning videos, zero-based, advanced, combat free online live free courses within qun 784758214, hope can help you quickly understand Python, learning python

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 (double underline the beginning and end foo ) represents in particular python specific identification method, such as __init constructor () represent the class.

## 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.

## 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:

s = "peter is

writing this article"

# Second, the operator of the expression

1. Operator its usage

2. Operator Priority (from low to high)

## three control flow

1. Conditional statements

1.1 if statement

Program in the example of execution if statement

a = input(“a:”)

b = input(“b:”)

if(a > b):

print a, " > ", b

if else statements:

a = input(“a:”)

b = input(“b:”)

if(a > b):

print a, " > ", b

else:

print a, " < ", b

1.2 if ... elif ... else statement

Examples: The scores, the output level of the input score:

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”

the raw_input () to read the input values.

1.3 if the nested statement

When writing conditional statements, nested statements should be avoided. Nested statements are not easy to read, but may ignore some of the possibilities. Learning Python installation packages and video learning materials, zero-based, advanced, combat free online live free course, we hope to help you quickly understand Python, python learning within qun 784758214

x = -1

y = 99

if(x >= 0):

if (x> 0): # nested if statements

y = 1

else:

y = 0

else:

y = -1

print "y =", and

1.4 realize the function of a switch statement

There are no special word switch python, Python function can be achieved by a switch statement dictionary.

Implementation in two steps. First, define a dictionary. Dictionary is composed of a collection of keys. Secondly, the dictionary calls get () to obtain the corresponding expressions.

from future import division

x = 1

y = 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 = “+”

x = 1

y = 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);

四、函数

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

def sumOf(a, b):

return a + b

4.1 局部变量

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

def func():

global x

print "x is ", x

x = 1

x = 3

func()

print x

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

3

1

4.2 默认参数

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

def say(msg, times = 1):

print msg * times

say(“peter”)

say(“peter”, 3)

注意:只有在形参表末尾的那些参数可以有默认参数值,即不能在声明函数形参的时候,先声明有默认值的形参而后声明没有默认值的形参,只是因为赋给形参的值是根据位置而赋值的。

4.3 关键参数

如果某个函数有很多参数,而现在只想指定其中的部分,那么可以通过命名为这些参数赋值(称为‘关键参数’)。

优点:不必担心参数的顺序,使函数变的更加简单;假设其他参数都有默认值,可以只给我们想要的那些参数赋值。

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语句

return语句用来从一个函数返回,即跳出函数。可从函数返回一个值。

没有返回值的return语句等价于return None。None表示没有任何东西的特殊类型。

Guess you like

Origin blog.csdn.net/kkk123789/article/details/92004267