1、python作用域
注意:与函数的栈有所区别:http://www.cnblogs.com/rain-lei/p/3622057.html
对于变量的作用域,只要在内存中存在,就可以使用,如name变量在下面的代码中就可以使用。
>>> if 1 == 1:
... name = "QQ"
...
>>> print name
QQ
2、三元运算
>>> name = "QQ" if 1==1 else 'haha'
>>> print name
QQ
>>> name = "QQ" if 1!=1 else 'haha'
>>> print name
haha
3、python的进制
4、pycharm断点设置
创建project -->配置解释器-->创建文件-->执行:run debug(断点)
5、python对象
a、对于python,一切事物都是对象,对象基于类创建。
类有:字符串类、数字类、列表类
dir(list)查看list的方法
如何查看python的源码:在pycharm中,ctrl+list 查看
b、type查看对象的类型
c、dir(类型名)查看类中提供所有功能;
help(类型名)
help(类型名.方法)
6、数据类型的内置方法
类中的方法:
__方法__:内置方法,可能有多种执行,至少一种
方法:只有一种执行方法,类.方法
n1=1,n2=1,n1+n2
>>> n1.__add__(n2)
创建数字的两种方法: i=10,i=int(10)
求绝对值得两种方法:
>>> abs(n1)
1
>>> n1.__abs__()
1
求商和余数:
>>> a = 99
>>> a.__divmod__(10)
(9, 9)
7、编码与解码
编码:
Unicode------>UTF-8
Unicode------>GBK
解码:
UTF-8------->Unicode
GBK ------->Unicode
8、字符串的内置方法
class str(basestring): """ str(object='') -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. """ def capitalize(self): # real signature unknown; restored from __doc__ """ S.capitalize() -> string Return a copy of the string S with only its first character capitalized. """ return "" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.center(width[, fillchar]) -> string Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def decode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__ """ S.decode([encoding[,errors]]) -> object Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. """ return object() def encode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__ """ S.encode([encoding[,errors]]) -> object Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors. """ return object() def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=None): # real signature unknown; restored from __doc__ """ S.expandtabs([tabsize]) -> string Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ return "" def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ 在一个较长的字符串中查找子串,返回子串所在的最左端的索引,如果没有找到返回-1; 此方法还可以接收可选的起始点和结束点参数; """ """ S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def format(*args, **kwargs): # known special case of str.format """ S.format(*args, **kwargs) -> string Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ pass def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(sub [,start [,end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0 def isalnum(self): # real signature unknown; restored from __doc__ """ S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. """ return False def isalpha(self): # real signature unknown; restored from __doc__ """ S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return False def islower(self): # real signature unknown; restored from __doc__ """ S.islower() -> bool Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. """ return False def isspace(self): # real signature unknown; restored from __doc__ """ S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. """ return False def istitle(self): # real signature unknown; restored from __doc__ """ S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): # real signature unknown; restored from __doc__ """ S.isupper() -> bool Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. """ return False def join(self, iterable): # real signature unknown; restored from __doc__ """ 是split方法的逆方法,用来连接序列中的元素; """ """ S.join(iterable) -> string Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ return "" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.ljust(width[, fillchar]) -> string Return S left-justified in a string of length width. Padding is done using the specified fill character (default is a space). """ return "" def lower(self): # real signature unknown; restored from __doc__ """ 返回字符串的小写字母版 """ """ S.lower() -> string Return a copy of the string S converted to lowercase. """ return "" def lstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.lstrip([chars]) -> string or unicode Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ return "" def partition(self, sep): # real signature unknown; restored from __doc__ """ S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ 返回某字符串的所有匹配到的 """ """ S.replace(old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return "" def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rfind(sub [,start [,end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.rjust(width[, fillchar]) -> string Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" def rpartition(self, sep): # real signature unknown; restored from __doc__ """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. """ pass def rsplit(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__ """ S.rsplit([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.rstrip([chars]) -> string or unicode Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ return "" def split(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__ """ 是join的逆方法,用来将字符串分割成序列 """ """ S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return [] def splitlines(self, keepends=False): # real signature unknown; restored from __doc__ """ S.splitlines(keepends=False) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, chars=None): # real signature unknown; restored from __doc__ """ 除去两侧空格的字符串 """ """ S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ return "" def swapcase(self): # real signature unknown; restored from __doc__ """ S.swapcase() -> string Return a copy of the string S with uppercase characters converted to lowercase and vice versa. """ return "" def title(self): # real signature unknown; restored from __doc__ """ S.title() -> string Return a titlecased version of S, i.e. words start with uppercase characters, all remaining cased characters have lowercase. """ return "" def translate(self, table, deletechars=None): # real signature unknown; restored from __doc__ """ 和translate类似,不同的是只处理单个字符,同时可以进行多个替换,在使用translate之前,需要完成一张转换表 一般我们不自己写,使用string中的maketrans函数就可以了;from string import maketrans; table=maketrans('cs','kz') str1.translate(table) """ """ S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars. """ return "" def upper(self): # real signature unknown; restored from __doc__ """ S.upper() -> string Return a copy of the string S converted to uppercase. """ return "" def zfill(self, width): # real signature unknown; restored from __doc__ """ S.zfill(width) -> string Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. """ return "" def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown pass def _formatter_parser(self, *args, **kwargs): # real signature unknown pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __format__(self, format_spec): # real signature unknown; restored from __doc__ """ S.__format__(format_spec) -> string Return a formatted version of S as described by format_spec. """ return "" def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, string=''): # known special case of str.__init__ """ str(object='') -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. # (copied from class doc) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mod__(self, y): # real signature unknown; restored from __doc__ """ x.__mod__(y) <==> x%y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass bytes = str
>>> a.startswith('w') #以哪个字符串开头
True
>>> name='Char les'
>>> name.expandtabs() #将tab替换为空格,默认为8个空格
'Char les'
>>> name.expandtabs(1)
'Char les'
>>> name.expandtabs(0)
'Charles'
>>> name = 'Charles'
>>> name.find('a') #找到字符串中第一个子字符串的下标
字符串格式化的四种方法:
方法2:
>>> name = 'i am {ss} age {dd}'
>>> name.format(ss='Charles',dd=18)
'i am Charles age 18'
方法3:
>>> name = 'i am {0} age {1}'
>>> Li=[222,333]
>>> name.format(*Li)
'i am 222 age 333'
方法4:
>>> name = 'i am {0} age {1}'
>>> Li=[222,333]
>>> name.format(*Li)
'i am 222 age 333'
>>> a
'wahaha'
>>> a.islower() #都是小写
True
>>> a = 'a am charles'
>>> a.title() #字符首字母大写
'A Am Charles'
>>> a
'a am charles'
>>> a.ljust(30,"=") #邮编填充30个字符
'a am charles=================='
>>> a.lower() #全部变小写
'a am charles'
>>> a.upper() #全部变大写
'A AM CHARLES'
>>> a.swapcase() #大小写转换
'a aM cHARLES'
>>> name
'Charles'
>>> name.partition('a') #将字符串以...截断
('Ch', 'a', 'rles')
index和find的区别:
>>>name = 'Charles'
>>> name.index('a')
2
>>> name.find('a')
2
>>> name.index('j')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> name.find('j')
-1
>>> name.endswith('s') #以...结束
True
>>> name.__contains__('le') #是否包含子序列,返回布尔值
True
9、列表基础
>>> li = [11,22,33,44]
>>> del li[2] #删除列表的第三个元素
>>> del li #删除整个列表
>>> li.count(22) #计算列表中元素个数
2
>>> li.extend('wahaha') #扩展,可以是字符串或者列表
>>> li
[11, 22, 22, 33, 44, 'w', 'a', 'h', 'a', 'h', 'a']
>>> a_list = [1,2,3]
>>> li.extend(a_list)
>>> li
[11, 22, 22, 33, 44, 'w', 'a', 'h', 'a', 'h', 'a', 1, 2, 3]
>>> li.pop(2) #删除,下标
22
>>> li.remove('h') #删除,对象为元素
>>> li.reverse() #将列表的元素顺序反转
>>> li.sort() #将列表的元素排序,中文按照unicode比较,排序
10、列表与元组常用的方法
11、字典的常用方法
.get方法
>>> dic = {'a':123} >>> >>> >>> dic.get('a') #返回value的值 123 >>> dic.get('b','OK') #如果不存在key,返回OK 'OK'
字典的key不可以重复,value可以重复
.clear() #字典内容清空
>>> dic.clear() >>> dic {}
.has_key() #判断key是否在字典中
>>> dic.has_key('a') True
遍历字典的两种方法:
方法1:在数据量小的时候,这样用 >>> for k,v in dic.items():print k,v ... a 123 方法2:在大数据量的时候,这样用 >>> for k in dic:print k,dic[k] ... a 123
删除
>>> dic.pop('a') #删除元素 123 >>> del dic #全局性删除 >>> dic Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'dic' is not defined
update
>>> a = {'a':123} >>> b = {'b':456} >>> >>> a.update(b) #将b整合到a中 >>> a {'a': 123, 'b': 456}
.values()
>>> a.values() #value放置到列表中 [123, 456]
深浅拷贝:
>>> a {'a': 123, 'b': 456} >>> b = a >>> a['c']=789 >>> a {'a': 123, 'c': 789, 'b': 456} #字典为了节省内存,将b和a的引用都指向相同的地址,使得a变化,b也变化 >>> b {'a': 123, 'c': 789, 'b': 456}
>>> c = a.copy()
>>> c
{'a': 123, 'c': 789, 'b': 456}
>>> a['d']=111
>>> a
{'a': 123, 'c': 789, 'b': 456, 'd': 111}
>>> c #使用浅拷贝,可以使得a和c相互分离,但是这样还有问题,看下面
{'a': 123, 'c': 789, 'b': 456}
>>> a['e']={'name':['QQ']}
>>> a
{'a': 123, 'c': 789, 'b': 456, 'e': {'name': ['QQ']}, 'd': 111}
>>> d = a.copy()
>>> d
{'a': 123, 'c': 789, 'b': 456, 'e': {'name': ['QQ']}, 'd': 111}
>>>
>>> a['e']['name'].append('Charles') #如果字典/列表不只有一层,那么依旧没有分离,会原样拷贝,如何彻底分离呢,看下面
>>> a
{'a': 123, 'c': 789, 'b': 456, 'e': {'name': ['QQ', 'Charles']}, 'd': 111}
>>> d
{'a': 123, 'c': 789, 'b': 456, 'e': {'name': ['QQ', 'Charles']}, 'd': 111}
>>> import copy
>>> e = copy.deepcopy(a) #使用深拷贝,使得a和e完全分离
>>> e
{'a': 123, 'c': 789, 'b': 456, 'e': {'name': ['QQ', 'Charles']}, 'd': 111}
>>> a
{'a': 123, 'c': 789, 'b': 456, 'e': {'name': ['QQ', 'Charles']}, 'd': 111}
>>> a['e']['name'].append('Calen')
>>> a
{'a': 123, 'c': 789, 'b': 456, 'e': {'name': ['QQ', 'Charles', 'Calen']}, 'd': 111}
>>> e
{'a': 123, 'c': 789, 'b': 456, 'e': {'name': ['QQ', 'Charles']}, 'd': 111}
集合:
字符串本质上在C语言中是字符数组
python中一切事物都是对象,对象都是由类创建的,方法都是类的成员
set:其他语言中类似的hash表,不允许重复的元素出现
li= []
l2=list()
创建集合(只有一种方法):s1=set()
s1=set()
s1.add('alex')
s1.add('alex')
print s1
#访问速度快,天生解决重复问题;比如在python web爬虫的时候,可以将获取的内容增加到set中,去掉重复的内容
s2 = set(['alex','eric','tony','alex']) #可以将列表传入set集合,可以去掉重复的元素
print s2
s3 = s2.difference(['alex','eric']) #difference不会修改原来的集合,但是会生成新的集合
print s2 #set(['tony', 'alex', 'eric'])
print s3 #set(['tony'])
s4 = s2.difference_update(['alex','eric']) #不会生成新的集合,但是会修改原来的元素;
print s2 #set(['tony'])
print s4 #None
字典的缺点:无序
函数被调用的时候返回一个生成器,那么这个函数就是
a((w*)c)(d)
函数中没有return,那么返回值就为None;
python递归超过99层,就会报错;
购物车程序:
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import sys sales_dict = { #商品的名目 1:['Iphone6S',6088], 2:['MAC',8888], 3:['bike',500], 4:['car',30000] } buy_sales_list = {'Iphone6S':0, #购买商品和数量 'MAC':0, 'bike':0, 'car':0 } while True: total_money = int(raw_input('