Python Second Day

A、进制

  1. 硬盘上保存数据: 01010101010101010101
  2. 读取:01010101010101010101 -> 对应的编码的汉字 --> xx
  3. 看到的:
    - 转换完成的字符串
    - 以十六进制展示的01010101
  4. 以二进制打开文件
    f = open('log','rb')

B.基本数据类型

#######################################################   str   #######################################################

1.
capitalize(self)  #字符串首字母大写
return ""
"""
 S.capitalize() -> str
 Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case.
 返回一个大写版本的 S,即第一个字符大写其余小写。
"""
例:
S = 'alex'
v = S.capitalize()     
print(v)               #结果:Alex
--------------------------------------------------------------------------------------------------------------------------------
2.
casefold(self)  #将所有大小变小写,casefold更牛逼,可以转化德语等其他语言...
return ""
"""
 S.casefold() -> str
 Return a version of S suitable for caseless comparisons.
 返回一个比较适合的 S 小写版本。
"""
例:
S = 'AleX'
v = S.casefold() 
print(v)               #结果:alex
--------------------------------------------------------------------------------------------------------------------------------
3.
lower(self)    #将所有大小变小写
return ""
"""
 S.lower() -> str
 Return a copy of the string S converted to lowercase.
 返回已转换为小写字符串 S 的副本 
"""
例:
S = 'AleX'
v = v = S.lower()
print(v)               #结果:alex
-------------------------------------------------------------------------------------------------------------------------------
4.
center(self, width, fillchar=None) #文本居中
return ""
"""
 S.center(width[, fillchar]) -> str
 Return S centered in a string of length width. Padding is done using the specified fill character (default is a space)
 返回 以S为中心 长度为width 的字符串。使用指定的填充字符 填充(默认是空格)
 参数1: 表示总长度
 参数2:空白处填充的字符(长度为1)
"""
例:
S = 'alex'
v = S.center(10)       
n = S.center(10,'行')  
a = S.center(2,'行')   
b = S.center(5,'行')   
print(v)               #结果:   alex   
print(n)               #结果:行行行alex行行行
print(a)               #结果:alex
print(b)               #结果:行alex
-------------------------------------------------------------------------------------------------------------------------------
5.
count(self, sub, start=None, end=None) #表示传入值在字符串中出现的次数
return 0
"""
 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.
 返回 sub 在字符串 S [start:end] 中 非重叠出现的子串次数。可选参数的 start和end 被解释为切片符号。
 参数1: 要查找的值(子序列)
 参数2: 起始位置(索引)
 参数3: 结束位置(索引)
"""
例:
S = "alexasdfdsafsdfasdfaaaaa"
v = S.count('a')       
n = S.count('df')
a = S.count('df',12)
b = S.count('df',0,15)
print(v)               #结果:9
print(n)               #结果:3
print(a)               #结果:2
print(b)               #结果:2
-------------------------------------------------------------------------------------------------------------------------------
6.
endswith(self, suffix, start=None, end=None) #是否以xx结尾
return False
"""
 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.
 如果字符串S的结尾和指定的suffix相同返回True,否则返回False。可选start,测试 在S的该位置开始。可选end,停止匹配 在S的该位置。suffix可以是一个元组去尝试。
 参数1: 要查找的值(子序列)
 参数2: 起始位置(第一个字符为1)
 参数3: 结束位置(第一个字符为1)
"""
例:
S = 'alex' 
v = S.endswith('ex')   
n = S.endswith(("w","x"))
a = S.endswith(("w","e"))
b = S.endswith(("w","a"),0,1)
print(v)               #结果:True
print(n)               #结果:True
print(a)               #结果:False
print(b)               #结果:True
-------------------------------------------------------------------------------------------------------------------------------
7.
startswith(self, prefix, start=None, end=None) #是否以xx开始
return False
"""
 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.
 如果字符串S的开始和指定的suffix相同返回True,否则返回False。可选start,测试 在S的该位置开始。可选end,停止匹配 在S的该位置。suffix可以是一个元组去尝试。
 参数1: 要查找的值(子序列)
 参数2: 起始位置(第一个字符为1)
 参数3: 结束位置(第一个字符为1)
"""
例:
S = 'alex' 
v = S.startswith('al')   
n = S.startswith(("w","x"))
a = S.startswith(("w","e"))
b = S.startswith(("w","a"),0,1)
print(v)               #结果:True
print(n)               #结果:False
print(a)               #结果:True
print(b)               #结果:True
-------------------------------------------------------------------------------------------------------------------------------      
8.
def encode(self, encoding='utf-8', errors='strict') #转换成字节
return b""
"""
 S.encode(encoding='utf-8', errors='strict') -> bytes
 Encode S using the codec registered for encoding. Default encoding is 'utf-8'. 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 can handle UnicodeEncodeErrors.
""" 
例:
S = "李杰"
v1 = S.encode(encoding='utf-8') # 字节类型
print(v1)                          # 结果:b'\xe6\x9d\x8e\xe6\x9d\xb0'
v2 = S.encode(encoding='gbk')   # 字节类型
print(v2)                          # 结果:b'\xc0\xee\xbd\xdc'
-------------------------------------------------------------------------------------------------------------------------------  
9.
expandtabs(self, tabsize=8) #找到制表符\t,进行替换(包含前面的值)
return ""
"""
 S.expandtabs(tabsize=8) -> str
 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.
 返回使用空格扩展所有tab字符的S的副本。如果没有给出tabsize,一个tab制表符大小 假设为8个字符。
"""
例:
S = "al\te\tx\nalex\tuu\tkkk"
v = S.expandtabs(10)
print(v)
结果:
al        e         x
alex      uu        kkk
-------------------------------------------------------------------------------------------------------------------------------
10.
find(self, sub, start=None, end=None)  #找到指定子序列的索引位置:不存在返回-1
return 0
"""
 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.
 返回 在最小的索引 开始 ,字符串 S 中发现子串sub,这样的 sub 是包含在 S[start:end]里。可选参数start和end被解释为切片符号。失败返回-1。
"""
例:
S = 'alex'
v = S.find('e',0,1)
print(v)             #结果:-1
-------------------------------------------------------------------------------------------------------------------------------
11.
index(self, sub, start=None, end=None) #找到指定子序列的索引位置
return 0
"""
 S.index(sub[, start[, end]]) -> int
 Like S.find() but raise ValueError when the substring is not found.
 像S.find() 但是 当在字符串中没有找到时 报错。
"""
例:
S = 'alex'
v = S.index('e',0,1)
print(v)             #结果:报错ValueError: substring not found
-------------------------------------------------------------------------------------------------------------------------------
12.
format(*args, **kwargs)  #字符串格式化
pass
"""
 S.format(*args, **kwargs) -> str
 Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}').
 返回一个格式化的版本 S,使用args 和 kwargs替换。替换是以括号('{'和'}')鉴别。
"""
例:
S = "我是:{0};年龄:{1};性别:{2}"
v = S.format("李杰",19,'都行')
print(v)                       #结果:我是:李杰;年龄:19;性别:都行
S = "我是:{name};年龄:{age};性别:{gender}"
v = S.format(name='李杰',age=19,gender='随意')
print(v)                       #结果:我是:李杰;年龄:19;性别:都行
-------------------------------------------------------------------------------------------------------------------------------
13.
format_map(self, mapping)  #字符串格式化
return ""
"""
 S.format_map(mapping) -> str
 Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces ('{' and '}').
 返回一个格式化的版本 S,使用mapping替换。替换是以括号('{'和'}')鉴别。
"""
例:
S = "我是:{name};年龄:{age};性别:{gender}"
v = S.format_map({'name':"李杰",'age':19,'gender':'中'})
print(v)                                                  #结果:我是:李杰;年龄:19;性别:中
-------------------------------------------------------------------------------------------------------------------------------
14.
isalnum(self)  #是否是数字、汉字、数字.
return False
"""
 S.isalnum() -> bool
 Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.
 如果S中的所有字符都是字母数字,则至少有一个字符在S中返回True,否则为False。
"""
例:
S = 'alex8汉子'
v = S.isalnum()      
print(v)             #结果:True
-------------------------------------------------------------------------------------------------------------------------------
15.
isalpha(self)  #是否是字母、汉字.
return False
"""
 S.isalpha() -> bool
 Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise.
 如果S中的所有字符都是字母,则至少有一个字符在S中返回Ture,否则为False。
"""
例:
S  = 'alex8汉子'
v = S.isalpha()
print(v)              #结果:False
-------------------------------------------------------------------------------------------------------------------------------
16.
isdecimal(self) #是否是阿拉伯数字
return False
"""
 S.isdecimal() -> bool
 Return True if there are only decimal characters in S, False otherwise.
 如果只有十进制数的字符则返回Ture 否则False
"""
例:
S = '二'
v = S.isdecimal()  # '123'
print(v)         #结果:False
-------------------------------------------------------------------------------------------------------------------------------
17.
isdigit(self) #是否是数字
return False
"""
 S.isdigit() -> bool
 Return True if all characters in S are digits and there is at least one character in S, False otherwise.
 如果S中的所有字符都是数字,并且至少有一个字符在s中返回True,否则为False。
"""
例:
S = '二'
v = S.isdigit()    # '123','②'
print(v)         #结果:False
-------------------------------------------------------------------------------------------------------------------------------
18.
isnumeric(self)   #是否是数字字符
return False
"""
 S.isnumeric() -> bool
 Return True if there are only numeric characters in S, False otherwise.
 如果S中只有数字字符,则返回True,否则为False。
"""
例:
S = '二'
v = S.isnumeric()    # '123','二','②'
print(v)             #结果:Ture
-------------------------------------------------------------------------------------------------------------------------------
19.
isidentifier(self) #是否是表示符
return False
"""
 S.isidentifier() -> bool
 Return True if S is a valid identifier according to the language definition. 
 Use keyword.iskeyword() to test for reserved identifiers such as "def" and "class".
 如果S是一个有效标识符,则根据语言定义返回true。使用关键词。iskeyword()测试保留标识符如“def”和“class”。
"""
例:
S = 'name'
v = S.isidentifier()
print(v)              #结果:Ture
-------------------------------------------------------------------------------------------------------------------------------
20.
islower(self)  #是否全部是小写
return False
"""
 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.
 如果S中的所有字符都是小写字母,并且在S中至少有一个字符返回true,否则为False
"""
例:
S = "ALEX"
v = S.islower()     
print(v)            #结果:False
-------------------------------------------------------------------------------------------------------------------------------
21.
isupper(self) #是否全部是大写
return False
"""
 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.
 如果S中的所有字符都是大写,并且至少包装一个字符在S里返回Ture,否则为False
"""
例:
S = "ALEX"
v = S.isupper()     
print(v)            #结果:True
-------------------------------------------------------------------------------------------------------------------------------
22.
isprintable(self) #是否包含隐含的xx
return False
"""
 S.isprintable() -> bool
 Return True if all characters in S are considered printable in repr() or S is empty, False otherwise.
 如果所有的字符是repr()标准打印或是空返回true,否则为false。
"""
例:
S = "钓鱼要钓刀鱼,\t刀鱼要到岛上钓"
v = S.isprintable()
print(v)                #结果:False
-------------------------------------------------------------------------------------------------------------------------------
23.
isspace(self)    #是否全部是空格
return False
"""
 S.isspace() -> bool   
 Return True if all characters in S are whitespace and there is at least one character in S, False otherwise.
 如果所有字符在S中是空格 并且至少有一个字符在S里 ,返回true,否则为False 。
"""
例:
S = '    '
v = S.isspace()
print(v)                #结果:Ture
-------------------------------------------------------------------------------------------------------------------------------
24.☆☆☆☆☆
join(self, iterable)  # 元素拼接(元素字符串)
return ""
"""
 S.join(iterable) -> str
 Return a string which is the concatenation of the strings in the iterable.  The separator between elements is S.
 返回一个连接每个字符的iterable。元素之间的分隔符是 S.
"""
例:
iterable = 'alex'
S = "_"
v = S.join(iterable)        # 内部循环每个元素
print(v)               # 结果:a_l_e_x

