初学python之快速入门(一)

       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]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> myString = raw_input('Enter a string word:')  
  5. Enter a string word:hello  
  6. >>> print myString  
  7. hello  
  8. >>>   

       2:注释用#表示:

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> # input a number  
  5. ... myNum = raw_input('Enter a number'#input a number  
  6. Enter a number 3  
  7. >>> print myNum  
  8.  3  
  9. >>>   

     3:python语言中的标准算术操作符有:+,-, ×, /, //, %, ××;+; +, -, ×, /, %都是标准的操作符和Java,C, C++类似;除法有/,//两种;/它表示传统的除法,两个数都是整数的话,就取比商小的最大整数;//它表示浮点除法即正真的除法(对结果进行四舍五入);××表示乘方;python中不支持自增和自减操作符;即++和--;++n还表示是n本身;--n表示的也是n本身;

        python语言中的比较操作符有:<,  <=,  >,  >=,  ==,   !=,   <>;其中!=和<>都表示不等于,不过<>常用;

        python语言中提供了逻辑操作符 and, or,  not;

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> print -3**2 + 3 * 3 - 12  
  5. -12  
  6. >>> print 5.3/2.1  
  7. 2.52380952381  
  8. >>> print 5.3//2.1  
  9. 2.0  
  10. >>> 4 > 2  
  11. True  
  12. >>> 4 <= 3  
  13. False  
  14. >>> 4 != 3  
  15. True  
  16. >>> 4.001 < 4.0011  
  17. True  
  18. >>> 4>2 and 3<=4  
  19. True  
  20. >>> 2>4 and 3<=4  
  21. False  
  22. >>> 2>4 or 3<=4  
  23. True  
  24. >>> not 2>4  
  25. True  
  26. >>>   

     4:python语言中也有为变量赋值;变量名的命名规则和C, C++, java一样,开头字符只能是字母或者下划线,其他字符可以是数字,字符,下划线_;变量的命名也是大小写敏感;赋值也是用=;支持增量赋值;但是python不需要预先声明变量类型,变量的类型和声明在变量初始化时

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> myNum = 12  
  5. >>> myString = 'hello, world'  
  6. >>> myPrice = 3.0  
  7. >>> myCount = myNum * myPrice  
  8. >>> print myNum, myString, myPrice, myCount  
  9. 12 hello, world 3.0 36.0  
  10. >>> print 'Prince:%f; Nums:%d; Count_Price:%f'%(myPrice, myNum, myCount)  
  11. Prince:3.000000; Nums:12; Count_Price:36.000000  
  12. >>> myNum+=10  
  13. >>> myNum  
  14. 22  
  15. >>>   

     5:数值;python支持五种基本的数字类型:有符号整型(长整型,布尔值,),浮点值, 复数;其中python中的长整型和C,C++,Java的长整型还是有区别的,python的长整型受限于用户计算机的虚拟内存总数;布尔值:True或者False;整型分为十进制整型,八进制,16进制;

    

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> 00101 #八进制  
  5. 65  
  6. >>> 0x0101#十六进制  int型  
  7. 257  
  8. >>> 0X0101 #十六进制  int型  
  9. 257  
  10. >>> 84 #decimal 十进制  int型  
  11. 84  
  12. >>> 3333333999999L #长整型  
  13. 3333333999999L  
  14. >>> -3333339999999  #长整型  
  15. -3333339999999  
  16. >>> 0X222abcdeL  #长整型  
  17. 573226206L  
  18. >>> 3.1415926  #浮点数  
  19. 3.1415926  
  20. >>> True  #bool值  
  21. True  
  22. >>> False #bool值  
  23. False  
  24. >>> 6.23+1.5j  
  25. (6.23+1.5j)  
  26. >>> 6.23+12j  #复数  
  27. (6.23+12j)  
  28. >>> (6.23 + 12j) + (2.3 + 11j)  
  29. (8.530000000000001+23j)  

     6:字符串;python中字符串被定义为引号之间的字符集合。python支持成对的单引号,双引号,三引号(三个连续的单引号或者双引号)可以用来包含特殊字符。使用索引操作符( [   ] )和切片操作符( [  :   ] )可以得到子字符串。字符串如果从头开始遍历第一个索引号为0开始,如果从后往前遍历那么最后一个索引号是-1开始;使用(+)连接两个字符串运算,使用星号(×)来进行字符串的重复。

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> myStr1 = 'Hello'  
  5. >>> myStr2 = 'Python'  
  6. >>> myStr1[0]  
  7. 'H'  
  8. >>> myStr1[-1]  
  9. 'o'  
  10. >>> myStr1[1:3]  
  11. 'el'  
  12. >>> myStr1[1:]  
  13. 'ello'  
  14. >>> myStr1[:4]  
  15. 'Hell'  
  16. >>> myStr1+myStr2  
  17. 'HelloPython'  
  18. >>> myStr1+'  '+myStr2  
  19. 'Hello  Python'  
  20. >>> myStr1 * 2  
  21. 'HelloHello'  
  22. >>> 'Python'*3  
  23. 'PythonPythonPython'  
  24. >>> myStr3 = '''''python 
  25. ... is very cool'''  
  26. >>> myStr3  
  27. 'python\nis very cool'  
  28. >>> print myStr3  
  29. python  
  30. is very cool  
  31. >>>   

      7:列表和元组;可以将列表和元组当成普通的“数组",它能保存任意数量和任意类型的python对象。和数组一样,通过从0开始的数字索引访问元素,但是列表和元组可以存储不同类型的对象。列表用[   ],列表中的元素个数和值都可以改变;元组用(   ),元组中的元素不可以修改,即元组可以看成只读的列表,但是两个元组可以连接,也可以删除整个元素值,不允许删除一个元组元素值;通过切片运算 [  ] 和[ : ]可以得到子集。

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> aList = [12345]  
  5. >>> aList  
  6. [12345]  
  7. >>> aList[0]  
  8. 1  
  9. >>> aList[1:4]  
  10. [234]  
  11. >>> aList[1:]  
  12. [2345]  
  13. >>> aList[:4]  
  14. [1234]  
  15. >>> aList[0] = 6  
  16. >>> aList  
  17. [62345]  
  18. >>> del aList[4]  
  19. >>> aList  
  20. [6234]  
  21. >>> aTuple = ('apple''pig''banana''C''C++''Java')  
  22. >>> aTuple  
  23. ('apple''pig''banana''C''C++''Java')  
  24. >>> aTuple[1]  
  25. 'pig'  
  26. >>> aTuple[1:]  
  27. ('pig''banana''C''C++''Java')  
  28. >>> aTuple[:5]  
  29. ('apple''pig''banana''C''C++')  
  30. >>> aTuple[1:5]  
  31. ('pig''banana''C''C++')  
  32. >>> aTuple[0] = 'Python'  
  33. Traceback (most recent call last):  
  34.   File "<stdin>", line 1in <module>  
  35. TypeError: 'tuple' object does not support item assignment  
  36. >>>   

       8:字典;字典是python中的映射数据类型,工作原理像哈希表一样字典元素由键-值对(key-value)构成。几乎所有类型的python对象都可以用作键,不过一般还是以数字或者字符串为主。值可以是任意类型的python对象,字典元素用大括号包裹。

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> aDict = {'name':'xiaoxiao'}  #创建字典  
  5. >>> aDict['age'] = 18  #给字典里添加元素  
  6. >>> aDict  
  7. {'age'18'name''xiaoxiao'}  
  8. >>> aDict['name']  
  9. 'xiaoxiao'  
  10. >>> for key in aDict:  
  11. ...     print key, aDict[key]  
  12. ...   
  13. age 18  
  14. name xiaoxiao  
  15. >>>   

       9:代码块和缩进对齐;代码块通过缩进对齐表达代码逻辑,而不使用大括号。因为没有了额外的字符,程序的可读性更高。而且缩进也可以完全表达清楚一个语句属于哪个代码块。当然代码块也可以只有一个语句组成。可以参考上面的字典的循环。

      10:if语句使用;格式如下:

      单个if语句:

[python]  view plain  copy
  1. if expression:  
  2.     if_suite  
     if...else语句:

[python]  view plain  copy
  1. if expression:  
  2.     if_suite  
  3. else:  
  4.     else_suite  
    if...elif..else语句:
[python]  view plain  copy
  1. if expression:  
  2.     if_else  
  3. elif expression:  
  4.     elif_suite;  
  5. else:  
  6.     else_suite  
code:

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> a = 3  
  5. >>> b = 2  
  6. >>> if a > b:  
  7. ...     print'a大于b'  
  8. ...   
  9. a大于b  
  10. >>> if a > b:  
  11. ...     print'a大于b'  
  12. ... else:  
  13. ...     print'b大于a'  
  14. ...   
  15. a大于b  
  16. >>> if a < 0:  
  17. ...     print 'a小于0'  
  18. ... elif a < 2:  
  19. ...     print 'a小于2'  
  20. ... else:  
  21. ...     print 'a大于2'  
  22. ...   
  23. a大于2  
  24. >>>   

       11:while循环语句;格式如下

[python]  view plain  copy
  1. while expression:  
  2.     while_expression;  

code:

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> count = 0  
  5. >>> while count < 5:  
  6. ...     print 'loop:%d' %(count)  
  7. ...     count+=1   #count++格式是没有的  
  8. ...   
  9. loop:0  
  10. loop:1  
  11. loop:2  
  12. loop:3  
  13. loop:4  
  14. >>>   
      12:for循环和range( )内建函数:code:

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> aList = ['C''C++''Java''Python']  
  5. >>> for item in aList:  
  6. ...     print item  
  7. ...   
  8. C  
  9. C++  
  10. Java  
  11. Python  
  12. >>> for items in aList:  
  13. ...     print items,  
  14. ...   
  15. C C++ Java Python  
  16. >>> for nums in [1234]:  
  17. ...     print nums  
  18. ...   
  19. 1  
  20. 2  
  21. 3  
  22. 4  
  23. >>> for num in range(4):  
  24. ...      print num,  
  25. ...   
  26. 0 1 2 3  
  27. >>> myStr = 'abcd'  
  28. >>> for str in myStr:  
  29. ...     print str  
  30. ...   
  31. a  
  32. b  
  33. c  
  34. d  
  35. >>> myStr1 = 'abcde'  
  36. >>> for i in range(len(myStr1)):  
  37. ...     print myStr1[i], '(%d)'%i  
  38. ...   
  39. a (0)  
  40. b (1)  
  41. c (2)  
  42. d (3)  
  43. e (4)  
  44. >>> myStr0 = 'abc'  
  45. >>> for i, ch in enumerate(myStr0):  #enumerate()内建函数可以即遍历元素也可以产生循环索引  
  46. ...     print ch, '(%d)' %i  
  47. ...   
  48. a (0)  
  49. b (1)  
  50. c (2)  
  51. >>>   

      13:列表解析;可以在一行中使用一个for循环将所有的值放到一个列表当中,code:

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> squared = [x**2 for x in range(4)]  
  5. >>> for i in squared:  
  6. ...     print i  
  7. ...   
  8. 0  
  9. 1  
  10. 4  
  11. 9  
  12. >>> sEvens = [x**2 for x in range(8if not x % 2]  
  13. >>>   
  14. >>> for i in sEvens:  
  15. ...     print i  
  16. ...   
  17. 0  
  18. 4  
  19. 16  
  20. 36  
  21. >>>   

      14:文件和内建函数open(),file();格式:handle = open(file_name, access_mode = 'r');

[python]  view plain  copy
  1. file_name = raw_input('Enter file name:')  
  2. fobj = open(file_name, 'r')  
  3. for eachLine in fobj:  
  4.     print eachLine,  
  5. fobj.close()  

     15:错误和异常;python在编译时会检查语法错误,不过python也允许在程序运行时检测错误。   当遇到错误时,python解释器就会引发一个异常,并显示异常的详细信息,程序员可以根据这些信息快速定位问题并进行调试,并找出错误的解决办法。要给你的python代码添加错误检测及异常处理,只要将它们”封装“在try-except语句当中。code:

[python]  view plain  copy
  1. try:  
  2.     file_name = raw_input('Enter file name:')   
  3.     fobj = open(file_name, 'r')  
  4.     for eachLine in fobj:  
  5.         print eachLine,  
  6.     fobj.close()  
  7. except IOError, e:  
  8.     print 'file open error:', e  

     16:定义函数及函数的调用,函数的定义是在关键字def后面紧跟着函数的名字,再加上该函数需要的几个参数构成,函数的参数是可选的。格式为:

def function_name( [arguments] ):

    "optional documentation string"

    function_suite

code:

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> def say():  
  5. ...     print 'hello, python'  
  6. ...   
  7. >>> def addNum(num1, num2):  
  8. ...     return(num1+num2)  
  9. ...   
  10. >>> say()  
  11. hello, python  
  12. >>> addNum(1,2)  
  13. 3  
  14. >>> addNum('Hello''Python')  
  15. 'HelloPython'  
  16. >>> addNum((12), (34))  
  17. (1234)  
  18. >>> addNum([12], [34])  
  19. [1234]  
  20. >>>   
      17:函数的参数可以有一个默认值,如果提供有默认值,在函数定义中,参数以赋值语句形式提供。函数默认参数是指函数如果没有提供参数就把这个默认值当做值。code:

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> def addNum(num1 = 1, num2 = 2):  
  5. ...     return (num1+num2)  
  6. ...   
  7. >>> addNum()  
  8. 3  
  9. >>> addNum(34)  
  10. 7  
  11. >>>   

      18:类;类是面向对象编程的核心,他扮演相关数据及逻辑容器的角色。它们提供了创建“真实”对象的蓝图。因为Python并不强求你以面向对象的方式编程。格式为:

class ClassName(base_class[es]):

    "optional documentation string"

     static_member_declarations

     method_declarations

code:

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> class Operator():  
  5. ...     '''''this is my first python class'''  
  6. ...     version = 1.0 #class (data) attribute  
  7. ...     def __init__(self, nm = 'Peter'):  
  8. ...         '''''constructor'''  
  9. ...         self.name = nm #class instance(data) attribute  
  10. ...         print 'Create a class instance for ', nm  
  11. ...     def showversion(self):  
  12. ...         print self.version  
  13. ...     def jia(self, x1, x2):  
  14. ...         return x1 + x2  
  15. ...     def jian(self, x1, x2):  
  16. ...         return x1 - x2  
  17. ...     def cheng(self, x1, x2):  
  18. ...         return x1 * x2  
  19. ...     def chu(self, x1, x2):  
  20. ...         return x1 / x2  
  21. ...     def showname(self):  
  22. ...         '''''display instance attribute and class name'''  
  23. ...         print 'Your name is'self.name  
  24. ...         print 'My name is'self.__Class__.__name__  
  25. ...   
  26. >>> op1 = Operator()  
  27. Create a class instance for  Peter  
  28. >>> op1.showversion()  
  29. 1.0  
  30. >>> op1.showname()  
  31. Your name is Peter  
  32. My name is __main__.Operator  
  33. >>> print op1.jia(12)  
  34. 3  
  35. >>> print op1.cheng(23)  
  36. 6  
  37. >>>   
         19:模块的导入:格式为:

[python]  view plain  copy
  1. import module_name  
例如导入tensorflow模块,并起别名code:

[python]  view plain  copy
  1. import tensorflow as tf  
         20:访问模块函数或者访问一个模块变量:code:

         a):访问模块函数code:

[python]  view plain  copy
  1. $ python    
  2. ...    
  3. >>> import tensorflow as tf    
  4. >>> hello = tf.constant('Hello, TensorFlow!')    
  5. >>> sess = tf.Session()    
  6. >>> print(sess.run(hello))    
  7. Hello, TensorFlow!    
  8. >>> a = tf.constant(10)    
  9. >>> b = tf.constant(20)    
  10. >>> print(sess.run(a + b))    
  11. 30    

         b):访问模块变量code:

