注释
# 注释
下载库
$ pip install 库名
导库
import math
from math import *
输入(等待输入并返回字符串类型)
input()
输出
print("人生苦短,我用python")
变量
name = 'lisa'
查看类型
type(1)
条件 and or not
if a==b or a==c:
print()
print()
if a==c and b==c:
print()
elif not b==c:
print()
else:
print()
函数和方法的区别
对象.方法()
函数()
列表(序列结构)
a = ['apple','banana']
字典(映射结构)
a = {'张伟':'12345678910'}
# 由于key的类型必须为不可变类型,可以用元组类型作为key
b = {('张伟',7):'12345678910',('张伟',25):'01987654321',('张伟',26):'21379192731'}
循环
#列表
for item in items:
#字典
for key,value in items:
# for(int i=1, i<101, i=i+2)
for i in range(1,101,2)
字符串的format方法
定义函数
def 函数名 ():
return a
两个除号相当于c语言的除号,会向下取整
类
class 类名(父类):
文件
f = open('./data.doc', 'r', encoding='UTF-8')
print(f.read(10))
print(f.readline())
print(f.readlines())
f.close()
# 如果想防止忘记close,但是三思使用w模式会清空内容
with open('./data.doc', 'w', encoding='UTF-8') as f:
f.write('hello world!')
# 如果不想清空内容,而是追加内容,用a
with open('./data.doc', 'a', encoding='UTF-8') as f:
# a和w模式都不能读取内容,如果想要同时读写,使用r+
with open('./data.doc', 'r+', encoding='UTF-8') as f:
异常捕捉(短路)
try:
#code
except ZeroDivisionError:
#捕捉到ZeroDivisionError时运行
except:
#捕捉到其他错误时运行
else:
#没有错误时运行
finally:
#结束时无论有无错误都运行
测试(assert 断言)
assert 1+1>3
assert 1/0==1
#由于断言到false时程序会终止,所以测试最好使用unittest库