iterable = ['海峰','杠娘','李杰','李泉']
S = "搞"
v = S.join(iterable)       
print(v)               # 结果:海峰搞杠娘搞李杰搞李泉
-------------------------------------------------------------------------------------------------------------------------------
25.
ljust(self, width, fillchar=None)   # 左填充
return ""
"""
 S.ljust(width[, fillchar]) -> str
 Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space).
 返回左对齐的S ,Unicode字符串的长度为width。填充使用指定的填充字符(默认是空格)。
"""
例:
S = 'alex'
v = S.ljust(10,'*')
print(v)                #结果:alex******
-------------------------------------------------------------------------------------------------------------------------------
26.
rjust(self, width, fillchar=None)   #右填充
return ""
"""
 S.rjust(width[, fillchar]) -> str
 Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space).
 返回右对齐的S ,Unicode字符串的长度为width。填充使用指定的填充字符(默认是空格)。
"""
例:
S = 'alex'
v = S.rjust(10,'*')
print(v)                #结果:******alex
-------------------------------------------------------------------------------------------------------------------------------
27.
maketrans(self, *args, **kwargs)   #对应关系 + 翻译
pass
"""
 Return a translation table usable for str.translate().
 If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. 
 Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary,
 each character in x will be mapped to the character at the same position in y. 
 If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

""" 
translate(self, table)
return ""
"""
 S.translate(table) -> str
 Return a copy of the string S in which each character has been mapped through the given translation table. 
 The table must implement lookup/indexing via __getitem__, for instance a dictionary or list, mapping Unicode ordinals to Unicode ordinals, strings, or None. 
 If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

""" 
例:
m = str.maketrans('aeiou','12345')  # 对应关系
S = "akpsojfasdufasdlkfj8ausdfakjsdfl;kjer09asdf"
v = S.translate(m)
print(v)                            #结果:1kps4jf1sd5f1sdlkfj815sdf1kjsdfl;kj2r091sdf
-------------------------------------------------------------------------------------------------------------------------------
28.
partition(self, sep)  #分割,保留分割的元素
pass
"""
 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.
 在S中搜索分离器SEP,并返回它之前的部分、分离器本身和它后面的部分。如果找不到分隔符,则返回S和两个空字符串。
"""
例:
S = "李泉SB刘康SB刘一"
v = S.partition('SB') 
print(v)               #结果:('李泉', 'SB', '刘康SB刘一')
-------------------------------------------------------------------------------------------------------------------------------
29.
replace(self, old, new, count=None)
return ""
"""
 S.replace(old, new[, count]) -> str
 Return a copy of S with all occurrences of substring old replaced by new.  If the optional argument count is given, 
 only the first count occurrences are replaced.
 返回一份用new 取代 S所有的old字符串。如果给定可选参数计数,则只有前 count 个事件被替换。
"""
例:
S = "李泉SB刘康SB刘浩SB刘一"
v = S.replace('SB','Love')
print(v)                 #结果:李泉Love刘康Love刘浩Love刘一
v = S.replace('SB','Love',1)
print(v)                 #结果:李泉Love刘康SB刘浩SB刘一
-------------------------------------------------------------------------------------------------------------------------------
30.
rfind(self, sub, start=None, end=None)
return 0
"""
 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.
 返回 在最大的索引开始 ,字符串 S 中发现子串sub ,这样的 sub 是包含在 S[start:end]里。可选参数start和end被解释为切片符号。失败返回-1。
"""
例:
S = 'alex'
v = S.rfind('e',2,3)
print(v)             #结果:2
-------------------------------------------------------------------------------------------------------------------------------
31.
rindex(self, sub, start=None, end=None)
return 0
"""
 S.rindex(sub[, start[, end]]) -> int
 Like S.rfind() but raise ValueError when the substring is not found.
 像S.rfind() 但是当没有找到字符串时 报ValueError
"""
例:
S = 'alex'
v = S.rindex('e',2,3)
print(v)             #结果:2
-------------------------------------------------------------------------------------------------------------------------------
32.
rpartition(self, sep)
pass
"""
 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.

""" 
例:
S = "李泉SB刘康SB刘一"
v = S.rpartition('SB') 
print(v)               #结果:('李泉SB刘康', 'SB', '刘一')
-------------------------------------------------------------------------------------------------------------------------------
33.
rsplit(self, sep=None, maxsplit=-1)
return []
"""
 S.rsplit(sep=None, maxsplit=-1) -> list of strings
 Return a list of the words in 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, any whitespace string is a separator.
 返回一个列表,单词在S中,使用sep作为分隔符,从字符串的结尾开始并工作到最前面。如果maxsplit是给定的,最多分裂maxsplit次。
 如果未指定任何SEP,空格的字符串是一个分离器。
"""
例:
S = 'as|ww|ee'
v = S.rsplit('|',1)
print(v)              #结果:['as|ww', 'ee']
-------------------------------------------------------------------------------------------------------------------------------
34.
rstrip(self, chars=None) #去除尾部空格
return ""
"""
 S.rstrip([chars]) -> str
 Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead.
 返回一个拷贝的字符串的尾部空格删除。如果字符是给定的,而不是没有,删除字符用chars代替。
"""
例:
S = 'ALEX     '
v = S.rstrip()
print(v)             #结果:ALEX
-------------------------------------------------------------------------------------------------------------------------------
35.
lstrip(self, chars=None)
return ""
"""
 S.lstrip([chars]) -> str
 Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead.
 返回一个拷贝的字符串的开头空格删除。如果字符是给定的,而不是没有,删除字符用chars代替。
"""
例:
S = '    ALEX'
v = S.lstrip()
print(v)             #结果:ALEX
-------------------------------------------------------------------------------------------------------------------------------
36.
split(self, sep=None, maxsplit=-1)  #
return []
"""
 S.split(sep=None, maxsplit=-1) -> list of strings
 Return a list of the words in 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.
 返回一个列表,单词在S中,用SEP作为分隔符串。如果maxsplit是给定的,最多分裂maxsplit次。
 如果sep未被指定或者是空,任何空白字符是一个分离器并且空白字符在结果中移除。
"""
例:
S = 'as|ww|ee'
v = S.split('|',1)
print(v)              #结果:['as', 'ww|ee']
-------------------------------------------------------------------------------------------------------------------------------
37.
splitlines(self, keepends=None)  #按回车生产列表
return []
"""
 S.splitlines([keepends]) -> 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.
 返回一个列表,在S中的行,在行边界处断开。换行不包含在结果列表中,除非keepends给出并为Ture。
"""
例:
S = """ALEX
asd
"""
v = S.splitlines()
print(v)             #结果:['ALEX', 'asd']
-------------------------------------------------------------------------------------------------------------------------------
38.
strip(self, chars=None)   移除空白,\n,\t
return ""
"""
 S.strip([chars]) -> str
 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.
 返回一个拷贝的字符串的开头和结尾的空格去掉。如果字符是给定的,而不是没有,删除字符用chars代替。
"""
例:
S = '   ALEX     '
v = S.strip()
print(v)             #结果:ALEX
-------------------------------------------------------------------------------------------------------------------------------
39.
swapcase(self)      # 大小写转换
return ""
"""
 S.swapcase() -> str
 Return a copy of S with uppercase characters converted to lowercase and vice versa.
 返回一个s的拷贝,大写字符转换为小写,反之亦然。
"""
例:
S = "Alex"
v = S.swapcase()
print(v)             #结果:aLEX
-------------------------------------------------------------------------------------------------------------------------------
40.
title(self)  #转换 标题版
return ""
"""
 S.title() -> str
 Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case.
 返回一个titlecased版的S,从单词开始标题版 字符串,所有剩余的字符的小写。
"""
例:
S = "i have a dream"
v =S.title()
print(v)            #结果:I Have A Dream
-------------------------------------------------------------------------------------------------------------------------------
41.
istitle(self)   #是否是标题版
return False
"""
 S.istitle() -> bool
 Return True if S is a titlecased string and there is at least one character in S, i.e. 
 upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.
 如果S是一个titlecased字符串并且至少有一个字符在S里返回True,i.e.大写 并且 titlecase字符只能跟着未包装的字符和小写字符的唯一情况。否则返回False。
"""
例:
S = "I Have A Dream"
v = S.istitle()
print(v)           #结果:Ture
-------------------------------------------------------------------------------------------------------------------------------
42.
upper(self)  #转换大写
return ""
"""
 S.upper() -> str
 Return a copy of S converted to uppercase.
 返回一个S 的大写副本
"""
例:
S = 'Alex'
v = S.upper()
print(v)            #结果:ALEX
-------------------------------------------------------------------------------------------------------------------------------
43.
zfill(self, width)   #填充0
return ""
"""
 S.zfill(width) -> str
 Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated.
 在左边填充一个带零的数字字符串,以填充指定width的字段。字符串从不被截断。
"""
例:
S = "alex"
v = S.zfill(10)
print(v)          #结果:000000alex
-------------------------------------------------------------------------------------------------------------------------------
44.
# 补充功能
name = "alex"
print(name[0]))         #结果:a
print(name[0:3])        #结果:ale
print(name[0:3:2])      #结果:ae
print(len(name))        #结果:4
# for循环,每个元素是字符
for v in name:
    print(v)
