1.简介
- 源码文件UTF-8编码,字符串是unicode
- 如果数值相同,会分配同一个空间
type(apple) #查看数据类型
print(1,2,3) #输出为1 2 3
print(1,2,3,sep=":")#输出为1:2:3
print(1,end=":")
print(2) #输出为1:2
id(pi) #查看内存地址
x,y=y,x #交换
temp = 3.14159,3,6
PI ,r,q = temp
2.字符串
str=r'hello\n' #输出为hello\n,用r或R表示,转义字符不会被转义
str='hello\"' #输出为hello"
stirng1 = 'python1'
stirng2 = "python2"
stirng1+stirng2
string1*3
int ('898') #只能转换数字
2.1索引与切片
2.1.1索引
正索引
P Y T H O N
0 1 2 3 4 5
负索引
P Y T H O N
-6 -5 -4 -3 -2 -1
2.1.2切片
左闭右开
string3='PYTHON'
string3[1:3] #YT
string3[:3]
string3[2:]
3.常用运算符
运算符 | 描述 | 例子 |
---|---|---|
/ | x/y | 20/10=2.0 |
// | 取整 | 23/20=2 |
** | x^y | 2**3=8 |
and | 若第一个数为0则返回0,否则返回第二个数 | 20 and 30=30,0 and 20=20 |
or | 若第一个数非0则返回第一个数,否则第2个 | 20 or 30=20,0 or 20=20 |
not x | True/False | not(20 and 30)=False |
4.数据结构
4.1序列
列表、元组
4.1.1创建列表
all_in_list = [0.25,'hello',true,[0.0,0.7,1.4,4.89,5.59,6.28]]
all_in_list = list('ABCD')
all_in_list = list(range(1,11))
4.1.2索引与切片
all_in_list[:3]#切片,返回是列表
all_in_list[:]
all_in_list[3]#索引,返回是值
4.1.3增
all_in_list.append(0.78)
all_in_list.append([1, 2])#整体添加到目标对象
all_in_list.extend([1, 2])#列表中的每个元素加入列表
all_in_list.insert(1, 'world')#在坐标1前面插入world
[1,2]+[3,4]
4.1.4删
all_in_list = list('ABCD')
all_in_list.remove('B')//第一个
del all_in_list[:2]
del all_in_list
4.1.5改
all_in_list[0] = 125
4.1.6查
all_in_list.index(125)//第一个
4.1.7列表推导式
x = []
for i in range(1, 11):
x.append(i)
#需要第二行和第三行全部选中
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
import math
s = [math.sin(i) for i in x_new]
x_new = [i for i in range(1, 11)]#for i in range(1, 11)是对i的解释
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sum(s)
4.2字典
只有字符串和数值可以作为键,列表不可以
dict_first = {
'the': 2,
3.4: [3.5, 4],
'hello': 'world'
}
dict_second = {i: i**2 for i in range(1, 11)}
4.3.1增
通过赋值来实现
dict_first['world'] = 2.5
dict_first.update({'hello world': 3, 4.5: [2.3, 1.2]})
4.3.2删
del dict_first['world']
4.3.3改
dict_first['the']
dict_first['the'] = 101
4.3.4查
dict_first.keys()#访问键
dict_first.values()#访问值
dict_first.items()#访问键值对
统计单词出现的频次
lyric = 'The night begin to shine, the night begin to shine'
lyric.lower()
words = lyric.split()
word_freq = {}
for word in words:
if word in word_freq.keys():
word_freq[word] += 1
else:
word_freq[word] = 1
5.控制语句
5.1条件判断
if 1 < 2:
print('hello1')
if 1 > 2:
print('hello2')
else:
print('hello world')
if 1 > 2:
pass
# 什么都不执行
elif 2 > 3:
print('123')
else:
print('null')
5.2异常处理
5.2.1try-except
即使遇到错误,不会终止程序
try:
print(hello)
except OverflowError:
print('溢出错误')
except:
print("未知错误")
5.2.2异常类型
异常名 | 异常名 |
---|---|
BaseException | RuntimeError |
Exception | NotImplementedError |
ArithmeticError | SyntaxError |
StandardError | IndentationError(缩进不对等) |
FloatingPointError | TabError |
OverflowError | SystemError |
ZeroDivisionError | TypeError |
AssertionError | ValueError |
UnboundLocalError | BytesWarning |
ReferenceError | ResourceWarning |
5.2.3考试成绩
try:
score = input("输入:")
score = float(score)#input--》str
if score >= 90:
print('A')
elif score >= 80:
print('B')
else:
print('C')
except:
print("输入的为非数值类型")
5.3循环
for i in range(10):
print(i)
s = 0
while s < 10:
print(s)
s += 1
list_1 = [1, 2, 1, 0.5, 7, -4.0, -12]
for i in list_1:#i为元素不是下标
print(i)
5.4冒泡
for i in range(len(list_1)):
for j in range(i):
if list_1[j] > list_1[i]:
list_1[j], list_1[i] = list_1[i], list_1[j]
6.函数
6.1 def
def def_mean(x):
m = 0
for i in x:
m += i
return m/len(x)
list_1 = [12, 27, 35, 46]#要有两行缩进
def_mean(x=list_1)
6.2 lambda匿名函数
q = lambda x, y_2: x ** 2 + y_2
q(2, 1)
6.3导入函数
导入常量,lambda
from test01 import def_mean, def_sum, q, pi
list_1 = [1, 2, 3, 4, 5, 6]
def_mean(list_1) * pi
7.面向对象
class Human:
def __init__(self, age, gender):#self可以换成其他
self.age = age
self.gender = gender
def sqrt(self, x):
return x ** 2
zhangfei = Human(age=23, gender='男')
8.文件
8.1读取
f = open('hello.txt', mode='r', encoding='utf-8')#have bug so add encoding
txt = f.read()
f.close() # 不关,一直被python占用
f = open('hello.txt', mode='r', encoding='utf-8')
txt = f.readlines()#列表
f.close()
9.库
pip install jieba -i https://pypi.tuna.tsinghua.edu.cn/simple/