Python基本语法

来源:互联网 发布:itudou官方下载mac 编辑:程序博客网 时间:2024/06/05 21:04

注释:#开头的行是注释,三个单引号在文件/函数/类开头就是文档注释
顺序:以缩进indent表示语句块,同一缩进级别为同一级别语句块,0级缩进在文件加载时就会被执行,冒号:开启新的缩进;一行多个语句可用逗号,分隔
选择:if:…elif:…elif:…else:
循环:for .. in ..: 用于迭代sequence
多用于loop的range()返回一个list, range(end)=range(0,end) ,range(start, end), range(start, end, step) 不包含end
beak:like in C, breaks out of the smallest enclosing for or while loop:continue:borrowed from C, continues with the next iteration of the loop
pass: no action 用于语法需要或临时占位符
Functional Programming: 函数式编程,操作的对象是集合,将函数作用于集合中的每一个元素 filter/map/reduce
List Comprehensions: [x*2 for x in range(5)]
Dict Comprehensions: {x:x*x for x in range(5)]
del: 删除一个元素或slice,del a[0]/a[1:2]/a[:]
yeild:定义生成器函数,generator function返回generator
iterator, 当生成器函数的next()被调用时会执行生成器函数,直至生成器函数抛出异常或终止,当yeild expression_list执行时,expresion_list返回结果给next(),同时生成器会被冻结直到下一次next()调用
global: 声明变量为全局,在局部代码块中对全局变量赋值
File:文件操作,使用c语言中stdio实现open()/close()/flush()
打开文件open(‘filename’, ‘mode’)mode可以为r/w/a/r+,默认 是’r’,使用with open(‘file’) as f 会帮助自动关闭f
fileno(): 返回文件描述符fd
next(): 按行迭代 f=open(“demo.txt”) try : for line in f: print line; finally f.close()
read/readline/releadlines: for line in f: print line,
seek/tell/truncate
write/writelines
closed/name/mode: 获取属性
None:null object, 被没有返回值的函数返回
assert: assert expression1, expression2; 是否是Debug模式由变量debug决定,不能对debug赋值, debug由interpreter赋值,interpreter默认以debug模式启动,当带有-O选项启动时则关闭debug模式
function:def fun(parameter1, parameter2…):….. 函数都有返回值,没有return语句的返回值是None, 与C语言一样,函数可以有默认参数,只能从右到左,并且默认参数只会计算一次;调用函数是可以用keywor指定参数,keyword参数只能在position参数之后 fun(p1,p2, key3=p3);packing argument即用*parameter接受参数tuple,**parameter接受参数dict,参数tuple需在参数dict之前;unpacking argument即解开list/dict作为参数传递func(*list)/func(**dict); 函数名应遵循low_case_with_underscores,常用built-in function有sorted/reversed/zip/len
Lambda Expression: 关键字lambda定义,lambda a:a+1 匿名函数对象,只能包含一条简单的expression,可用于任何需要函数对象的地方,就是普通函数定义的语法糖
I/O 输入/输出:
    Standard Input:    raw_input/raw_input(“hit:”)
    Standard Output:print statement依次计算print后的
    expression并转换为str输出到sys.stdout, ‘\n’会被追加到末尾,除非expression以common结束
str/repr: The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax). For objects which don’t have a particular representation for human consumption,str() will return the same value as repr(). Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function. Strings and floating point numbers, in particular, have two distinct representations.

1 0
原创粉丝点击