python入门1-环境准备
python入门2-变量、语句、运算符、列表、元组、字典
python入门3-函数
python入门4-面向对象
python入门5-numpy
python入门6-pandas
一、环境
学习阶段建议选择2.7,相对成熟
环境变量Path:C:\Python27\;C:\Python27\Scripts;
方便cmd各地方使用python;方便pip安装组件
二、hello world
1、D盘创建文件夹、及文件:D:\python\test.py
2、编辑文件:pring "hello world"
3、cmd执行:cd D:\python python test.py
三、中文处理(python3不需要)
文件开始:#coding=utf-8
四、IDE PyCharm
快捷键
格式化:ctrl+alt+L
注释:ctrl+/ 支持多选后注释
五、变量、语句、运算符
变量是弱类型,大小写敏感,i = 10 ,
#查看对象类型
print type(i)
'''
数据类型
Number: int float complex bool
String 字符串
Tuple 元组
Sets 集合
Dictionary 字典
'''
# int
num1 = 100
print(type(num1)) # 查看类型
print(int(1.5)) # 类型转换
#complex 复数
num3 = 45.j
print(type(num3))
print(complex(1.5)) # 反向可以将int float转换为复数,反向不行
# bool True False
print(int(False)) # 0
print(int(True)) # 1
print(bool(100)) # True
print(bool(0)) # False
print(bool(-1)) # True
print(bool('')) # False 注意!!!
print(bool(' ')) # True 注意!!!
print(bool('abc')) # True
print(bool([])) # False 空字符串、空列表、空元组都为False
运算符:
**幂指数
/ 除法 11/3 = 3.6666666666666665
// 除法商 11//3 = 3
% 除法余数 11%3 = 2
&按位与(自动转二进制进行与操作,再转回来)
| 按位或
^异或(相同为0,不同为1,异性相吸)
~非(对一个数按位取反)
if 1 : 非0代表true ,0代表false
str = "hello"
str[0] 输出h
str[-1] 输出o
str[1:3] 输出el
str[1:] 输出ello
'h' in str 输出true
str * 2 输出 hellohello
分支 语句:
if a<b:
print "<"
elif a==b:
print "="
else:
print ">"
循环语句:
while i > 0:
i-=1
print i
for x in range(5):
print x
输出:0 1 2 3 4
列表推导式
# 列表推导式
# 利用其它列表创建新列表
names = ['a','b','c','d']
new_names = [name.upper() for name in names]
print(new_names)
# ['A', 'B', 'C', 'D']
a = [ i**2 for i in range(10) if i%2 !=0]
# [1, 9, 25, 49, 81]
六、列表、元组、字典、集合
列表,用方括号,有顺序
list = [ 1, 2, 3, "hello" , [0,1,2] ]
for i in list:
print i
查询 print list [ 0:3 ]
添加 list.append(" world") list.insert(索引,对象)
删除 list.remove(obj) remove第一个匹配 list.pop(index) del list[index]
修改 list[0] = 2
计数 list.count(obj)
反转 list.reverse()
长度 leng(list) 通用方法
元组,用圆括号,不能改变
tup = (0 , 1 , 2)
字典,用大括号,无序,key value,key必须唯一
dict = {"name" : "bf" , "age" : 18}
for i in dict:
print dict[i]
长度 len(dict)
拷贝 dict.copy()
清空 dict.clear()
获取1 dict.get(key) 获取不到时返回None
获取2 dict.get(key, defaultValue) 获取不到时返回defaultValue
获取3 dict['name'] 获取不到时报错
删除 del dict['key']
keys dict.keys()
for遍历字典
person = { "age":'18' , 'name':'zhangsan'}
print(person.items())
# dict_items([('age', '18'), ('name', 'zhangsan')])
for key,value in person.items():
print(key+"="+value)
# name=zhangsan
# age=18
Set集合,用大括号,自动去重复,无序,其它同列表,不支持索引
s1 = {1,2,3,1}
s2 = set( [ 3,4 ] )
print( s1 | s2 ) 并集
print( s1 & s2 ) 交集
print( s1 - s2 ) 差集