Python作为是一种面向对象的解释型计算机程序语言,它属于脚本语言的一种。它是在Guido van Rossum 在1989年底创建的python语言。自我感觉python最伟大的杰作解释所有都是引用,也许你现在不明白我说的话,但是你慢慢学一学就可以深有体会,也巧妙的避免了指针这一令所有初学者难以接受理解的概念。python语言由很多特点:
1:python语言的特点:
1:python语言具有高级性;比如python语言中的大小可变的数组简称列表和哈希表即字典就内建于语言本身的,在核心语言中提供这些重要的构建单元,可以鼓励人们使用它们,缩短开发时间与代码量,产生出可读性更好的代码。
2:python语言是面向对象的;面向对象编程支持将特定的行为,特性以及和/或功能与它们要处理或所代表的数据结合在一起。而python语言都支持。
3:python语言具有可升级性;python语言支持你可以不断的在各个项目中完善你的代码,高级的数据结构和模块化的组件,这些特点可以让你在提升项目的范围和规模的同时,确保灵活性,一致性并缩短必要的调试时间,python也提供了基本的模块,你可以在它的基础上开发你自己的软件,当这些需要扩展和增长时,python的可插入性和模块化架构能使你的项目生机盎然和易于管理。
4:python语言具有可扩展性;即使你的项目中有大量的python代码,依旧可以扩展你的项目。
5:python语言具有可移植性;python可以运行在任何带有ANSI C编译器的平台上。
6:python语言易于学习;python关键字少,结构简单明了,语法清晰。
7:python语言易读;python语言没有其他语言的访问变量,定义代码块和进行模式匹配的命令式符号。少了很多条条框框故易于读。
8:python语言易于维护;
9:python语言健壮性好;
10:python语言具有高效的快速原型开发工具;
11:python解释器可以管理内存管理器;
12:python语言具有解释性和编译性特点;python语言是一种解释性语言,python语言是字节编译的。
2:python语言的安装:
如果你是在ubuntu系统中,系统自身已经自带了python2.7系列和python3.0系列的python软件;如果你是在windows下可以参考我的python安装教程。MAC OS自身也带有python。
3:快速入门python语言(这里以2.7为主,3.0系列有区别但是不大):
1.程序的输出与输入:用print来显示输出;程序的输入用内建函数raw_input():
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> myString = raw_input('Enter a string word:')
- Enter a string word:hello
- >>> print myString
- hello
- >>>
2:注释用#表示:
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>>
- ... myNum = raw_input('Enter a number')
- Enter a number 3
- >>> print myNum
- 3
- >>>
3:python语言中的标准算术操作符有:+,-, ×, /, //, %, ××;+; +, -, ×, /, %都是标准的操作符和Java,C, C++类似;除法有/,//两种;/它表示传统的除法,两个数都是整数的话,就取比商小的最大整数;//它表示浮点除法即正真的除法(对结果进行四舍五入);××表示乘方;python中不支持自增和自减操作符;即++和--;++n还表示是n本身;--n表示的也是n本身;
python语言中的比较操作符有:<, <=, >, >=, ==, !=, <>;其中!=和<>都表示不等于,不过<>常用;
python语言中提供了逻辑操作符 and, or, not;
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> print -3**2 + 3 * 3 - 12
- -12
- >>> print 5.3/2.1
- 2.52380952381
- >>> print 5.3//2.1
- 2.0
- >>> 4 > 2
- True
- >>> 4 <= 3
- False
- >>> 4 != 3
- True
- >>> 4.001 < 4.0011
- True
- >>> 4>2 and 3<=4
- True
- >>> 2>4 and 3<=4
- False
- >>> 2>4 or 3<=4
- True
- >>> not 2>4
- True
- >>>
4:python语言中也有为变量赋值;变量名的命名规则和C, C++, java一样,开头字符只能是字母或者下划线,其他字符可以是数字,字符,下划线_;变量的命名也是大小写敏感;赋值也是用=;支持增量赋值;但是python不需要预先声明变量类型,变量的类型和声明在变量初始化时
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> myNum = 12
- >>> myString = 'hello, world'
- >>> myPrice = 3.0
- >>> myCount = myNum * myPrice
- >>> print myNum, myString, myPrice, myCount
- 12 hello, world 3.0 36.0
- >>> print 'Prince:%f; Nums:%d; Count_Price:%f'%(myPrice, myNum, myCount)
- Prince:3.000000; Nums:12; Count_Price:36.000000
- >>> myNum+=10
- >>> myNum
- 22
- >>>
5:数值;python支持五种基本的数字类型:有符号整型(长整型,布尔值,),浮点值, 复数;其中python中的长整型和C,C++,Java的长整型还是有区别的,python的长整型受限于用户计算机的虚拟内存总数;布尔值:True或者False;整型分为十进制整型,八进制,16进制;
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> 00101
- 65
- >>> 0x0101
- 257
- >>> 0X0101
- 257
- >>> 84
- 84
- >>> 3333333999999L
- 3333333999999L
- >>> -3333339999999
- -3333339999999
- >>> 0X222abcdeL
- 573226206L
- >>> 3.1415926
- 3.1415926
- >>> True
- True
- >>> False
- False
- >>> 6.23+1.5j
- (6.23+1.5j)
- >>> 6.23+12j
- (6.23+12j)
- >>> (6.23 + 12j) + (2.3 + 11j)
- (8.530000000000001+23j)
6:字符串;python中字符串被定义为引号之间的字符集合。python支持成对的单引号,双引号,三引号(三个连续的单引号或者双引号)可以用来包含特殊字符。使用索引操作符( [ ] )和切片操作符( [ : ] )可以得到子字符串。字符串如果从头开始遍历第一个索引号为0开始,如果从后往前遍历那么最后一个索引号是-1开始;使用(+)连接两个字符串运算,使用星号(×)来进行字符串的重复。
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> myStr1 = 'Hello'
- >>> myStr2 = 'Python'
- >>> myStr1[0]
- 'H'
- >>> myStr1[-1]
- 'o'
- >>> myStr1[1:3]
- 'el'
- >>> myStr1[1:]
- 'ello'
- >>> myStr1[:4]
- 'Hell'
- >>> myStr1+myStr2
- 'HelloPython'
- >>> myStr1+' '+myStr2
- 'Hello Python'
- >>> myStr1 * 2
- 'HelloHello'
- >>> 'Python'*3
- 'PythonPythonPython'
- >>> myStr3 = ''
-
- >>> myStr3
- 'python\nis very cool'
- >>> print myStr3
- python
- is very cool
- >>>
7:列表和元组;可以将列表和元组当成普通的“数组",它能保存任意数量和任意类型的python对象。和数组一样,通过从0开始的数字索引访问元素,但是列表和元组可以存储不同类型的对象。列表用[ ],列表中的元素个数和值都可以改变;元组用( ),元组中的元素不可以修改,即元组可以看成只读的列表,但是两个元组可以连接,也可以删除整个元素值,不允许删除一个元组元素值;通过切片运算 [ ] 和[ : ]可以得到子集。
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> aList = [1, 2, 3, 4, 5]
- >>> aList
- [1, 2, 3, 4, 5]
- >>> aList[0]
- 1
- >>> aList[1:4]
- [2, 3, 4]
- >>> aList[1:]
- [2, 3, 4, 5]
- >>> aList[:4]
- [1, 2, 3, 4]
- >>> aList[0] = 6
- >>> aList
- [6, 2, 3, 4, 5]
- >>> del aList[4]
- >>> aList
- [6, 2, 3, 4]
- >>> aTuple = ('apple', 'pig', 'banana', 'C', 'C++', 'Java')
- >>> aTuple
- ('apple', 'pig', 'banana', 'C', 'C++', 'Java')
- >>> aTuple[1]
- 'pig'
- >>> aTuple[1:]
- ('pig', 'banana', 'C', 'C++', 'Java')
- >>> aTuple[:5]
- ('apple', 'pig', 'banana', 'C', 'C++')
- >>> aTuple[1:5]
- ('pig', 'banana', 'C', 'C++')
- >>> aTuple[0] = 'Python'
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- TypeError: 'tuple' object does not support item assignment
- >>>
8:字典;字典是python中的映射数据类型,工作原理像哈希表一样字典元素由键-值对(key-value)构成。几乎所有类型的python对象都可以用作键,不过一般还是以数字或者字符串为主。值可以是任意类型的python对象,字典元素用大括号包裹。
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> aDict = {'name':'xiaoxiao'}
- >>> aDict['age'] = 18
- >>> aDict
- {'age': 18, 'name': 'xiaoxiao'}
- >>> aDict['name']
- 'xiaoxiao'
- >>> for key in aDict:
- ... print key, aDict[key]
- ...
- age 18
- name xiaoxiao
- >>>
9:代码块和缩进对齐;代码块通过缩进对齐表达代码逻辑,而不使用大括号。因为没有了额外的字符,程序的可读性更高。而且缩进也可以完全表达清楚一个语句属于哪个代码块。当然代码块也可以只有一个语句组成。可以参考上面的字典的循环。
10:if语句使用;格式如下:
单个if语句:
if...else语句:
- if expression:
- if_suite
- else:
- else_suite
if...elif..else语句:
- if expression:
- if_else
- elif expression:
- elif_suite;
- else:
- else_suite
code:
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> a = 3
- >>> b = 2
- >>> if a > b:
- ... print'a大于b'
- ...
- a大于b
- >>> if a > b:
- ... print'a大于b'
- ... else:
- ... print'b大于a'
- ...
- a大于b
- >>> if a < 0:
- ... print 'a小于0'
- ... elif a < 2:
- ... print 'a小于2'
- ... else:
- ... print 'a大于2'
- ...
- a大于2
- >>>
11:while循环语句;格式如下
- while expression:
- while_expression;
code:
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> count = 0
- >>> while count < 5:
- ... print 'loop:%d' %(count)
- ... count+=1
- ...
- loop:0
- loop:1
- loop:2
- loop:3
- loop:4
- >>>
12:for循环和range( )内建函数:code:
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> aList = ['C', 'C++', 'Java', 'Python']
- >>> for item in aList:
- ... print item
- ...
- C
- C++
- Java
- Python
- >>> for items in aList:
- ... print items,
- ...
- C C++ Java Python
- >>> for nums in [1, 2, 3, 4]:
- ... print nums
- ...
- 1
- 2
- 3
- 4
- >>> for num in range(4):
- ... print num,
- ...
- 0 1 2 3
- >>> myStr = 'abcd'
- >>> for str in myStr:
- ... print str
- ...
- a
- b
- c
- d
- >>> myStr1 = 'abcde'
- >>> for i in range(len(myStr1)):
- ... print myStr1[i], '(%d)'%i
- ...
- a (0)
- b (1)
- c (2)
- d (3)
- e (4)
- >>> myStr0 = 'abc'
- >>> for i, ch in enumerate(myStr0):
- ... print ch, '(%d)' %i
- ...
- a (0)
- b (1)
- c (2)
- >>>
13:列表解析;可以在一行中使用一个for循环将所有的值放到一个列表当中,code:
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> squared = [x**2 for x in range(4)]
- >>> for i in squared:
- ... print i
- ...
- 0
- 1
- 4
- 9
- >>> sEvens = [x**2 for x in range(8) if not x % 2]
- >>>
- >>> for i in sEvens:
- ... print i
- ...
- 0
- 4
- 16
- 36
- >>>
14:文件和内建函数open(),file();格式:handle = open(file_name, access_mode = 'r');
- file_name = raw_input('Enter file name:')
- fobj = open(file_name, 'r')
- for eachLine in fobj:
- print eachLine,
- fobj.close()
15:错误和异常;python在编译时会检查语法错误,不过python也允许在程序运行时检测错误。 当遇到错误时,python解释器就会引发一个异常,并显示异常的详细信息,程序员可以根据这些信息快速定位问题并进行调试,并找出错误的解决办法。要给你的python代码添加错误检测及异常处理,只要将它们”封装“在try-except语句当中。code:
- try:
- file_name = raw_input('Enter file name:')
- fobj = open(file_name, 'r')
- for eachLine in fobj:
- print eachLine,
- fobj.close()
- except IOError, e:
- print 'file open error:', e
16:定义函数及函数的调用,函数的定义是在关键字def后面紧跟着函数的名字,再加上该函数需要的几个参数构成,函数的参数是可选的。格式为:
def function_name( [arguments] ):
"optional documentation string"
function_suite
code:
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> def say():
- ... print 'hello, python'
- ...
- >>> def addNum(num1, num2):
- ... return(num1+num2)
- ...
- >>> say()
- hello, python
- >>> addNum(1,2)
- 3
- >>> addNum('Hello', 'Python')
- 'HelloPython'
- >>> addNum((1, 2), (3, 4))
- (1, 2, 3, 4)
- >>> addNum([1, 2], [3, 4])
- [1, 2, 3, 4]
- >>>
17:函数的参数可以有一个默认值,如果提供有默认值,在函数定义中,参数以赋值语句形式提供。函数默认参数是指函数如果没有提供参数就把这个默认值当做值。code:
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> def addNum(num1 = 1, num2 = 2):
- ... return (num1+num2)
- ...
- >>> addNum()
- 3
- >>> addNum(3, 4)
- 7
- >>>
18:类;类是面向对象编程的核心,他扮演相关数据及逻辑容器的角色。它们提供了创建“真实”对象的蓝图。因为Python并不强求你以面向对象的方式编程。格式为:
class ClassName(base_class[es]):
"optional documentation string"
static_member_declarations
method_declarations
code:
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> class Operator():
- ... ''
- ... version = 1.0
- ... def __init__(self, nm = 'Peter'):
- ... ''
- ... self.name = nm
- ... print 'Create a class instance for ', nm
- ... def showversion(self):
- ... print self.version
- ... def jia(self, x1, x2):
- ... return x1 + x2
- ... def jian(self, x1, x2):
- ... return x1 - x2
- ... def cheng(self, x1, x2):
- ... return x1 * x2
- ... def chu(self, x1, x2):
- ... return x1 / x2
- ... def showname(self):
- ... ''
- ... print 'Your name is', self.name
- ... print 'My name is', self.__Class__.__name__
- ...
- >>> op1 = Operator()
- Create a class instance for Peter
- >>> op1.showversion()
- 1.0
- >>> op1.showname()
- Your name is Peter
- My name is __main__.Operator
- >>> print op1.jia(1, 2)
- 3
- >>> print op1.cheng(2, 3)
- 6
- >>>
19:模块的导入:格式为:
例如导入tensorflow模块,并起别名code:
20:访问模块函数或者访问一个模块变量:code:
a):访问模块函数code:
- $ python
- ...
- >>> import tensorflow as tf
- >>> hello = tf.constant('Hello, TensorFlow!')
- >>> sess = tf.Session()
- >>> print(sess.run(hello))
- Hello, TensorFlow!
- >>> a = tf.constant(10)
- >>> b = tf.constant(20)
- >>> print(sess.run(a + b))
- 30
b):访问模块变量code:
- Python 2.7.12 (default, Nov 19 2016, 06:48:10)
- [GCC 5.4.0 20160609] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> import sys
- >>> sys.stdout.write('Hello Python!\n')
- Hello Python!
- >>> sys.version
- '2.7.12 (default, Nov 19 2016, 06:48:10) \n[GCC 5.4.0 20160609]'
- >>> sys.platform
- 'linux2'
- >>>
21:python中实用的内建函数
- dir([obj]):显示对象属性,没有提供参数的话,显示全局变量的名字
-
- help([obj]):一种整齐美观的形式,显示对象的文档字符串,如果没有提供任何参数,则会进入交互式帮助。
-
- int(obj):将一个对象转换为整型
-
- len(obj):返回对象的长度
-
- open(fn, mode):以mode的方式打开名为fn的文件,mode有两种方式:r读的方式;w写的方式
-
- str(obj):将一个对象转换为字符串
-
- type(obj):返回对象的类型(返回的值本身又是一个type对象)
-
- raw_input(str):等待用户输入一个字符串,str参数可选,str为提示信息字符串
-
- range([start], stop, [step]):返回一个整型列表,起始值为start,结束值为stop-1, start默认值为0,step默认值为1
-
- id(obj):返回对象的地址