Python入门和基础

Python应用领域

Python可以应用于众多领域,如:数据分析、组件集成、网络服务、图像处理、数值计算和科学计算等众多领域。目前业内几乎所有大中型互联网企业都在使用Python,如:Youtube、Dropbox、BT、Quora(中国知乎)、豆瓣、知乎、Google、Yahoo!、Facebook、NASA、百度、腾讯、汽车之家、美团等。互联网公司广泛使用Python来做的事一般有:自动化运维、自动化测试、大数据分析、爬虫、Web 等。

为什么是Python而不是其他语言?

C 和 Python、Java、C#等

    C语言: 代码编译得到 机器码 ,机器码在处理器上直接执行,每一条指令控制CPU工作

其他语言: 代码编译得到 字节码 ,虚拟机执行字节码并转换成机器码再后在处理器上执行

Python 和 C  Python这门语言是由C开发而来

  对于使用:Python的类库齐全并且使用简洁,如果要实现同样的功能,Python 10行代码可以解决,C可能就需要100行甚至更多.
  对于速度:Python的运行速度相较与C,绝逼是慢了

Python 和 Java、C#等

  对于使用:Linux原装Python,其他语言没有;以上几门语言都有非常丰富的类库支持
  对于速度:Python在速度上可能稍显逊色

所以,Python和其他语言没有什么本质区别,其他区别在于:擅长某领域、人才丰富、先入为主。

Python的种类

  • Cpython

Python的官方版本,使用C语言实现,使用最为广泛,CPython实现会将源文件(py文件)转换成字节码文件(pyc文件),然后运行在Python虚拟机上。

  • Jyhton

Python的Java实现,Jython会将Python代码动态编译成Java字节码,然后在JVM上运行。

  • IronPython

Python的C#实现,IronPython将Python代码编译成C#字节码,然后在CLR上运行。(与Jython类似)

  • PyPy(特殊)

Python实现的Python,将Python的字节码字节码再编译成机器码。
RubyPython、Brython ...

Python环境 

  • Windows

1、下载安装包

    https://www.python.org/downloads/
2、安装
    默认安装路径:C:python27
3、配置环境变量
    【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【Python安装目录追加到变值值中,用 ; 分割】
    如:原来的值;C:python27,切记前面有分号
  • linux:
Linux的yum依赖自带Python,为防止错误,此处更新其实就是再安装一个Python
 1 查看默认Python版本
 2 python -V
 3  
 4 1、安装gcc,用于编译Python源码
 5     yum install gcc
 6 2、下载源码包,https://www.python.org/ftp/python/
 7 3、解压并进入源码文件
 8 4、编译安装
 9     ./configure
10     make all
11     make install
12 5、查看版本
13     /usr/local/bin/python2.7 -V
14 6、修改默认Python版本
15     mv /usr/bin/python /usr/bin/python2.6
16     ln -s /usr/local/bin/python2.7 /usr/bin/python
17 7、防止yum执行异常,修改yum使用的Python版本
18     vi /usr/bin/yum
19     将头部 #!/usr/bin/python 修改为 #!/usr/bin/python2.6
View Code

基础知识

>>在linux上直接用python执行shell命令

1 import os
2 os.system('df -h')

  • 获取到linux上的命令执行的结果
1 cmd_res = os.popen('df -h').read()
  • 打印系统环境变量

  • 数据类型

>>列表
name = [1,2,3,4,5,6]
name.insert(1,0)
name.append(7)
name.remove(4)
del name[2:4]
--修改步长
name[::2]
--判断是否在列表中
print(5 in name)
--判断次数
print (name.count(5))
--查找位置
name.index(5)
--扩展一个新的列表
name.extend(new_list)
--翻转
name.reverse()
--复制(浅拷贝,深拷贝需要用到copy模块)
name.copy()
--按照某分隔符将列表合并成字符串
'|'.join(mylist)

>>字符串
--移出空白
strip()
--切片
str.split(',')
--格式化
msg = 'hello {0},age,{1}'
msg2 = msg.formate('majh',22)

--填充
msg = 'hello'
msg.center(40,'-')
--判断是否有特殊字符
str.isalnum()

>>数据运算
>>字典
--查看
dic['name']
--添加(提供一个不存在的key即可)
dic['new_name']=123
--删除
dic.pop(key)
dic.keys()
dic.values()
--循环遍历(效率低)
for k,v in dic.items():
print(k,v)

--效率高
for key in dic:
print(key,dic[key])

>>Set 集合
无序,不重复序列
--创建
s = {1,2,3,4,5}
s = set((1,2,3,4,5))
# s1.symmetric_difference_update()
#取出s1中存在s2中不存在的,然后更新到s1中
s1.difference_update(s2)
print(s1)
#取出s1中存在s2中不存在的,s2中存在s1中不存在的,然后更新到s1中
s1.symmetric_difference_update(s2)
print(s1)

--存在就删除,不存在不报错
s.discard(111)
--存在就删除,不存在就报错
s.remove(111)
--添加
s.add(111)
--批量添加
s.update(set)

函数

1.在Python中如果不指定return返回值,默认返回None
2.函数参数
1.普通参数
2.默认参数(必须要放在参数的最后)
3.指定参数
4.* 默认将传入的参数,全部放入到元组中
5.**默认将传入的参数,全部放入到字典中
3.如果参数带*,那调用函数时会吧参数转换成元组

