Python复习踩坑记录

一、TypeError: can only concatenate str (not “int”) to str

报错代码如下:

r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
print("status_code ==> "+r.status_code)

原因:int类型和str类型不兼容,修改即可。

print("status_code ==> "+str(r.status_code))

二、取消Pycharm语法检查

关闭拼写检查:file --> settings --> Inspections --> Spelling --> 取消勾选Typo

关闭代码风格检查:file --> settings --> Inspections --> Python --> 取消勾选PEP 8检查

三、if__name__=='__main__'

https://blog.csdn.net/anshuai_aw1/article/details/82344884

if __name__ == '__main__'的意思是:当.py文件被直接运行时,if __name__ == '__main__'之下的代码块将被运行;当.py文件以模块形式被导入时,if __name__ == '__main__'之下的代码块不被运行。

四、如何判断值为空

参考:https://www.cnblogs.com/mikeluwen/p/7422022.html

代码中经常会有变量是否为None的判断,有三种主要的写法:

if x is not None # 1
if not x # 2
if not x is None # 3

使用if not x这种写法的前提是:必须清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。if x is not None是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。

foo is None 和 foo == None的区别

如果比较相同的对象实例,is总是返回True 而 == 最终取决于 “eq()”

==只要相等,is表明要一样,同一个对象

五、通过第三方服务器发送邮件

登录qq邮箱,左上角点击设置,在账户一栏,开启POP3/SMTP服务。

在这里插入图片描述

https://www.runoob.com/python3/python3-smtp.html

六、Windows创建定时任务执行Python脚本

https://blog.csdn.net/u012849872/article/details/82719372

七、格式化时间的方式

https://www.runoob.com/python3/python3-date-time.html

#!/usr/bin/python3

import time

# 格式化成2016-03-20 11:45:39形式
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# 格式化成Sat Mar 28 22:24:24 2016形式
print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
  
# 将格式字符串转换为时间戳
a = "Sat Mar 28 22:24:24 2016"
print (time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))

# 输出结果
2020-06-06 21:44:05
Sat Jun 06 21:44:05 2020
1459175064.0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章