Python快速入门(上)
文章目录
环境安装
Anocoda安装
相关链接
Anoconda的下载链接如下:
Anoconda Download
Anoconda的各版本安装方式如下:
Anoconda Installation
Anoconda的文档链接如下:
Anoconda Documentation
本文安装环境为macOS 10.13.6,安装版本为Anaconda2-2018.12-MacOSX-x86_64.sh
安装步骤1
-
下载对应版本。本文所下版本为Anaconda2-2018.12-MacOSX-x86_64.sh
-
打开command,使用如下命令执行下载文件
bash ~/Downloads/Anaconda2-2018.12-MacOSX-x86_64.sh
- 安装中,会弹出"In order to continue the installation process, please review the license agreement.(为继续安装,请阅读许可证协议)",按Enter阅览许可协议
- 滑到协议末尾,输入yes同意许可
- 安装中,会弹出选择安装位置,选择默认位置,默认位置为*/home/userName/anaconda*
- 安装中,会弹出*"Do you wish the installer to prepend the Anaconda install location to PATH in your /home/userName/.bash_profile ?(是否希望安装器将Anaconda的安装目录添加到.bash_profile中)"建议选择yes*
- 安装结束
- 安装器会询问你是否安装VS Code,选择yes或是no
在命令行中执行:conda info --env
输出如下:
# conda environments:
#
base * /Users/userName/anaconda3
则代表安装成功,如输出command not found
,则可能是环境配置有误,打开~/.bash_profile,加入export PATH="/<path to anaconda>/bin:$PATH"
Jupyter使用
conda默认安装了jupyter,在命令行中输入如下命令:
conda list
列出其中所有的安装包,以下是列出的jupyter安装包
jupyter 1.0.0 py37_7
jupyter_client 5.2.4 py37_0
jupyter_console 6.0.0 py37_0
jupyter_core 4.4.0 py37_0
jupyterlab 0.35.3 py37_0
jupyterlab_server 0.2.0 py37_0
输入jupyter notebook
则在网页上运行了notebook,运行效果如下:
点击New python3,则编译器运行成功,效果如下:
至此,我们便可以编译python的代码了
第一句代码
在jupyter中输入框中输入如下命令:
print('hello jupyter')
按shift+enter键运行代码,输出如下:
python基础
python特性
- python语法简单,容易理解和学习
- 跨平台,可在Windows,Mac,Linux上运行
- 可以做网站,爬虫,大数据处理,机器学习
- 拥有强大、丰富的第三方库 numpy,pandas
变量
定义
变量:代表着某个值的名称
number = 10
其中number为变量,10为值,*=*表示变量对值的引用
#语法糖 交换两个变量的值
a = 10
b = 5
a,b = b,a
print("a is {}, b is {}".format(a,b))
output: a is 5, b is 10
命名规范
- 标示符中第一个字符必须是字母表中的字母或是下划线
- 标示符名称的其他部分可以有字母,下滑线或是数字组成
- 标示符名称对大小写敏感
代码规范
- 不要使用单字符
- 变量名能清晰表达变量的意思
- 合理使用字母中间的下划线
变量类型
5种基本类型
- 字符串
str
- 数字
int float complex
- 列表
list
- 元组
tuple
- 字典
dict
范例
#数值类型
number_ten = 10
#字符串类型
string_love_python = 'python is simple'
#列表类型
list_fruit = ['apple','pen','penapple']
#字典类型
dict_color = {'red':'#FF0000','blue':'#0000FF','yellow':'#FFFF00'}
#元组类型,即不可变的列表
tuple_city = ('Mumbai','Manhattan','paris')
将上述范例用graph展示如下:
python是一种动态类型的语言,一个变量是什么类型,要看变量在运行过程中所代表的值是什么
var = 10
type(var)
output:<class 'int'>
var = [10,10,10]
type(var)
output:<class 'list'>
数值类型
基本运算
print(10+5)
output: 15
print(10-5)
output: 5
print(10*5)
output: 50
print(10 / 5)
output:2.0
#取余数
print(10 % 3)
output:1
#10的三次方
print(10 ** 3)
output:1
数值类型
number = 10
print(number)
output:10
number = number+10
print(number)
output:20
number +=10
print(number)
output:30
number -=10
print(number)
output:20
number *=10
print(number)
output:200
number /=10
print(number)
output:20.0
math模块
#引入math模块
import math
#取小于10.05143最大整数
math.floor(10.05143)
output: 10
#取大于10.05143最小整数
math.ceil(10.05143)
output: 11
#3的十次方
math.pow(3,10)
output:59049.0
#度的转换
math.radians(180)
output:3.141592653589793
math.pi
output: 3.141592653589793
#sin (pi / 2)
math.sin(math.pi/2)
output: 1.0
#最小值
min(10,5,200,180,45)
output:5
#最大值
min(10,5,200,180,45)
output:5
#求和
sum([10,5,200,180,45])
output:440
#返回两个数的相除的商和余数的元祖
divmod(10,3)
output:(3,1)
#格式化字符串format
print("不小于10.05143的最小整数为{},小于10.05143最大整数{}".format(math.ceil(10.05143),math.floor(10.05143)))
bool类型
bool类型有两个值True或者Flase
#或运算,一真为真
True or False
output: True
#和运算,同真为真
True and False
output: False
#取反运算
not False
output: True
not True
output: False
比较操作符
操作符 | 解释 |
---|---|
< | 小于 |
<= | 小于等于 |
> | 大于 |
>= | 大于 |
== | 等于 |
!= | 不等于 |
is | 是相同对象 |
字符串类型
字符串运算
line = "hello world"
print(line)
output: hello world
#\转义字符
line = "hello \' world"
print(line)
output: hello ' world
#字符串加法
line_1 = "Hello"
line_2 = " Kitty"
line_3 = line_1+line_2
print(line_3)
output:Hello Kitty
#字符串乘法
line = "Hello "
print(line*10)
output:Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
#字符串为不可变类型的变量
print(line)
output:Hello
#字符串长度
len(line)
output:6
#字符串标识符符,可以理解为一个变量的内存地址
line = "Hello"
id(line)
output:4557964824
line = "Kitty"
id(line)
output:4557965272
#指向同一引用,所以标识符相同
line_copy = line
id(line_copy)
output:4557965272
字符串切片
字符串切片:根据索引取出字符串的某一部分
line = "welcome to China"
print(line)
print(len(line))
output:welcome to China
output:16
#取前7个字符
line[0:7]
output:welcome
line[:7]
output:welcome
#取前7个字符,每两个字符一取
line[0:7:2]
output:wloe
#取后5个字符
line[-5:]
output:China
#翻转字符
line[::-1]
output:anihC ot emoclew
#字符串不可修改值
line[0] = 'W'
output:TypeError 'str' object does not support item assignment
其他常用方法
#首字母大写
line = 'welcome to China'
line.capitalize()
output:'Welcome to china'
#居中
line.center(20)
output:' welcome to China '
line.center(20,'*')
output:'**welcome to China**'
#计算字符数量
line.count('z')
output:0
line.count('e')
output:2
#首尾判断
line.startswith('wel')
output:True
line.endswith('America')
output:False
#查找函数
line.find('e')
#找到了welcome种的第一个e
output:1
#index 与find的区别是,index找不到则返回错误,find返回-1
line.index('e')
output:1
#是否小写
line.islower()
output:False
line.lower()
output:'welcome to china'
#是否大写
line.isupper()
output:False
line.upper()
output:'WELCOME TO CHINA'
#是否是标题
line.istitle()
output:False
line = ' hello world '
#去空格
line.strip()
output:'hello world'
#去左侧空格
line.lstrip()
output:'hello world '
#去右侧空格
line.rstrip()
output:'' hello world'
#交换大小写
line.swapcase()
output:' HELLO WORLD '
列表类型
列表创建
可以容纳任何类型的对象,任意数量的对象,列表时可变的类型
#创建列表
variables = [1,2,3,'one','two','three',[],[1,2]]
#创建空列表
variables = []
print(variables)
output:[]
#添加元素
variables.append(1)
variables.append(2)
print(variables)
output:[1,2]
#列表相加
variables+=[3,4]
print(variables)
output:[1, 2, 3, 4]
$列表乘以常数
variables*4
output:[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
列表切片
variables = ["Easy","chocolate","recipes","to","satisfy","your","sweet","cravings"]
#取前三个元素
variables[0:3]
output:['Easy', 'chocolate', 'recipes']
variables[:3]
output:['Easy', 'chocolate', 'recipes']
#取后两个元素
variables[-2:]
output:['sweet', 'cravings']
#翻转所有元素
variables[::-1]
output:['cravings', 'sweet', 'your', 'satisfy', 'to', 'recipes', 'chocolate', 'Easy']
增删改查
#列表相加
a = [1,2]
b = [3,4]
a+b
output:[1, 2, 3, 4]
a
output:[1,2]
#列表扩展
a.extend(b)
a
output:[1, 2, 3, 4]
#在某一索引处插入值
a.insert(0,0)
a
output:[0, 1, 2, 3, 4]
#列表长度
len(variables)
output:8
#没有返回值,而是修改了列表对象本身
variables.append('!')
variables
output:['Easy', 'chocolate', 'recipes', 'to', 'satisfy', 'your', 'sweet', 'cravings', '!']
#清空列表
variables.clear()
variables
output:[]
#列表弹出最后一项
a.pop()
a
output:[0, 1, 2, 3]
#列表弹出特定项
a.pop(0)
a
output:[1,2,3]
#列表移出特定值
a = [1,2,3,4,5]
a.remove(6)
output:ValueError: list.remove(x): x not in list
a.remove(3)
output:[1, 2, 4, 5]
#排序
variables = [6,5,1,2,4,3]
variables.sort()
output:[1,2,3,4,5,6]
#逆序
variables = [6,5,1,2,4,3]
variables.sort(reverse=True)
variables
output:[6, 5, 4, 3, 2, 1]
#是否存在
5 in variables
output:True
10 in variables
output:False
#参见上图
#列表浅复制 对复制后新的列表修改会改变原列表
variables = ["Easy","chocolate","recipes","to","satisfy","your","sweet","cravings"]
variables_new = variables
variables_new[0] = 'complex'
variables
output: ["complex","chocolate","recipes","to","satisfy","your","sweet","cravings"]
variables_new
output: ["complex","chocolate","recipes","to","satisfy","your","sweet","cravings"]
#variables与variables_new引用同一对象
id(variables)
output:4562107400
id(variables_new)
output:4562107400
#列表深复制,对复制后新的列表修改不会改变原列表 参见上图
variables = ["Easy","chocolate","recipes","to","satisfy","your","sweet","cravings"]
variables_new = variables.copy()
variables_new[0] = 'complex'
variables
output: ["Easy","chocolate","recipes","to","satisfy","your","sweet","cravings"]
variables_new
output: ["complex","chocolate","recipes","to","satisfy","your","sweet","cravings"]
#两者引用的是不同对象
id(variables)
output:4562107400
id(variables_new)
output:4561845128
元组类型
#元组类型
var_t = tuple()
type(var_t)
output:tuple
#元组查询元素个数
var = (1,2,3,4,5,[6,7,8])
var.count(1)
output:1
#查询元素位置
var.index(1)
output:0
字典类型
var = dict()
var = {}
type(var)
output:dict
#创建
var = {'coffe':'black','milk':'white','water':'alpha'}
var
output:{'coffe': 'black', 'milk': 'white', 'water': 'alpha'}
#取值
var['coffe']
output:'black'
#拉锁函数
city = ['changhun','wuhan','haikou']
province = ['jilin','hubei','hainan']
var_1 = list(zip(city,province))
var_1
output:[('changhun', 'jilin'), ('wuhan', 'hubei'), ('haikou', 'hainan')]
dict(var_1)
output:{'changhun': 'jilin', 'wuhan': 'hubei', 'haikou': 'hainan'}
a=[1,2]
b = [3,4]
c = [5,6]
list(zip(a,b,c))
output
[(1, 3, 5), (2, 4, 6)]
#由列表生成字典
students = ['devin','archer','alan','joy']
age = dict.fromkeys(students,10)
age
output:{'devin': 10, 'archer': 10, 'alan': 10, 'joy': 10}
#获取值,如果有值则返回,无值返回传入的默认值
age.get('mark',20)
output:20
#获取所有的value值
age.values()
output:dict_values([10, 10, 10, 10])
#获取所有的key值
age.keys()
output:dict_keys(['devin', 'archer', 'alan', 'joy'])
#获取所有的key-value值
age.items()
output:dict_items([('devin', 10), ('archer', 10), ('alan', 10), ('joy', 10)])
#删除操作 返回删除的key的value值
age.pop('mark')
output:10
age
output:
{'archer': 10, 'alan': 10, 'joy': 10}
#修改字典
age['joy'] = 18
age
outoput:{'archer': 10, 'alan': 10, 'joy': 18}
#设置默认值
age.setdefault('jenny',18)
output:18
age
output:{'archer': 10, 'alan': 10, 'joy': 18, 'jenny': 18}