# 结果:
a
l
e
x

#######################################################   int   #######################################################

1.
def bit_length(self) # 当前整数的二进制表示,最少位数
return 0
"""
	int.bit_length() -> int
	Number of bits necessary to represent self in binary.
	二进制中表示自我必要的位数。
"""
例:
age = 4 # 100
print(age.bit_length()) #结果:3
-------------------------------------------------------------------------------------------------------------------------------
2.
def conjugate(self, *args, **kwargs)
pass
"""
	Returns self, the complex conjugate of any int. 
	返回该复数的共轭复数
"""
-------------------------------------------------------------------------------------------------------------------------------
3.
def from_bytes(cls, bytes, byteorder, *args, **kwargs)
pass
"""
	int.from_bytes(bytes, byteorder, *, signed=False) -> int
	Return the integer represented by the given array of bytes.
	The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
	The byteorder argument determines the byte order used to represent the
	integer.  If byteorder is 'big', the most significant byte is at the
	beginning of the byte array.  If byteorder is 'little', the most
	significant byte is at the end of the byte array.  To request the native
	byte order of the host system, use `sys.byteorder' as the byte order value.
	The signed keyword-only argument indicates whether two's complement is
	used to represent the integer.
"""
-------------------------------------------------------------------------------------------------------------------------------
4.
def to_bytes(self, length, byteorder, *args, **kwargs) # 获取当前数据的字节表示
pass
"""
	int.to_bytes(length, byteorder, *, signed=False) -> bytes
	Return an array of bytes representing an integer.
	The integer is represented using length bytes.  An OverflowError is
	raised if the integer is not representable with the given number of
	bytes.
	The byteorder argument determines the byte order used to represent the
	integer.  If byteorder is 'big', the most significant byte is at the
	beginning of the byte array.  If byteorder is 'little', the most
	significant byte is at the end of the byte array.  To request the native
	byte order of the host system, use `sys.byteorder' as the byte order value.
	The signed keyword-only argument determines whether two's complement is
	used to represent the integer.  If signed is False and a negative integer
	is given, an OverflowError is raised.
"""
例:
age = 15
v = age.to_bytes(1,byteorder='big') # 15 -> 00001111 
print(v)  #结果:b'\x0f'
v = age.to_bytes(2,byteorder='big') # 15 -> 00000000 00001111
print(v)	#结果:b'\x00\x0f'
v = age.to_bytes(2,byteorder='little') # 15 -> 00001111 00000000
print(v)  #结果:b'\x0f\x00'

