基础知识:
课前练习:
s = ”a boy,a girl. glory roay is glory”
#1判断glory和a个出现了几次
s = "a boy,a girl. glory roay is glory"
b=s.split()
def str_count(x):
res=0
for i in b:
if x in i:
res+=1
return res
print(str_count("a"))
print(str_count("glory"))
D:\>py b.py
3
2
#可变参数
def judeg_str(*arg):
result = False
for i in agr:
if not isinstance(i,str):
return result
return result
judge_str(['age','sdf11'])
#2一句话里面删除所有的a
b=""
s = "a boy,a girl. glory roay is glory"
for i in s:
if i != "a":
b+=i
print(b)
D:\>py b.py
boy, girl. glory roy is glory
知识点:s.replace()
>>> s = "a boy,a girl. glory roay is glory"
>>> s.replace("a","")
' boy, girl. glory roy is glory'
#3统计一句话话每个字母出现的次数,使用字典
#1
s = "a boy,a girl. glory roay is glory"
b={}
for i in s:
b[i]=s.count(i)
print(b)
D:\>py b.py
{'a': 3, ' ': 6, 'b': 1, 'o': 4, 'y': 4, ',': 1, 'g': 3, 'i': 2, 'r': 4, 'l': 3, '.': 1, 's': 1}
#2
b={}
s = "a boy,a girl. glory roay is glory"
for i in s:
if i in b.keys():
b[i]=b[i]+1
else:
b[i]=1
print(b)
D:\>py b.py
{'a': 3, ' ': 6, 'b': 1, 'o': 4, 'y': 4, ',': 1, 'g': 3, 'i': 2, 'r': 4, 'l': 3, '.': 1, 's': 1}
默认python编辑器是使用Cpython
Jpython,可以用python代码调用java代码(场景:java已经实现了所有功能,不需要重新写入。)
Lronpython,微软.net使用
Python执行平台:win、mac、Linux
编码和解码(encode、decode):
Python操作的str类型(Unicode)
咋文件中保存的类型bytes类型
Unicode ---通过encode函数编码--->bytes类型
bytes类型----通过decode函数解码---.>unicode
文件写入前的声明
文件写入(保存磁盘时):
需要先声明文件保存格式,防止编译器或磁盘文件存储格式与文件报错格式不符
#encoding=gbk
如果当文件格式与编辑器不符,执行时:
>>> import sys
>>> dir(sys)
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_framework', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']
>>> sys.getdefaultencoding()
'utf-8'
注意事项:
中文没办法使用type判断类型
>>> '中国'.encode('gbk')
b'\xd6\xd0\xb9\xfa'
>>> print('中国'.encode('gbk'))
b'\xd6\xd0\xb9\xfa'
>>> b'a'
b'a'
>>> type(b'a')
<class 'bytes'>
>>> type(b'中国')
File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters. #中文不可以使用type判断类型
知识点:
编码后内存地址解码:
>>> b'\xd6\xd0\xb9\xfa'.decode('gbk')
'中国'
练习:
1、 把gbk的bytes类型转换成utf-8的bytes类型
#1
>>> import chardet
>>> chardet.detect("中国".encode('gbk').decode('gbk').encode('utf-8'))
{'encoding': 'utf-8', 'confidence': 0.7525, 'language': ''}
关于内存泄漏:
文件被打开不关闭,在内存不够时会存在内场泄漏。
结束一个py程序里面的所有文件内容都会得到释放,但是一个服务端的进程会一直执行,如果服务端的内存足够大,会导致文件打开(句柄)的个数上限,上限的值是65535个数。
结果就是导致服务端崩溃
write():#写入内存中,内场读到一定量(4K)也会写入磁盘
知识点:4K对齐,系统存储的最小空间就是4K,哪怕只有一个字节
fp.flush():#强制写入磁盘
常量:
‘’’
保证这个变量的值不会因为其他操作从而改变他的值
‘’’
1、const文件内容:
#encoding='utf-8'
#Filename:const.py
#定义一个常量的类实现常量的功能
#
#改类定义一个方法__setattr()__,和一个异常ConstError,ConstError类基础
#自类TypeError,通过调用类自带的字典__dic__,判断定义的常量是否包含在字典中。
#如果字典中包含此变量,将抛出异常,否则,给新创建的常量赋值。
#最后两行代码的作用是把const类注册到sys.modules这个全局字典中。
class _const(object):
class ConstError(TypeError):pass
def __setattr__(self,name,value):
if name in self.__dict__:
raise self.ConstError
self.__dict__[name] = value
import sys
sys.modules[__name__] = _const()
print(__name__)
print(_const())
2、b.py文件内容
import const
const.mageic = 23
print(const.mageic)
const.mageic = 33
b.py调用文件结果:D:\>py b.py
const
<const._const object at 0x0000029BC05C8278>
23
Traceback (most recent call last):
File "b.py", line 4, in <module>
const.mageic = 33 #b.py文件中const.mageic变量重新传入33这个值,
结果抛出异常,表示这个变量值为常量
File "D:\const.py", line 15, in __setattr__
raise self.ConstError
const.ConstError
数字类型:
1、Int整数:
>>> a = 1
>>> type(a)
<class 'int'>
2、Float小数:
>>> b=1.2
>>> type(b)
<class 'float'>
3、Complex复数:
>>> c = 1+1j
>>> type(c)
<class 'complex'>
4、科学>>> 1e10
10000000000.0
>>> 1e-10
1e-10法
其他:
>>> True +1
2
>>> False +1
1
与或非:
1、判断为True
判断-1是否为:True
bool(-1)
>>> bool(-1)
True
>>> bool(' ') #空格为True
True
2、 判断为False
‘’‘’
空或0
‘’‘
>>> bool(0)
False
>>> bool([])
False
>>> bool('')
False
>>> bool({})
False
>>> bool(())
False
>>> bool(None)
False
变量:
‘’’
区分大小写
‘’’
>>> A = 1
>>> a = 2
>>> a
2
>>> A
1
1、变量交换:
>>> A = 1
>>> a = 2
>>> a
2
>>> A
1
>>> a,A = 1,2
>>> a
1
>>> A
2
2、特殊赋值:
>>> a=b=c=1
>>> a
1
>>> b
1
>>> c
1
对象:
‘’’
简单来说就是个类:
类=数据+方法
‘’’
Python所有都是对象,有数据有方法
例如:
>>> a=1
>>> type(a)
<class 'int'>
>>> type(len)
<class 'builtin_function_or_method'>
>>> len('abc')
3
>>> len
<built-in function len>
保留字:
python内置函数__builtins__:
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
什么时候需要缩进:相关的一组逻辑关系
‘’’
如:while for if else with...as try except class def。。。等。
‘’’
一行写多个python语句,以;分号符进行分割
>>> print("hello");print('line');print('world!')
hello
line
world!
编码规范:
1、 函数尽量使用英文命名,动名词中间加_下划线去命名 例如:upper_letter()
2、 注释一般解释这个功能使用情况
3、 代码行不要太长,每行不要超过80个字符
4、 不要添加多余的空格
5、 定义的函数空两行
6、 类下面定义的函数空一行
7、 方法和方法之间空一行
8、 一个函数只做一件事
9、 类命名驼峰命名,开始字母大写 例如:CherkMailContet(object)
原码、反码和补码:
‘’’
正数的原码、反码、补码都是一个数
以下是针对负数:
原码:
如果机器字长为n,那么一个数的原码就是一个n位的二进制数,其中最高位为符号位:正整数为0,负数为1。剩下的n-1位表示改数的绝对值
反码:
反码就是在原码的基础上,符号位不变其他位按位取反(就是0变1,1变0)就可以了。
补码:
补码也非常的简单就是在反码的基础上按照正常的加法运算加1
‘’’