Python 基础语法概览

EusebiaConc 7年前
   <p>我是最近才开始接触 Python 的,之前只是听说过,但从来没有亲手用过。直到最近学习了之后,立马爱上了这个简洁优雅的语言,真后悔没早点开始学习它。</p>    <p>之前在学校学的 C/C++、Java 等现在大部分都忘得差不多了,并且也不太喜欢这些强类型语言。编写起来很麻烦,一点都不灵活。</p>    <p>用的第一个灵活的编程语言是 JavaScript,你懂的,前端必会的。现在学了 Python,感觉它比 JavaScript 更加灵活。哈哈,两个我都要了啊。</p>    <p>自认为 JavaScript 学的还不错,所以在最近学 Python 的时候发现两者之间的语法上其实是有很多的共同点的。eg:Python 的字典 vs JavaScript 的对象。并且在学习 ES6 的时候,发现里面很多新型的语法与 Python 的语法很像(比如迭代器、乘方运算符等),应该是 ES6 从 Python 这里借鉴过去的吧。 ^_^</p>    <h3>Python 简介</h3>    <p>Python是一种面向对象、 <strong>解释型</strong> 的计算机程序设计语言。它使用 <strong>缩进</strong> 来定义语句块。</p>    <p>Python的设计哲学是“优雅”、“明确”、“简单”。</p>    <pre>  <code class="language-python"># shell 下显示 Python 格言    >>> import this  The Zen of Python, by Tim Peters    Beautiful is better than ugly.  Explicit is better than implicit.  Simple is better than complex.  Complex is better than complicated.  Flat is better than nested.  Sparse is better than dense.  Readability counts.  Special cases aren't special enough to break the rules.  Although practicality beats purity.  Errors should never pass silently.  Unless explicitly silenced.  In the face of ambiguity, refuse the temptation to guess.  There should be one-- and preferably only one --obvious way to do it.  Although that way may not be obvious at first unless you're Dutch.  Now is better than never.  Although never is often better than *right* now.  If the implementation is hard to explain, it's a bad idea.  If the implementation is easy to explain, it may be a good idea.  Namespaces are one honking great idea -- let's do more of those!  </code></pre>    <p>应用领域:网络爬虫、网站开发、GUI开发、数据挖掘、机器学习、自然语言处理等。</p>    <p>小提示:在 Python shell 下,通过 help() 可查看当前变量的帮助信息(比如有哪些方法、属性等)</p>    <h3>字符编码</h3>    <ul>     <li>对于单个字符的编码,Python 提供了 ord() 函数获取字符 Unicode 编码的整数表示, chr() 函数把编码转换为对应的字符</li>    </ul>    <pre>  <code class="language-python">ord('¥')   => 65509  chr(25991)  => '文'  </code></pre>    <ul>     <li>由于 Python 的字符串类型是 str,在内存中以 Unicode 表示,一个字符对应若干个字节。如果要在网络上传输,或者保存到磁盘上,就需要把 str 变为以字节为单位的 bytes。(使用 encode() 编码 和 decode() 解码 )</li>    </ul>    <pre>  <code class="language-python">s = '死亡如风'  b = s.encode('utf-8')   print(b) => b'\xe6\xad\xbb\xe4\xba\xa1\xe5\xa6\x82\xe9\xa3\x8e'  s.encode('ascii') => 报错  b.decode('utf-8') => '死亡如风'  </code></pre>    <h3>数据类型(另起文章)</h3>    <p>下面只列出了常见的数据类型,全部数据类型 。</p>    <ul>     <li>布尔值(True、False)</li>     <li>整数(int)</li>     <li>小数(float)</li>     <li>字符串(str)</li>     <li>列表(list):类似于数组</li>     <li>元组(tuple):类似于 list,不同的是 tuple 一旦初始化,便不能再进行改动</li>     <li>集合(set):一组键的集合</li>     <li>字典(dict)一组键值对的集合,类似 JavaScript 中的对象</li>     <li>迭代器(Iterator)</li>    </ul>    <h3>操作符</h3>    <ul>     <li>普通除: / , <strong>平板除:</strong> // 。 <strong>平板除的结果只保留整数部分</strong></li>    </ul>    <pre>  <code class="language-python">5 // 2    => 2  5.0 // 2  => 2.0  </code></pre>    <ul>     <li> <p>乘方运算符: ** 。eg:2**3 = 8</p> </li>     <li> <p>赋值运算符: += 、 -= 、 **= 、 //= 、 %= 等。</p>      <ul>       <li><strong>注意:</strong> Python 中没有自减(a–)或自增(a++)运算符</li>      </ul> </li>     <li> <p>逻辑运算符: and 、 or 、 not</p> </li>     <li> <p>成员运算符: in 、 not in ,可用于字符串、list、tuple 等</p> </li>    </ul>    <pre>  <code class="language-python">'w' in 'hello world'             => True  'apple' in ['a','bbb','apple']   => True  's' not in 'abc'                 => True  </code></pre>    <ul>     <li><strong>身份运算符:</strong> is 、 is not ,用于比较两个对象的存储单元      <ul>       <li><strong>注意区分 is 与 == , is not 与 != </strong></li>       <li>is 用来判断两个变量的地址是否相同(可通过内置函数 id() 获取指定对象的地址标识符)</li>       <li>== 用来判断两个变量的值是否相同</li>      </ul> </li>    </ul>    <pre>  <code class="language-python">a = {'name':'percy'}  b = {'name':'percy'}  id(a)    => 645668157576 # 每次可能会不一样  id(b)    => 645668535560  a is b   => False  a == b   => True    c = 20  d = 20  c is d   => True  c == d   => True  </code></pre>    <ul>     <li><strong>位运算符:</strong> & (按位与)、 | (按位或)、 ^ (按位异或)、 - (按位取反)、 >> (右移)、 << (左移)</li>    </ul>    <h3>语句</h3>    <ul>     <li><strong>if语句:</strong> 当条件成立时运行语句块。经常与else, elif(相当于else if)配合使用。</li>    </ul>    <pre>  <code class="language-python">a = 5  if a > 8:      print('a > 8')  elif a < 4:      print('a < 4')  else:      print('4 <= a <= 8')  </code></pre>    <ul>     <li><strong>for…in 语句:</strong> 遍列列表、字符串、字典、集合等迭代器,依次处理迭代器中的每个元素,可配合 break 、 continue 使用</li>     <li><strong>while 语句:</strong> 当条件为真时,循环运行语句块。</li>     <li><strong>class 语句:</strong> 用于定义类型。</li>     <li><strong>def 语句:</strong> 用于定义函数和类型的方法。</li>     <li><strong>pass 语句:</strong> 表示此行为空,不运行任何操作。</li>     <li><strong>assert 语句:</strong> 又称 <strong>断言</strong> ,用于程序调适阶段时测试运行条件是否满足。</li>    </ul>    <pre>  <code class="language-python">n = int(input())  assert n != 0, 'n is zero!'    # 如果断言失败,assert 语句本身就会抛出 AssertionError  </code></pre>    <ul>     <li><strong>with 语句:</strong> Python2.6以后定义的语法,在一个场景中运行语句块。比如,运行语句块前加锁,然后在语句块运行结束后释放锁。</li>    </ul>    <pre>  <code class="language-python"># 比如使用 with 语句操作文件,可以省略写关闭文件语句    with open('1.txt','r',encoding='utf-8') as f:      content = f.read()  </code></pre>    <ul>     <li><strong>yield 语句:</strong> 在迭代器函数内使用,用于返回一个元素。自从Python 2.5版本以后。这个语句变成一个运算符。</li>     <li><strong>try 语句:</strong> 与 <strong>except</strong> , <strong>finally</strong> 配合使用处理在程序运行中出现的异常情况。</li>     <li><strong>raise 语句:</strong> 抛出一个异常。</li>    </ul>    <pre>  <code class="language-python">// 方式一  try:      10 / 0  except ZeroDivisionError as e:      print('Error: %s' % e)  finally:      print('Finally statement: 发生了某些错误')    // 方式二  try:      10 / 0  except ZeroDivisionError as e:      raise ValueError('Error: value error,哈哈')  finally:      print('Finally statement: 发生了某些错误')  </code></pre>    <ul>     <li><strong>import 语句:</strong> 导入一个模块或包。</li>    </ul>    <pre>  <code class="language-python"># 常见的引入模块的写法  import module    import module as name    from module import name    from module import name as anothername  </code></pre>    <h3>表达式</h3>    <ul>     <li>最基本的表达式(a and b、a + b、a // b 等)</li>     <li>字典、集合、列表的推导式</li>    </ul>    <pre>  <code class="language-python">[x + 3 for x in range(4)]   => [3, 4, 5, 6]  {x + 3 for x in range(4)}   => {3, 4, 5, 6}  (x + 3 for x in range(4))   => 这里变成了一个生成器对象    d = {'num'+str(x): x for x in range(4)}  d => {'num0': 0, 'num3': 3, 'num1': 1, 'num2': 2}    l = [x*x for x in range(1,11) if x%2 == 0]  l => [4, 16, 36, 64, 100]    l = [m+n for m in 'ABC' for n in 'XY']  l => ['AX', 'AY', 'BX', 'BY', 'CX', 'CY']  </code></pre>    <ul>     <li>匿名函数表达式( lambda )</li>    </ul>    <pre>  <code class="language-python">add = lambda x, y : x + y  add(1,4)  => 5  </code></pre>    <ul>     <li>Python 中的条件表达式, x if condition else y ,类似于 C 语言中的 condition ? x : y</li>    </ul>    <pre>  <code class="language-python">a = 'xxx' if {} else 'yyy'  a => 'yyy'  </code></pre>    <ul>     <li><strong>切片表达式</strong> ,主要用于切割数据,支持的数据类型有: str 、 bytes 、 list 、 tuple 等。</li>    </ul>    <pre>  <code class="language-python"># 语法 s[left:right:step]    l = list(range(1,100))  l[:]      => [1, 2 ... ,99]  l[96:]    => [97, 98, 99]  l[:3]     => [1, 2, 3]  l[3:6]    => [4, 5, 6]  l[::20]   => [1, 21, 41, 61, 81]  l[:10:2]  => [1, 3, 5, 7, 9]  </code></pre>    <pre>  <code class="language-python"># 翻转一个字符串    s = 'hello world'  s[::-1]   => 'dlrow olleh'  </code></pre>    <h3>函数</h3>    <p>为了增强代码的可读性,可以在函数后书写“文档字符串”(Documentation Strings,或者简称docstrings),用于解释函数的作用、参数的类型与意义、返回值类型与取值范围等。可以使用内置函数help()打印出函数的使用帮助。</p>    <pre>  <code class="language-python">deftest():      'Text on this line is to introduce this function'      print('A test function')        help(test)  </code></pre>    <p>函数名</p>    <p>函数名只是指向函数对象的引用。( 虽然可以更改内置函数,但是不推荐更改,所以请尽量不要使用与 Python 关键字、内置函数名名称相同的变量名 )</p>    <pre>  <code class="language-python">abs(-11)   => 11  aaa = abs  aaa(-12)   => 12  abs = 'a'  abs(-13)   => 报错  </code></pre>    <p>函数参数</p>    <ul>     <li>必选参数(缺一不可)</li>    </ul>    <pre>  <code class="language-python">defadd(a,b):      return a+b    add(1)    => 报错  add(1,2)  => 3  </code></pre>    <ul>     <li>默认参数(必选参数在前,默认参数在后)</li>    </ul>    <pre>  <code class="language-python">defadd(a,b=5):      return a+b        add(1)    => 6  add(1,2)  => 3  </code></pre>    <ul>     <li>可变参数(在传入 list、tuple 时,注意在前面加个星号)</li>    </ul>    <p>可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个 tuple。</p>    <pre>  <code class="language-python">defadd(*numbers):      print(type(numbers))       # <class 'tuple'>      sum = 0      for number in numbers:          sum += number      return sum    add(1)                => 1  add(1,2,3)            => 6  add(*[1,2,3,4,5])     => 15  add(*(11,22,33))      => 66  </code></pre>    <ul>     <li>关键字参数</li>    </ul>    <p>关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个 dict。</p>    <pre>  <code class="language-python">deffunc(**keywords):      print(keywords)        func()                    => {}  func(name='percy')        => {'name': 'percy'}  func(name='percy',age=22) => {'age': 22, 'name': 'percy'}  </code></pre>    <p>如果要限制关键字参数的名字,就可以用命名关键字参数。命名关键字参数需要一个特殊分隔符 * , * 后面的参数被视为命名关键字参数。</p>    <pre>  <code class="language-python">deffunc(*,name):      print(name)        func()                    => 报错  func(name='percy')        => percy  func(name='percy',age=22) => 报错  </code></pre>    <p>如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符 * 了。</p>    <pre>  <code class="language-python">deffunc(*numbers,name):      print(name)    func()                    => 报错  func(name='percy')        => percy  func(name='percy',age=22) => 报错  </code></pre>    <ul>     <li>上面的四种参数可以组合使用,但是要注意顺序。 参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。</li>    </ul>    <p>函数返回值</p>    <ul>     <li> <p>函数执行完毕也没有 return 语句时,自动 return None</p> </li>     <li> <p>看下面代码,函数居然可以返回多个值。。。</p> </li>    </ul>    <pre>  <code class="language-python">import random  defmove():      x = random.randrange(100) # 0-100 随机整数      y = random.randrange(100) # 0-100 随机整数      return x,y    rX,rY = move()  rX  => 54  rY  => 61  </code></pre>    <p>其实这只是一种假象,Python 函数返回的仍然是单一值,只不过这个值是一个 tuple 对象。 在语法上,返回一个 tuple 可以省略括号,而多个变量可以同时接收一个 tuple,按位置赋给对应的值 (有点像 ES6 的解构赋值,哈哈)</p>    <p>就到这儿吧,剩下的陆续更新。</p>    <p> </p>    <p>来自:http://blog.percymong.com/2017/03/21/python-basic-grammar/</p>    <p> </p>