#######################################################   bool   #######################################################

# v = 0 #False   1,-1  Ture
# v = "" #False
# v = [] #False
# --> 空内容:False

#######################################################   list   #######################################################

1.追加
def append(self, p_object): # real signature unknown; restored from __doc__
    """ L.append(object) -> None -- append object to end """
    pass
例:
user_list = ['李泉','刘一','刘康','豆豆','小龙']
user_list.append('刘铭')
print(user_list)        #结果:['李泉', '刘一', '刘康', '豆豆', '小龙', '刘铭']
-------------------------------------------------------------------------------------------------------------------------------
2.清空
def clear(self): # real signature unknown; restored from __doc__
    """ L.clear() -> None -- remove all items from L """
    pass
例:
user_list = ['李泉','刘一','刘康','豆豆','小龙']
user_list.clear()
print(user_list)      #结果:[]
-------------------------------------------------------------------------------------------------------------------------------
3.拷贝(浅拷贝)
def copy(self): # real signature unknown; restored from __doc__
    """ L.copy() -> list -- a shallow copy of L """
    return []
例:
user_list = ['李泉','刘一','刘康','豆豆','小龙']
v = user_list.copy()
print(v)              #结果:['李泉', '刘一', '刘康', '豆豆', '小龙']
print(user_list)      #结果:['李泉', '刘一', '刘康', '豆豆', '小龙']
-------------------------------------------------------------------------------------------------------------------------------
4.计数
def count(self, value): # real signature unknown; restored from __doc__
    """ L.count(value) -> integer -- return number of occurrences of value """
    return 0
例:
user_list = ['李泉','刘一','李泉','刘康','豆豆','小龙']
v = user_list.count('李泉')
print(v)              #结果:2
-------------------------------------------------------------------------------------------------------------------------------
5.扩展原列表
def extend(self, iterable): # real signature unknown; restored from __doc__
    """ L.extend(iterable) -> None -- extend list by appending elements from the iterable """
    pass