4.三元运算
username = 'Meek' if 1 == 2 else 'Alex'

5.内置函数
chr() #将数值转换为ascii
ord() #将ascii转换为数值

compile()
eval() #将字符串转换为Python可识别的特殊代码,然后执行
exec()
divmod(x, y) #得到x/y商和余数

isinstance('Meek', str) # 判断对象是否是某个类的实例

filter()
map()
#print(list(filter(lambda x: x > 10, range(20))))


>>文件操作
f = open('db','r') #只读
f = open('db','w') #只写,先清空
f = open('db','x') #存在报错,不存在创建一个新的
f = open('db','a') #追加
f = open('db','rb') #只读 打开的时候以二进制打开


>>装饰器:在不改变原函数功能的前提下额外的给函数增加功能
如果在某个函数上面一行加上@装饰器名称,则执行该函数时会完成以下功能:
1.将函数名作为参数传递给装饰器函数执行装饰器函数
2.将装饰器函数的返回值重新赋值给该函数
通俗理解:将该行重新赋值给装饰器的内层函数

 

字符串格式化

1、字符串格式化
>> 百分号格式化
s = '%(name)s age is %(age)d,购买金额为 %(fee).2f' %
{'name': 'Meek', 'age': 20, 'fee':232.2323}
print(s)
>>当格式化字符串中出现了百分号占位符,要显示百分号,要用两个百分号标识一个
tpl = "i am %s" % "alex"
 
tpl = "i am %s age %d" % ("alex", 18)
 
tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}
 
tpl = "percent %.2f" % 99.97623
 
tpl = "i am %(pp).2f" % {"pp": 123.425556, }
 
tpl = "i am %.2f %%" % {"pp": 123.425556, }

2.format格式化
tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')
  
tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])
  
tpl = "i am {0}, age {1}, really {0}".format("seven", 18)
  
tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])
  
tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
  
tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
  
tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
  
tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)
  
tpl = "i am {:s}, age {:d}".format(*["seven", 18])
  
tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)
  
tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})
 
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
 
tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)

 

模块

好处:
便于分类管理;
提高代码重用性;

模块导入时寻找路径依据:sys.path
自定义搜索模块:sys.path.appen('xxxx')

第三方安装:
1.pip安装
python2.7需要安装pip,然后pip install moudle_name
对于python3,自带了pip3,
2.源码安装
>下载源码
>解压,cd到压缩位置,python3 setup.py install

》》序列化--将python可识别的数据类型转换为字符串
JOSN
使用dumps和loads函数
dumps:是将python类型转换为字符串
loads:将字符串转换为python类型
注意:通过loads反序列化时必须使用双引号

》》
dump:将字符串序列化后写入到文件中
loads:从文件中读取数据然后转换为python类型
pickle

》》比较
json:跨平台,只支持基本数据类型
pickle:只支持python,支持各种类型的序列化

天气url:
http://wthrcdn.etouch.cn/weather_mini?city=北京


》》时间模块
import time
import datetime

# 返回自1970年1月1号到现在的时间戳
print(time.time())
# 返回当前时间
print(time.ctime())
# 返回时间列表
t = time.gmtime()
print(t.tm_year, t.tm_mon, t.tm_mday)
print(time.localtime())
# 把时间对象转换为时间戳
print(time.mktime(time.localtime()))
# 时间格式化
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
# 时间反格式化
print(time.strptime('2016-10-12', '%Y-%m-%d'))

print('-------datetime--------')
print(datetime.date.today())
# 输出当前时间
print(datetime.datetime.now())
# 获取10天前时间
now = datetime.datetime.now()
day = datetime.timedelta(days=-10, hours=-10, minutes=10, seconds=10)
print(now)
print(day)
print(now+day)

常用的时间计算

 1 # 返回自1970年1月1号到现在的时间戳
 2 print(time.time())
 3 # 返回当前时间
 4 print(time.ctime())
 5 # 返回时间列表
 6 t = time.gmtime()
 7 print(t.tm_year, t.tm_mon, t.tm_mday)
 8 print(time.localtime())
 9 # 把时间对象转换为时间戳
10 print(time.mktime(time.localtime()))
11 # 时间格式化
12 print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
13 # 时间反格式化
14 print(time.strptime('2016-10-12', '%Y-%m-%d'))
15 
16 print('-------datetime--------')
17 print(datetime.date.today())
18 # 输出当前时间
19 print(datetime.datetime.now())
20 # 获取10天前时间
21 now = datetime.datetime.now()
22 day = datetime.timedelta(days=-10, hours=-10, minutes=10, seconds=10)
23 print(now)
24 print(day)
25 print(now+day)
26 # 时间快速加减法
27 print(datetime.datetime.now().replace(2015,1,1))
28 t1 = datetime.datetime.now().replace(2015,1,1)
29 t2 = datetime.datetime.now()
30 print(t2-t1)
View Code

----------------------未完待续-------------------------------

 
 
 
 
 
聪明的人喜欢用思考替代行动,而勤奋的人喜欢用行动替代思考
原文地址:https://www.cnblogs.com/majh/p/5996059.html