Python基础笔记

1.环境变量设置:

 

编辑系统变量Path,添加两个新路径

c:\Python26 能调用python.exe。

c:\python26\Scripts 调用通过扩展为Python添加的第三方脚本。

 

2.如果使用了中文,py文件第一行需指定字符集:

 

# -*- coding: utf-8 -*-

#encoding:utf-8

 

3.可变长参数

 

 

4.使用全局变量

 

函数中使用函数外的变量,可在变量名前使用global关键字

a = 5

def fun(x):

global a

return x+a

 

5.lambda表达式

 

匿名函数,单行小函数

 

格式:labmda 参数:表达式

返回表达式的值。

 

可包含单一的参数表达式,不能包含语句,但可以调用其他函数

fun = lambda x: x*x-x

fun(3)

 

def show():

print 'lambda'

f = lambda:show()

f()

 

def shown(n):

print 'lambda'*n

fn = lambda x : shown(x)

fn(2)

 

6.可运行脚本

 

Python代码  收藏代码
  1. #encoding=utf-8  
  2.   
  3. def show():  
  4.     print u'I am a module.'  
  5.   
  6. if __name__ == '__main__':  
  7.     show()  

 

7.随机数

 

import random

random.random() #产生[0,1)之间的随机浮点数

random.randint(a,b) #产生[a,b]之间的整数(包括a和b)

 

 

8.命令行输入参数

 

 

def prompt(prompt):

        return raw_input(prompt).strip()

name = prompt("Your Name: ")

 

9.Python的字符

在python中,字符就是长度为1的字符串。

获得字符串的所有字符:

 

Python代码  收藏代码
  1. >>> string = 'abcxyz'  
  2. >>> char_list = list(string)  
  3. >>> print char_list  
  4. ['a', 'b', 'c', 'x', 'y', 'z']  
  5. >>> char_list = [c for c in string]  
  6. >>> print char_list  
  7. ['a', 'b', 'c', 'x', 'y', 'z']  
  8. >>> #获得字符串的所有字符的集合  
  9. >>> import sets  
  10. >>> char_set = sets.Set('aabbcc')  
  11. >>> print char_set  
  12. Set(['a', 'c', 'b'])  
  13. >>> print ','.join(char_set)  
  14. a,c,b  
  15. >>> type(char_set)  
  16. <class 'sets.Set'>  
  17. >>> for c in char_set:  
  18.     print c   
  19. a  
  20. c  
  21. b  

 

10.字符和字符值的转换

将字符转换为ascii码,内建函数ord():

 

>>> ord('a')

97

 

将ascii码转换为字符,内建函数chr():

 

>>> chr(97)

'a'

 

将unicode字符转换为unicode码,内建函数ord():

 

>>> ord(u'\u2020')

8224

 

将unicode码转换为unicode字符,内建函数unichr():

 

>>> unichr(8224)

u'\u2020'

 

11.测试对象是否是类字符串

isinstance(anobj, basestring)

 

12.  sys.argv

传递给Python脚本的命令行参数列表。argv[0]是脚本的名称。

 

Python代码  收藏代码
  1. # _*_ coding:utf-8 _*_  
  2. import sys  
  3. if __name__ == "__main__":  
  4.     if len(sys.argv) < 2:  
  5.         print "Need a argument!"  
  6.         sys.exit(1)  
  7.     arg = sys.argv[1]  
  8.     print 'You input a argument:', arg  
posted @ 2015-01-14 17:02  juggd  阅读(478)  评论(1编辑  收藏  举报