• [带你飞]一小时带你学会Python


    1.面向的读者:

       具有Javascript经验的程序猿。

    2 快速入门
    2.1 Hello world

    安装完Python之后,打开IDLE(Python GUI) , 该程序是Python语言解释器,你写的语句能够立即运行.我们写下一句著名的程序语句:

    1 print "Hello,world!"

    并按回车.你就能看到这句被K&R引入到程序世界的名言.

    在解释器中选择"File"--"New Window" 或快捷键 Ctrl+N , 打开一个新的编辑器.写下如下语句:

    1 print "Hello,world!"
    2 raw_input("Press enter key to close this window...");

    保存为a.py文件.按F5,你就可以看到程序的运行结果了.这是Python的第二种运行方式.

    找到你保存的a.py文件,双击.也可以看到程序结果.Python的程序能够直接运行,对比Java,这是一个优势.

    2.2 国际化支持
    我们换一种方式来问候世界.新建一个编辑器并写如下代码:

    1 print "欢迎来到奥运中国!"
    2 raw_input("Press enter key to close this window...");

    在你保存代码的时候,Python会提示你是否改变文件的字符集,结果如下:

    1 # -*- coding: cp936 -*-
    2 
    3 print "欢迎来到奥运中国!"
    4 raw_input("Press enter key to close this window...");

    将该字符集改为我们更熟悉的形式:

    1 # -*- coding: GBK -*-
    2 
    3 print "欢迎来到奥运中国!" # 使用中文的例子
    4 raw_input("Press enter key to close this window...");

    程序一样运行良好.

    2.3 方便易用的计算器
    用微软附带的计算器来计数实在太麻烦了.打开Python解释器,直接进行计算:

    1 a=100.0
    2 b=201.1
    3 c=2343
    4 print (a+b+c)/c

    Python会自动帮你实现类型转换。


    2.4 字符串,ASCII和UNICODE
    可以如下打印出预定义输出格式的字符串:

    1 print """
    2 Usage: Python
    3 -Java
    4 -C++
    5 """

    结果输出:

    1 Usage: Python
    2 -Java
    3 -C++

    字符串是怎么访问的?请看这个例子:

     1 word="abcdefg"                         // 数组
     2 a=word[2]                              // 数组中的一个值
     3 print "a is: "+a
     4 b=word[1:3]                            // 数组范围,取1到2的值,但是不取最后区间的值
     5 print "b is: "+b # index 1 and 2 elements of word.
     6 c=word[:2]                             // 数组范围,从开始取到2,但是不取2的值
     7 print "c is: "+c # index 0 and 1 elements of word.
     8 d=word[0:]                             // 从头开始取到尾
     9 print "d is: "+d # All elements of word.
    10 e=word[:2]+word[2:]                    // 继续从头取到尾
    11 print "e is: "+e # All elements of word.
    12 f=word[-1]                             // 取最后一个元素“g”
    13 print "f is: "+f # The last elements of word.
    14 g=word[-4:-2]                          // 倒着取,打印“de”
    15 print "g is: "+g # index 3 and 4 elements of word.
    16 h=word[-2:]                            // 倒着取,打印“fg”
    17 print "h is: "+h # The last two elements.
    18 i=word[:-2]                            // 倒着去,打印“abcde”
    19 print "i is: "+i # Everything except the last two characters
    20 l=len(word)                            // 长度,结果为7
    21 print "Length of word is: "+ str(l)

    请注意ASCII和UNICODE字符串的区别:

    1 print "Input your Chinese name:"
    2 s=raw_input("Press enter to be continued...");
    3 print "Your name is ... : " +s;
    4 l=len(s)
    5 print "Length of your Chinese name in asc codes is:"+str(l);
    6 a=unicode(s,"GBK")
    7 l=len(a)
    8 print "I'm sorry we should use unicode char!Characters number of your Chinese 
    9 name in unicode is:"+str(l);

    2.5 使用List
    类似Java里的List,这是一种方便易用的数据类型:

     1 word=['a','b','c','d','e','f','g']
     2 a=word[2]                                                 // a is: c
     3 print "a is: "+a
     4 b=word[1:3]
     5 print "b is: "
     6 print b # index 1 and 2 elements of word.                 // ['b', 'c']
     7 c=word[:2]
     8 print "c is: "
     9 print c # index 0 and 1 elements of word.                 // ['a', 'b']
    10 d=word[0:]
    11 print "d is: "
    12 print d # All elements of word.                           // ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    13 e=word[:2]+word[2:]
    14 print "e is: "
    15 print e # All elements of word.                           // ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    16 f=word[-1]
    17 print "f is: "
    18 print f # The last elements of word.                      // g
    19 g=word[-4:-2]
    20 print "g is: "
    21 print g # index 3 and 4 elements of word.                 // ['d', 'e']
    22 h=word[-2:]
    23 print "h is: "
    24 print h # The last two elements.                          // ['f', 'g']
    25 i=word[:-2]
    26 print "i is: "
    27 print i # Everything except the last two characters       // ['a', 'b', 'c', 'd', 'e']
    28 l=len(word)
    29 print "Length of word is: "+ str(l)                       // 7
    30 print "Adds new element..."
    31 word.append('h')
    32 print word                                                // ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

    2.6 条件和循环语句

    1 # Multi-way decision
    2 x=int(raw_input("Please enter an integer:"))
    3 if x>0:
    4     print "x>0"
    5 elif x==0:
    6     print "Zero"
    7 else:
    8     print "x<0"

    while循环:

    1 x=0
    2 while (x<10):
    3     print 'x is:', x     // 需要特别注意的是:这里一定要缩进,不然会编译不过
    4     x+=1
    5 
    6 print "end!"

    for循环

    1 words=['this','is','a','A']
    2 for word in words:
    3     print word

    提示:能使用for循环,就尽量不使用while循环

    2.7 如何定义函数

    1 def hello(name):
    2     return 'hello ' + name + '!'
    3 
    4 print hello('a')

    并且,介绍一个方便好用的函数:

    函数原型:range(start, end, scan):

    参数含义:start:计数从start开始。默认是从0开始。例如range(5)等价于range(0, 5);

                  end:技术到end结束,但不包括end.例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5

                  scan:每次跳跃的间距,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)

    1 >>> range(0, 8)
    2 [0, 1, 2, 3, 4, 5, 6, 7]
    3 >>> range(-5, -2)
    4 [-5, -4, -3]
    5 >>> range(-2, -5)
    6 []
    7 >>> range(0, 6, 2)
    8 [0, 2, 4]

    我们再来试试麻烦的递归函数

    1 def foo(i):
    2     print 'the number is: ', i
    3     i+=1
    4     if i<10:
    5         foo(i)
    6     else:
    7         print 'end!'
    8 
    9 foo(0)

    打印:

     1 >>> 
     2 the number is:  0
     3 the number is:  1
     4 the number is:  2
     5 the number is:  3
     6 the number is:  4
     7 the number is:  5
     8 the number is:  6
     9 the number is:  7
    10 the number is:  8
    11 the number is:  9
    12 end!

    2.8 文件I/O

     1 spath="F:/1.txt"       
     2 f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist.
     3 f.write("First line 1.
    ")
     4 f.writelines("First line 2.")
     5 f.close()                                   // 1.txt 会被写入上面两行
     6 
     7 f=open(spath,"r") # Opens file for reading
     8 
     9 for line in f:
    10     print line
    11 
    12 f.close()


    2.9 异常处理

     1 s=raw_input("Input your age:")
     2 if s =="":
     3     raise Exception("Input must no be empty.")
     4     try:
     5         i=int(s)
     6     except ValueError:
     7         print "Could not convert data to an integer."
     8     except:
     9         print "Unknown exception!"
    10         
    11 else: # It is useful for code that must be executed if the try clause does not raise an exception
    12     print "You are ",s, "years old"
    13 
    14 print "Goodbye!"

    2.10 类和继承

    先看类的定义:

     1 _metaclass_ = type
     2 class Person:
     3     def setName(self, name):
     4         self.name = name
     5     def getName(self):
     6         return self.name
     7     def greet(self):
     8         print "hello, world. i am  %s." % self.name
     9 
    10 foo=Person()
    11 bar=Person()
    12 foo.setName('lucy')
    13 bar.setName('lili')
    14 
    15 foo.greet()
    16 bar.greet()

    为什么会有self呢?

    在c++中,this指针是隐式的,除非不得以的时候,,比如传进来的参数和类的成员变量的名字相同,或者要返回当前对象。 而python的self是显示的。而且this指针基本上不用在函数头里面。
    python是动态语言,设计出来的类和静态语言的格式不同,首先c++在类的定义(声明)时,会指定类的成员变量,比如在private:里。但是Python不行,它没法显式的说 哪个属性是自己的,而且属性还可以动态的增加,此时,一个解决方案出来了,增加self,通过self.访问的就可以做为类的属性。至于类的方法为什么要显式的写上self(我感觉,完全可以由解释器隐式添加上去),估计就是python的哲学导致的:Explicit is better than implicit.

     接下里是继承:

    在python中继承中的一些特点:
    1:在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。
    2:在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数
    3:Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。

     1 # -*- coding: utf-8 -*-
     2 _metaclass_ = type
     3 class Fruit:
     4       def __init__(self, color):
     5            self.color = color
     6            print "fruit's color: %s" % self.color
     7  
     8       def grow(self):
     9            print "grow..."
    10  
    11 class Apple(Fruit):                               #继承了父类
    12       def __init__(self, color):                  #显示调用父类的__init__方法
    13            Fruit.__init__(self, color)
    14            print "apple's color: %s" % self.color
    15  
    16 class Banana(Fruit):                              #继承了父类
    17       def __init__(self, color):                  #显示调用父类的__init__方法
    18            Fruit.__init__(self, color)
    19            print "banana's color:%s" % self.color
    20  
    21       def grow(self):                             #覆盖了父类的grow方法
    22            print "banana grow..."
    23 
    24 if __name__ == "__main__":
    25     apple = Apple("red")
    26     apple.grow()
    27     banana = Banana("yellow")
    28     banana.grow()

    结果显示:

    1 >>> 
    2 fruit's color: red
    3 apple's color: red
    4 grow...
    5 fruit's color: yellow
    6 banana's color:yellow
    7 banana grow...

    2.11 包机制
    每一个.py文件称为一个module,module之间可以互相导入.请参看以下例子:

    1 # a.py
    2 def add_func(a,b):
    3     return a+b
    1 # b.py
    2 from a import add_func # Also can be : import aprint "Import add_func from module a"
    3 print "Result of 1 plus 2 is: "
    4 print add_func(1,2)    # If using "import a" , then here should be "a.add_func"

    module可以定义在包里面。

    Python定义包的方式稍微有点古怪,假设我们有一个parent文件夹,该文件夹有一个child子文件夹.child中有一个module a.py . 如何让Python知道这个文件层次结构?很简单,每个目录都放一个名为_init_.py 的文件.该文件内容可以为空.这个层次结构如下所示:

    1 parent
    2 --__init_.py
    3 --child
    4 -- __init_.py
    5 --a.pyb.py

    那么Python如何找到我们定义的module?在标准包sys中,path属性记录了Python的包路径.你可以将之打印出来:

    1 import sys
    2 print sys.path

    通常我们可以将module的包路径放到环境变量PYTHONPATH中,该环境变量会自动添加到sys.path属性.另一种方便的方法是编程中直接指定我们的module路径到sys.path 中:

    1 import sys
    2 sys.path.append('D:\download')from parent.child.a import add_func
    3 
    4 print sys.path
    5 
    6 print "Import add_func from module a"
    7 print "Result of 1 plus 2 is: "
    8 print add_func(1,2)

    总结
    你会发现这个教程相当的简单.许多Python特性在代码中以隐含方式提出,这些特性包括:Python不需要显式声明数据类型,关键字说明,字符串函数的解释等等.你能够通过已有知识的迁移类比尽快熟悉Python,然后尽快能用它开始编程.

  • 相关阅读:
    cacti汇总流量图-将数据合并后作图
    Linux下查看磁盘与目录的容量——df、du
    Nagios
    Linux下的压缩和解压缩命令——jar
    Linux下的压缩和解压缩命令——tar
    Linux下的压缩和解压缩命令——compress/uncompress
    Linux下的压缩和解压缩命令——gzip/gunzip
    Linux下的压缩和解压缩命令——bzip2/bunzip2
    Linux下的压缩和解压缩命令——zip/unzip
    Nagios安装
  • 原文地址:https://www.cnblogs.com/hustcser/p/4244663.html
Copyright © 2020-2023  润新知