vivion32 发表于 2015-4-24 09:08:36

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代码
[*]#encoding=utf-8
[*]
[*]def show():
[*]    print u'I am a module.'
[*]
[*]if __name__ == '__main__':
[*]    show()
  
  7.随机数
  
  import random
  random.random() #产生[0,1)之间的随机浮点数
  random.randint(a,b) #产生之间的整数(包括a和b)
  
  
  8.命令行输入参数
  
  
  def prompt(prompt):
  return raw_input(prompt).strip()
  name = prompt("Your Name: ")
  
9.Python的字符
  在python中,字符就是长度为1的字符串。
  获得字符串的所有字符:
  



Python代码
[*]>>> string = 'abcxyz'
[*]>>> char_list = list(string)
[*]>>> print char_list
[*]['a', 'b', 'c', 'x', 'y', 'z']
[*]>>> char_list =
[*]>>> print char_list
[*]['a', 'b', 'c', 'x', 'y', 'z']
[*]>>> #获得字符串的所有字符的集合
[*]>>> import sets
[*]>>> char_set = sets.Set('aabbcc')
[*]>>> print char_set
[*]Set(['a', 'c', 'b'])
[*]>>> print ','.join(char_set)
[*]a,c,b
[*]>>> type(char_set)
[*]
[*]>>> for c in char_set:
[*]    print c   
[*]a
[*]c
[*]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是脚本的名称。
  



Python代码
[*]# _*_ coding:utf-8 _*_
[*]import sys
[*]if __name__ == "__main__":
[*]    if len(sys.argv) < 2:
[*]      print "Need a argument!"
[*]      sys.exit(1)
[*]    arg = sys.argv
[*]    print 'You input a argument:', arg
页: [1]
查看完整版本: Python基础笔记