Python快速入门
一、准备工作
1.1 安装
安装 Anaconda3
安装第三方库:
- 方法一:pip install xxx.whl
- 方法二:conda install xxx
备用第三方库安装包下载链接:https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook
1.2 Notebook快捷键
执行单元格:Shift+Enter
1.3 修改文件存储路径
查看文件存储路径,默认在C盘
import os
print(os.path.abspath('.'))
二、Python基础
2.1 初识Python
print ("hello world")
Python之歌
import this
2.2 数值运算
2.2.1 基本运算
print(10/3)
print(2**3)
print(1.3e5)
print(1.3e-5)
print(0xFF)
运行结果:
3.3333333333333335
8
130000.0
1.3e-05
255
2.2.2 常用类型
- int
- float
- str
- bool
定义变量不需要指定变量类型
a = 1
print(type(a))
a = 1.5
print(type(a))
b = '1.5'
print(type(b))
c = 1 < a < 2
print(c)
print(type(c))
运行结果:
<class ‘int’>
<class ‘float’>
<class ‘str’>
True
<class ‘bool’>
2.2.2类型转换
b = int(a)
c = float(a)
d = str(a)
a = 1.5
b = int(a)
print(b)
print(type(b))
运行结果:
1
<class ‘int’>
2.2.3 函数
- abs
- round
- min
- max
min(2,3,4,5)
max(2,3,4,5)
2.3 字符串操作
- len
- split
- join
- replace
- upper
- lower
- strip
- lstrip
- rstrip
- format
a = 'hello'
print(a)
b = 'hello' + 'python'
print(b)
print(a*3)
print(len(a))
c = '1 2 3 4 5'
print(c.split())
d = '1,2,3,4,5'
print(d.split(','))
e = ''
print(e.join(d))
print(b.replace('python','world'))
print(b)
f = 'aBc'
print(f.upper())
print(f.lower())
g = ' hello '
print(g.strip())
print(g.lstrip())
print(g.rstrip())
运行结果:
hello
hellopython
hellohellohello
5
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]
1,2,3,4,5
helloworld
hellopython
ABC
abc
hello
hello
hello
print('{} {} {}'.format("a","b","c"))
print('{2} {1} {0}'.format("a","b","c"))
print('{a} {b} {c}'.format(a=1,b=2,c=3))
a = "a"
b = 4.5
c = 1
print('%s %f %d' % (a,b,c))
a b c
c b a
1 2 3
a 4.500000 1
2.4 索引&切片
- 从前数第一个索引为0
- 从后数第一个索引为-1
- 切片
:
左闭右开
name = 'My name is Zoie'
print(name[0])
print(name[-1])
print(name[0:7])
print(name[:2])
print(name[3:-3])
print(name[-4:])
print(name[:])
print(name[::2])
运行结果:
M
e
My name
My
name is Z
Zoie
My name is Zoie
M aei oe
2.5 列表list
- 可以存放任何类型
- 长度无限制
- 可索引
- len
- del
- [not] in
- count
- index
- append
- insert
- remove
- pop
- sort 默认升序
sort(reverse=True) 降序
sort(reverse=False) 升序序 - sorted
- reverse
list1 = []
print(type(list1))
list2 = [1,'abc',3.5]
print(list2)
list3 = list()
print(list3)
list4 = list([1,'abc',3.5])
print(list4)
print(len(list4))
a = [123,456]
b = ['abc','def']
print(a+b)
print(a*3)
a[0] = 789
print(a)
a[:] = [0,1,'abc',2,3,4,5,6,7,8,9]
print(a)
del a[1]
print(a)
del a[6:]
print(a)
print('abc' in a)
print('abc' not in a)
<class ‘list’>
[1, ‘abc’, 3.5]
[]
[1, ‘abc’, 3.5]
3
[123, 456, ‘abc’, ‘def’]
[123, 456, 123, 456, 123, 456]
[789, 456]
[0, 1, ‘abc’, 2, 3, 4, 5, 6, 7, 8, 9]
[0, ‘abc’, 2, 3, 4, 5, 6, 7, 8, 9]
[0, ‘abc’, 2, 3, 4, 5]
True
False
a = [1,2,[3,4]]
print(a[2])
print(a[2][1])
a = ['apple','apple','1']
print(a.count('apple'))
print(a.index('1'))
a.append('abc')
print(a)
a.append(['a','b'])
print(a)
a.insert(1,'python')