例:
user_list = ['李泉','刘一','刘康','豆豆','小龙']
user_list.extend(['郭少龙','郭少霞'])
print(user_list)              #结果:['李泉', '刘一', '刘康', '豆豆', '小龙', '郭少龙', '郭少霞']
-------------------------------------------------------------------------------------------------------------------------------
6.查找元素索引,没有报错
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
    """
    L.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.
    """
    return 0
user_list = ['李泉','刘一','刘康','豆豆','小龙']
v = user_list.index('刘一')
print(v)              #结果:1
-------------------------------------------------------------------------------------------------------------------------------
7.指定位置插入
def insert(self, index, p_object): # real signature unknown; restored from __doc__
    """ L.insert(index, object) -- insert object before index """
    pass
例:
user_list = ['李泉','刘一','刘康','豆豆','小龙']
user_list.insert(2,'刘一')
print(user_list)              #结果:['李泉', '刘一', '刘一', '刘康', '豆豆', '小龙']
-------------------------------------------------------------------------------------------------------------------------------
8.删除并且获取元素 - 索引
def pop(self, index=None): # real signature unknown; restored from __doc__
    """
    L.pop([index]) -> item -- remove and return item at index (default last).
    Raises IndexError if list is empty or index is out of range.
    """
    pass
例:
user_list = ['李泉','刘一','刘康','豆豆','小龙']
v = user_list.pop(1)
print(v)                      #结果:刘一
print(user_list)              #结果:['李泉', '刘康', '豆豆', '小龙']
-------------------------------------------------------------------------------------------------------------------------------
9.删除 - 值
def remove(self, value): # real signature unknown; restored from __doc__
    """
    L.remove(value) -> None -- remove first occurrence of value.
    Raises ValueError if the value is not present.
    """
    pass
例:
user_list = ['李泉','刘一','刘康','豆豆','小龙']
user_list.remove('刘一') 
print(user_list)              #结果:['李泉', '刘康', '豆豆', '小龙']
-------------------------------------------------------------------------------------------------------------------------------
10.翻转
def reverse(self): # real signature unknown; restored from __doc__
    """ L.reverse() -- reverse *IN PLACE* """
    pass
例:
user_list = ['李泉','刘一','刘康','豆豆','小龙']
user_list.reverse()
print(user_list)              #结果:['小龙', '豆豆', '刘康', '刘一', '李泉']
-------------------------------------------------------------------------------------------------------------------------------
11.排序
def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
    """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
    pass
例:
nums = [11,22,3,3,9,88]
nums.sort()
print(nums)              #结果:[3, 3, 9, 11, 22, 88]
nums.sort(reverse=True)
print(nums)              #结果:[88, 22, 11, 9, 3, 3]
-------------------------------------------------------------------------------------------------------------------------------
12.额外附加
user_list = ['李泉','刘一','李泉','刘康','豆豆','小龙']
a.索引
	user_list[0]
b.切片 ,步长
	user_list[1:5:2]
c.删除
	del user_list[3]
d.for 循环
	for i in user_list:
		print(i)
e.修改
	user_list[1] = '姜日天'
f.嵌套
	user_list = ['李泉','刘一','李泉','刘康','豆豆',['日天','日地','泰迪'],'小龙']
g.长度
	v = len(user_list)

#######################################################   tuple   #######################################################

1.获取个数
def count(self, value): # real signature unknown; restored from __doc__
    """ T.count(value) -> integer -- return number of occurrences of value """
    return 0
例:
user_tuple = ('alex','eric','seven','alex')
v = user_tuple.count('alex')
print(v)              #结果:2
-------------------------------------------------------------------------------------------------------------------------------
2.获取值的第一个索引位置
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
    """
    T.index(value, [start, [stop]]) -> integer -- return first index of value.
    Raises ValueError if the value is not present.
    """
    return 0
例:
user_tuple = ('alex','eric','seven','alex')
v = user_tuple.index('alex')
print(v)              #结果:0
-------------------------------------------------------------------------------------------------------------------------------
3.额外附加
user_tuple = ('alex','eric','seven','alex')
a.索引
	v = user_tuple[0]
b.切片
	v = user_tuple[0:2]
c. for 循环
	for i in user_tuple:
		print(i)
d.嵌套
	user_tuple = ('alex','eric','seven',['陈涛','刘浩','赵芬芬'],'alex')
	user_tuple[0] = 123         #不可以
	user_tuple[3] = [11,22,33]  #不可以
	user_tuple[3][1] = '刘一'   #可以
e.注意
	- 元组,不可被修改的列表;不可变类型
	- 元组最后,加逗号  ('alex',)

#######################################################   dict   #######################################################

1.清空
def clear(self): # real signature unknown; restored from __doc__
    """ D.clear() -> None.  Remove all items from D. """
    pass
例:
dic = {'k1':'v1','k2':'v2'}
dic.clear()
print(dic)     #结果:{}
-------------------------------------------------------------------------------------------------------------------------------
2.浅拷贝
def copy(self): # real signature unknown; restored from __doc__
    """ D.copy() -> a shallow copy of D """
    pass
例:
dic = {'k1':'v1','k2':'v2'}
v = dic.copy()
print(v)     #结果:{'k1': 'v1', 'k2': 'v2'}
-------------------------------------------------------------------------------------------------------------------------------
3.循环keys,填充values,生成字典
def fromkeys(*args, **kwargs): # real signature unknown
    """ Returns a new dict with keys from iterable and values equal to value. """
    pass
例:
dic = dict.fromkeys(['k1','k2','k3'],123)
print(dic)   #结果:{'k2': 123, 'k3': 123, 'k1': 123}
dic = dict.fromkeys(['k1','k2','k3'],123)
dic['k1'] = 'asdfjasldkf'
print(dic)   #结果:{'k2': 123, 'k3': 123, 'k1': 'asdfjasldkf'}

dic = dict.fromkeys(['k1','k2','k3'],[1,])
dic['k1'].append(222)
print(dic)  #结果:{'k3': [1, 222], 'k2': [1, 222], 'k1': [1, 222]}
-------------------------------------------------------------------------------------------------------------------------------
4.根据key获取指定的value;不存在不报错
def get(self, k, d=None): # real signature unknown; restored from __doc__
    """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
    pass
例:
dic = {'k1':'v1','k2':'v2'}
v = dic.get('k1111',1111)
print(v)     #结果:1111
-------------------------------------------------------------------------------------------------------------------------------
5.取 键值对
def items(self): # real signature unknown; restored from __doc__
    """ D.items() -> a set-like object providing a view on D's items """
    pass