[python]  view plain  copy
  1. Python 2.7.12 (default, Nov 19 201606:48:10)   
  2. [GCC 5.4.0 20160609] on linux2  
  3. Type "help""copyright""credits" or "license" for more information.  
  4. >>> import sys  
  5. >>> sys.stdout.write('Hello Python!\n')  
  6. Hello Python!  
  7. >>> sys.version  
  8. '2.7.12 (default, Nov 19 2016, 06:48:10) \n[GCC 5.4.0 20160609]'  
  9. >>> sys.platform  
  10. 'linux2'  
  11. >>>   
          21:python中实用的内建函数

[python]  view plain  copy
  1. dir([obj]):显示对象属性,没有提供参数的话,显示全局变量的名字  
  2.   
  3. help([obj]):一种整齐美观的形式,显示对象的文档字符串,如果没有提供任何参数,则会进入交互式帮助。  
  4.   
  5. int(obj):将一个对象转换为整型  
  6.   
  7. len(obj):返回对象的长度  
  8.   
  9. open(fn, mode):以mode的方式打开名为fn的文件,mode有两种方式:r读的方式;w写的方式  
  10.   
  11. str(obj):将一个对象转换为字符串  
  12.   
  13. type(obj):返回对象的类型(返回的值本身又是一个type对象)  
  14.   
  15. raw_input(str):等待用户输入一个字符串,str参数可选,str为提示信息字符串  
  16.   
  17. range([start], stop, [step]):返回一个整型列表,起始值为start,结束值为stop-1, start默认值为0,step默认值为1  
  18.   
  19. id(obj):返回对象的地址  
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值