python3零碎的小知识和问题解决 持更

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34195441/article/details/88201985

1、灵活的if-else

a = 3 if False else 5

print(a)

# 与上面的方式等价
''' 
if True:
    a = 3
else:
    a = 5
'''

2、灵活的and/or

# 前面的表达式为真,才会执行后面的表达式
a = True and 3
print(a)

# 前面的表达式为假,后面的表达式不需要执行
b = False and 5
print(b)

# 前面的表达式为真,后面的表达式不需要执行
c = True or 3
print(c)

# 前面的表达式为假,才需要执行后面的表达式
d = False or 5
print(d)

3、类型判断

a = 123

# print(type(a))
# if type(a) == int:
if type(a) == type(1):
    print('整型')

# 类型判断函数,判断一个变量是否是一个类型的实例
# 是返回True,不是返回False
print(isinstance(a, int))
print(isinstance(a, str))

def test():
	pass

# 不能这样判断
# print(isinstance(test, function))

# 专门用户函数类型的判断
from inspect import isfunction
print(isfunction(test))
print(isfunction(a))

# 判断对象是否可调用
# 函数一定可以调用,但是能够调用的对象不一定都是函数
print(callable(test))
print(callable(a))

运行结果:
整型
True
False
True
False
True
False

3、Pycharm导入第三方库

https://blog.csdn.net/qq_42807924/article/details/82761568

4、从某段路径(文件夹中)取出一个文件,读取内容,进行处理,报错:

txt = open("C:\Users\lenovo\Desktop\hamlet.txt","r").read()

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

解决:加个 r ,r表示原始字符串

txt = open(r"C:\Users\lenovo\Desktop\hamlet.txt","r").read()

5、pycharm更新pip

在settngs中的project interpreter里,双击pip的箭头进行最新版本更新,或者点击添加,搜索pip,在右下方选择版本进行更新

6、python3读取文件时出现错误:

txt = open(r"C:\Users\lenovo\Desktop\三国演义.txt","r",encoding="utf-8").read()

错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 0: invalid continuation byte

解决:
(1)首先在打开文本的时候,设置其编码格式,如:open(‘1.txt’,encoding=’gbk’); 
(2)若(1)不能解决,可能是文本中出现的一些特殊符号超出了gbk的编码范围,可以选择编码范围更广的‘gb18030’,如:open(‘1.txt’,encoding=’gb18030’); 
(3)若(2)仍不能解决,说明文中出现了连‘gb18030’也无法编码的字符,可以使用‘ignore’属性进行忽略,如:open(‘1.txt’,encoding=’gb18030’,errors=‘ignore’); 
(4)还有一种常见解决方法为open(‘1.txt’).read().decode(‘gb18030’,’ignore’)

7、错误:ValueError: I/O operation on closed file.

解决:文件没有关闭

8、常用的pip命令方式有:

安装:pip install  packageName
卸载: pip uninstall packageName
更新:pip python -m pip install
列出所有过期的包:pip list --outdated  
升级某个包:pip install -upgrade xxx包名

猜你喜欢

转载自blog.csdn.net/qq_34195441/article/details/88201985