例:
dic = {'k1':'v1','k2':'v2'}
v = dic.items()
print(v)     #结果:dict_items([('k1', 'v1'), ('k2', 'v2')])
-------------------------------------------------------------------------------------------------------------------------------
6.取keys
def keys(self): # real signature unknown; restored from __doc__
    """ D.keys() -> a set-like object providing a view on D's keys """
    pass
例:
dic = {'k1':'v1','k2':'v2'}
v = dic.keys()
print(v)     #结果:dict_keys(['k2', 'k1'])
-------------------------------------------------------------------------------------------------------------------------------
7.取values
def values(self): # real signature unknown; restored from __doc__
    """ D.values() -> an object providing a view on D's values """
    pass
例:
dic = {'k1':'v1','k2':'v2'}
v = dic.values()
print(v)     #结果:dict_values(['v1', 'v2'])
-------------------------------------------------------------------------------------------------------------------------------
8. 删除并获取对应的value值
def pop(self, k, d=None): # real signature unknown; restored from __doc__
    """
    D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
    If key is not found, d is returned if given, otherwise KeyError is raised
    """
    pass
例:
dic = {'k1':'v1','k2':'v2'}
v = dic.pop('k1')
print(dic)  #结果:{'k2': 'v2'}
print(v)    #结果:v1
-------------------------------------------------------------------------------------------------------------------------------
9.随机删除键值对,并获取到删除的键值
def popitem(self): # real signature unknown; restored from __doc__
    """
    D.popitem() -> (k, v), remove and return some (key, value) pair as a
    2-tuple; but raise KeyError if D is empty.
    """
    pass
例:
dic = {'k1':'v1','k2':'v2'}
v = dic.popitem()
print(dic)   #结果:{'k2': 'v2'}
print(v)     #结果:('k1', 'v1')

dic = {'k1':'v1','k2':'v2'}
k,v = dic.popitem()
print(dic)    #结果:{'k2': 'v2'}
print(k,v)    #结果:k1 v1
-------------------------------------------------------------------------------------------------------------------------------
10.增加,如果存在则不做操作
def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
    """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
    pass
例:
dic = {'k1':'v1','k2':'v2'}
dic.setdefault('k3','v3')
print(dic)  #结果:{'k2': 'v2', 'k1': 'v1', 'k3': 'v3'}
dic.setdefault('k1','1111111')
print(dic)  #结果:{'k2': 'v2', 'k1': 'v1', 'k3': 'v3'}
-------------------------------------------------------------------------------------------------------------------------------
11. 批量增加或修改
def update(self, E=None, **F): # known special case of dict.update
    """
    D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
    If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
    If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
    In either case, this is followed by: for k in F:  D[k] = F[k]
    """
    pass
例:
dic = {'k1':'v1','k2':'v2'}
dic.update({'k3':'v3','k1':'v24'})
print(dic)   #结果:{'k1': 'v24', 'k3': 'v3', 'k2': 'v2'}
-------------------------------------------------------------------------------------------------------------------------------
12.额外补充
a.嵌套
	- 字典可以嵌套
	- 字典key: 必须是不可变类型
b.删除
	del dic['k1']

#######################################################   set   #######################################################

1.添加
def add(self, *args, **kwargs): # real signature unknown
    """
    Add an element to a set.
		This has no effect if the element is already present.
    """
    pass
例:
n = {"alex",'eric','tony'}
n.add("bill")
print(n)   #结果:{'alex', 'bill', 'tony', 'eric'}
-------------------------------------------------------------------------------------------------------------------------------
2.清空
def clear(self, *args, **kwargs): # real signature unknown
    """ Remove all elements from this set. """
    pass
例:
n = {"alex",'eric','tony'}
n.clear()
print(n)   #结果:set()
-------------------------------------------------------------------------------------------------------------------------------
3.拷贝
def copy(self, *args, **kwargs): # real signature unknown
    """ Return a shallow copy of a set. """
    pass
例:
n = {"alex",'eric','tony'}
v = n.copy()
print(v)   #结果:{'tony', 'eric', 'alex'}
print(n)   #结果:{'tony', 'eric', 'alex'}
-------------------------------------------------------------------------------------------------------------------------------
4.s1中存在,s2中不存在
def difference(self, *args, **kwargs): # real signature unknown
    """
    Return the difference of two or more sets as a new set.
		(i.e. all elements that are in this set but not the others.)
    """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
s2 = {"alex",'eric','tony','刘一'}
v = s1.difference(s2)
print(v)   #结果:{'李泉', '李泉11'}
-------------------------------------------------------------------------------------------------------------------------------
5.s1中存在,s2中不存在,然后对s1清空,然后在重新复制
def difference_update(self, *args, **kwargs): # real signature unknown
    """ Remove all elements of another set from this set. """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
s2 = {"alex",'eric','tony','刘一'}
s1.difference_update(s2)
print(s1)   #结果:{'李泉', '李泉11'}
-------------------------------------------------------------------------------------------------------------------------------
6.两集合不同的元素
def symmetric_difference(self, *args, **kwargs): # real signature unknown
    """
    Return the symmetric difference of two sets as a new set.
		(i.e. all elements that are in exactly one of the sets.)
    """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
s2 = {"alex",'eric','tony','刘一'}
v = s1.symmetric_difference(s2)
print(v)   #结果:{'刘一', '李泉11', '李泉'}
-------------------------------------------------------------------------------------------------------------------------------
7.两集合不同的元素,然后对s1清空,然后在重新复制
def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
    """ Update a set with the symmetric difference of itself and another. """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
s2 = {"alex",'eric','tony','刘一'}
s1.symmetric_difference_update(s2)
print(s1)   #结果:{'李泉', '李泉11', '刘一'}
-------------------------------------------------------------------------------------------------------------------------------
8.交集
def intersection(self, *args, **kwargs): # real signature unknown
    """
    Return the intersection of two sets as a new set.
		(i.e. all elements that are in both sets.)
    """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
s2 = {"alex",'eric','tony','刘一'}
v = s1.intersection(s2)
print(v)   #结果:{'tony', 'eric', 'alex'}
-------------------------------------------------------------------------------------------------------------------------------
9.取交集,然后对s1清空,然后在重新复制
def intersection_update(self, *args, **kwargs): # real signature unknown
    """ Update a set with the intersection of itself and another. """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
s2 = {"alex",'eric','tony','刘一'}
s1.intersection_update(s2)
print(s1)   #结果:{'eric', 'tony', 'alex'}
-------------------------------------------------------------------------------------------------------------------------------
10.并集
def union(self, *args, **kwargs): # real signature unknown
    """
    Return the union of sets as a new set.
		(i.e. all elements that are in either set.)
    """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
s2 = {"alex",'eric','tony','刘一'}
v = s1.union(s2)
print(v)   #结果:{'alex', '李泉', 'tony', '李泉11', '刘一', 'eric'}
-------------------------------------------------------------------------------------------------------------------------------
11.移除
def discard(self, *args, **kwargs): # real signature unknown
    """
    Remove an element from a set if it is a member.
		If the element is not a member, do nothing.
    """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
s1.discard('alex')
print(s1)   #结果:{'李泉', 'tony', 'eric', '李泉11'}
-------------------------------------------------------------------------------------------------------------------------------
12.是否没有交集
def isdisjoint(self, *args, **kwargs): # real signature unknown
    """ Return True if two sets have a null intersection. """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
s2 = {"alex",'eric','tony','刘一'}
v = s1.isdisjoint(s2)
print(v)   #结果:False
-------------------------------------------------------------------------------------------------------------------------------
13. s1 是否是 s2的子集
def issubset(self, *args, **kwargs): # real signature unknown
    """ Report whether another set contains this set. """
    pass
例:
s1 = {"alex",'eric','tony'}
s2 = {"alex",'eric','tony','刘一'}
v = s1.issubset(s2)
print(v)   #结果:True
-------------------------------------------------------------------------------------------------------------------------------
14.s1 是否是 s2的父集
def issuperset(self, *args, **kwargs): # real signature unknown
    """ Report whether this set contains another set. """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
s2 = {"alex",'eric','tony'}
v = s1.issuperset(s2)
print(v)   #结果:True
-------------------------------------------------------------------------------------------------------------------------------
15.随机删除一个元素,并取值
def pop(self, *args, **kwargs): # real signature unknown
    """
    Remove and return an arbitrary set element.
    Raises KeyError if the set is empty.
    """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
v = s1.pop()
print(s1)  #结果:{'李泉', '李泉11', 'tony', 'alex'}
print(v)   #结果:eric
-------------------------------------------------------------------------------------------------------------------------------
16.移除
def remove(self, *args, **kwargs): # real signature unknown
    """
    Remove an element from a set; it must be a member.
		If the element is not a member, raise a KeyError.
    """
    pass
s1 = {"alex",'eric','tony','李泉','李泉11'}
s1.remove('alex')
print(s1)  #结果:{'tony', 'eric', '李泉11', '李泉'}
-------------------------------------------------------------------------------------------------------------------------------
17.批量添加,有相同的部分不该
def update(self, *args, **kwargs): # real signature unknown
    """ Update a set with the union of itself and others. """
    pass
例:
s1 = {"alex",'eric','tony','李泉','李泉11'}
s1.update({'alex','123123','fff'})
print(s1)  #结果:{'李泉', '李泉11', 'tony', 'alex', 'eric', 'fff', '123123'}
-------------------------------------------------------------------------------------------------------------------------------
18.额外补充
a.for 循环
	for i in s1:
		print(i)
b.嵌套
	s1 = {"alex",'eric','tony','李泉','李泉11',(11,22,33)}

##################################################### range、enumrate #####################################################

# 1. 请输出1-10
# 2.7: 立即生成所有数字
# range(1,11) # 生成 1,2,3,...10

# 3.x: 不会立即生成,只有循环迭代时,才一个一个生成
# for i in range(1,11): #
#     print(i)

# for i in range(1,11,2): #
#     print(i)

# for i in range(10,0,-1): #
#     print(i)

# 1. 3.x 不会立生成,迭代之后才一个一个创建;
"""
    - 2.7:
        range()
        xrange()  不会立生成,迭代之后才一个一个创建;
    - 3.x
        range()  不会立生成,迭代之后才一个一个创建;
        list(range())生成列表 
"""
# 2. range: 三个参数
#
# li = ['eric','alex','tony']
# # range,len,li循环
# for i in range(0,len(li)):
#     ele = li[i]
#     print(ele)


# li = ['eric','alex','tony']
# for i in li:
#     print(i)

# for i in range(0,len(li)):
#     print(i+1,li[i])


# enumerate额外生成一列有序的数字
# li = ['eric','alex','tony']
# for i,ele in enumerate(li,1):
#     print(i,ele)
#
# v = input('请输入商品序号:')
# v = int(v)
# item = li[v-1]
# print(item)

作业:

要求:
1.个人账户(存在文件里面)。里面有用户名 密码 重复登录次数(3次登录失败锁定) 余额。
2.显示商品列表,让用户根据序号选择商品,加入购物车
3.商品列表也是个文件,商品如果特别多要进行分页。
4.购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
5.查看个人购物记录。
5.个人购物记录支持模糊匹配
6.具有充值功能

goods文件为
电脑|1000
鼠标|20
键盘|30
显示器|300
美女|998
帅哥|1998
豪宅|2000
跑车|10
游艇|3000
豆浆|10
油条|20

db文件为:
sys|123456|0|6002
sy|123456|0|1000

shopp文件为:
||
美女|998|sys
电脑|1000|sy

job_body文件为:

#!/usr/bin/python
# -*- coding:utf-8 -*-

# 打开文件
f1 = open('db', 'r', encoding='utf-8')
f2 = open('goods', 'r', encoding='utf-8')
f3 = open('shopping', 'r', encoding='utf-8')
# 读取文件
date = f1.read()
goods = f2.read()
shopping = f3.read()
# 关闭文件
f1.close()
f2.close()
f3.close()
# 用户属性格式化
user_attr_list = []
db_str_list = date.split('\n')
for item in db_str_list:
    temp = item.split('|')
    v = {
        'name': temp[0],
        'pwd': temp[1],
        'num': temp[2],
        'balance': temp[3]
    }
    user_attr_list.append(v)
# 商品属性格式化
goods_attr_list = []
goods_str_list = goods.split('\n')
for item in goods_str_list:
    temp = item.split('|')
    v = {
        'name': temp[0],
        'price': temp[1]
    }
    goods_attr_list.append(v)
# 购物车属性格式化
shopping_attr_list = []
shopping_str_list = shopping.split('\n')
for item in shopping_str_list:
    temp = item.split('|')
    v = {
        'name': temp[0],
        'price': temp[1],
        'owner': temp[2]
    }
    shopping_attr_list.append(v)

# 用户登录
# ####################################### start #######################################
print('欢迎光临!!!!!!')


def login():
    quit_login = 'n'
    while quit_login != 'q':
        user_name = input('请输出用户名:')
        user_pwd = input('请输出密码:')
        return_value = '0'
        for line in user_attr_list:
            if user_name == line['name']:             # 判断是否有该用户
                user_num = int(line['num'])
                if user_num < 3:                       # 判断密码错误次数是否小于3
                    if user_pwd == line['pwd']:       # 判断密码是否正确
                        print('登录成功!')
                        line['num'] = 0               # 登录成功错误上限清0
                        return "Y", user_attr_list.index(line)                    # 登录成功标志为Y,返回索引
                    else:                             # 密码输入错误
                        user_num += 1                  # 错误上限加1
                        line['num'] = user_num
                        if user_num >= 3:
                            return_value = '2'         # 如果登陆次数大于等于3 返回值为2 直接报错退出
                            break
                        else:
                            return_value = '1'         # 返回1 报错用户名密码或错误!
                else:                                 # 如果登陆次数大于等于3 返回值为2 直接报错退出
                    return_value = '2'
                    break
            else:
                return_value = '1'
        if return_value == '1':                       # 判断返回值,报相应的错
            print('用户名密码或错误!')
            quit_login = input('按q退出,任意键继续!')
        elif return_value == '2':
            print('用户已锁定!!')
            return "N", 0
        else:
            pass
    return "N", 0
# #######################################  end  #######################################

#  功能实现
# ####################################### start #######################################
user_tuple = login()
quit_body = user_tuple[0]
user_index = user_tuple[1]
user_names = user_attr_list[user_index]["name"]
while quit_body == "Y":
    option = input('1.购物\n2.查询已购买商品\n3.查询余额\n4.充值\n5.退出\n请输入:')
    if option == '1':
        if len(goods_attr_list) % 3 == 0:
            goods_pages = len(goods_attr_list) / 3
        else:
            goods_pages = len(goods_attr_list) // 3 + 1
        user_pages = 1
        back_goods = "n"
        while back_goods != "q":
            if (user_pages >= 1) and (user_pages <= (goods_pages - 1)):
                pages_start = (user_pages - 1) * 3
                pages_end = user_pages * 3
                goods_n = goods_attr_list[pages_start:pages_end]
            elif user_pages == goods_pages:
                pages_start = (user_pages - 1) * 3
                pages_end = len(goods_attr_list)
                goods_n = goods_attr_list[pages_start:pages_end]
            for lines in goods_n:
                goods_len = goods_n.index(lines) + 1
                print(goods_len, lines["name"], lines["price"])
            print("当前页码为%d/%d" % (user_pages, goods_pages))
            while True:
                user_type = input('购买商品请按1,换页请按2,返回请按q:')
                if user_type == "1":
                    goods_num = input("请输入商品编号:")
                    if goods_num.isdigit():
                        goods_num = int(goods_num)
                        if (goods_num >= 1) and (goods_num <= 3):
                            user_balance = user_attr_list[user_index]["balance"]
                            int_balance = int(user_balance)
                            if int_balance - int(goods_n[goods_num - 1]["price"]) > 0:
                                shopping_user_list = goods_n[goods_num - 1]
                                shopping_user_list.setdefault('owner', user_names)
                                shopping_attr_list.append(shopping_user_list)
                                user_attr_list[user_index]["balance"] = \
                                    int_balance - int(goods_n[goods_num - 1]['price'])
                                print("购买成功!!!")
                            else:
                                print("余额不足,请充值!!!")
                                continue
                        else:
                            print("请正确输出!!!")
                            continue
                    else:
                        print("请正确输出!!!")
                        continue
                elif user_type == "2":
                    user_pages_text = input("请输出页码,当前页码为%d/%d:" % (user_pages, goods_pages))
                    if user_pages_text.isdigit():
                        user_pages_text = int(user_pages_text)
                        if (user_pages_text >= 1) and (user_pages_text <= goods_pages):
                            user_pages = user_pages_text
                            break
                        else:
                            print("请输入正确的页码!!!")
                            continue
                    else:
                        print("请输入正确的页码!!!")
                        continue
                elif user_type == "q":
                    back_goods = "q"
                    break
                else:
                    print("请正确输入选项!!")
    elif option == '2':
        print("已购买列表为:")
        for lines in shopping_attr_list:
            if user_names == lines["owner"]:
                print(lines['name'], lines['price'], '元')
        while True:
            n = input("查询请按1,任意键返回:")
            if n == "1":
                v = input("请输入关键字:")
                for lines in shopping_attr_list:
                    if v in lines["name"]:
                        print(lines['name'], lines['price'], '元')
            else:
                break
    elif option == '3':
        amount = str(user_attr_list[user_index]['balance'])
        print('当前余额为:' + amount)
        option_1 = input('返回主页请按任意键,退出请按q')
        if option_1 == 'q':
            break
        else:
            continue
    elif option == '4':
        option_2 = 'n'
        while option_2 != 'q':
            money = input('请输出充值金额:')
            if money.isdigit():
                pass
            else:
                print('请正确输入!')
                continue
            option_1 = input('确认请按y,返回请按任意键!')
            if option_1 == 'y':
                money = int(money)
                user_attr_list[user_index]['balance'] = int(user_attr_list[user_index]['balance']) + money
                print('充值成功')
                option_2 = input('继续充值请按任意键,返回请按q')
            else:
                print('充值失败')
                option_2 = input('继续充值请按任意键,返回请按q')
                continue
    elif option == '5':
        print('谢谢光临!!!')
        break
    else:
        print('请正确输出选项!')
        continue
# #######################################  end  #######################################
# 用户属性格式化
db_str_list.clear()
for item in user_attr_list:
    temp = "%s|%s|%s|%s" % (item['name'], item['pwd'], item['num'], item['balance'])
    db_str_list.append(temp)
db = "\n".join(db_str_list)
# 购物车属性格式化
shopping_str_list.clear()
for item in shopping_attr_list:
    temp = "%s|%s|%s" % (item['name'], item['price'], item['owner'])
    shopping_str_list.append(temp)
shopping = "\n".join(shopping_str_list)
# 打开文件
f1 = open('db', 'w', encoding='utf-8')
f2 = open('shopping', 'w', encoding='utf-8')
# 写文件
f1.write(db)
f2.write(shopping)
# 关闭文件
f1.close()
f2.close()
posted @ 2017-05-13 11:30  BILL阳  阅读(285)  评论(0编辑  收藏  举报