【python】python 入门<1>——python词法和解析器

来源:互联网 发布:mysql分库分表策略 编辑:程序博客网 时间:2024/06/05 06:17

1. 词法分析

      1.1  注释  (#)

                  注释使用  #  开头


      1.2 编码声明

               如果第一行或者第二行的 注释 匹配     coding[=:]\s*([-\w.]+)   ,则 认为是 编码声明 ,默认编码 为  UTF-8

               推荐编码声明方式 :

# -*- coding: encoding-name -*-


栗子:

# -*- coding: utf-8 -*- def scope_test():    def do_local():        spam = "local spam"    def do_nonlocal():        nonlocal spam        spam = "nonlocal spam"    def do_global():        global spam        spam = "global spam"    spam = "test spam"    do_local()    print("After local assignment:", spam) #输出 test spam    do_nonlocal()    print("After nonlocal assignment:", spam) #输出 nonlocal spam    do_global()    print("After global assignment:", spam) #输出 nonlocal spamscope_test()print("In global scope:", spam) #输出 global spam


      1.3  显示的 行连接

                当需要换行时 , 可以使用 反斜线 (\)连接上下两行 ,且 反斜线后面不能添加注释

i.e

test.py

# -*- coding: UTF-8 -*-import syssys.stdout.write("hello 陈\ from Python %s\n" % (sys.version,))

打开 cmd , 输入  python  (test.py 的全路径即可运行)

python D:\workspace3\test.py


      1.4 隐式的行连接

                特殊情况下 , 如圆括号(( )),方括号([ ]),或者 大括号 ({ })中的表达式可以分割成多个物理行而不需要反斜线。此种换行方式下可以添加注解

i.e

# -*- coding: UTF-8 -*-import syssys.stdout.write("hello 陈\ from Python %s\n" % (sys.version ,))

      1.5 关键字

                以下的标识符被用作保留字 ,或者关键字 (注意大小写):

False      class      finally    is         returnNone       continue   for        lambda     tryTrue       def        from       nonlocal   whileand        del        global     not        withas         elif       if         or         yieldassert     else       import     passbreak      except     in         raise

                   

2.  使用 python 解析器

           打开 cmd , 输入  py | python | python<version>  ,即可打开 交互模式 。

i.e

 $  python                                                                                     Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information.                         >>> flag = True                                                                                >>> if flag:                                                                                   ...     print("flag is true!") #注意缩进                                                           ...                                                                                            flag is true!                                                                                  >>>      

      交互式输入复合语句时,最后必须跟随一个空行来表示结束(因为解析器无法猜测你什么时候已经输入最后一行)


3.  简单介绍

       3.1 作为计算器使用

             3.1  数字

i.e

>>> 2+24>>> 5/22.5>>> 2**38>>> 4+_ # 交互模式下,最后一个打印的表达式分配给变量_,即8分配给_12>>>


             3.2  字符串

                       如果字符串中只有单引号而没有双引号,就用双引号引用,否则用单引号引用 。 print()  函数生成可读性更好的输出 。
i.e

>>> '"isn\'t",she said''"isn\'t",she said'>>> print('"isn\'t",she said')"isn't",she said>>> print(r'"isn\'t",she said') # r 保持原始字符串输出"isn\'t",she said>>>

                       字符串拼接

i.e

>>> 'py' 'thon''python'>>> prefix = 'py'>>> prefix + 'thon''python'>>>

                     字符串截取

i.e

>>> word = 'hello everyone'>>> word[0]'h'>>> word[13]'e'>>> word[-1] # 倒序从 -1 开始'e'>>> word[-2]'n'>>> word[0:4]  # 包含头,不包含尾'hell'>>> word[0:5]'hello'>>> word[:5]   #空代表从头开始'hello'>>> word[0:]   #空代表一直到结尾'hello everyone'>>> word[:]  # 显示所有字符'hello everyone'>>>

字符串(Python)切割示意图 :

 +---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0   1   2   3   4   5   6-6  -5  -4  -3  -2  -1

Python 中的字符串是不能改变的 ,如果你尝试改变会报错 。


                        3.3 列表

                                 中括号中的一列用逗号分隔的值。列表可以包含不同类型的元素,但是通常一个列表中的所有元素都拥有相同的类型。

i.e

>>> words = [2,5,6,99]>>> words[2, 5, 6, 99]>>> words[-1]99>>> words + [111,222][2, 5, 6, 99, 111, 222]>>> words.append(333)  #添加新元素>>> words[2, 5, 6, 99, 333]>>> words[2:3] = [555,666] # 给切片赋值>>> words[2, 5, 555, 666, 99, 333]>>> len(words) # 列表长度6>>>

                                列表可嵌套,创建包含其他列表的列表

i.e

>>> a = [2,5,7]>>> b = [3,6,8]>>> c = [a,b]>>> c[[2, 5, 7], [3, 6, 8]]>>> c[0][2, 5, 7]>>> c[0][2]7>>>

                              输出斐波那契前几位

>>> #输出斐波那契前几位... a,b = 0,1>>> while b <10:...  print(b)...  a,b=b,a+b...112358>>>

调整输出格式 :

>>> #输出斐波那契前几位... a,b = 0,1>>> while b <10:...  print(b,end=',')...  a,b=b,a+b...1,1,2,3,5,8,>>>

4.  流程控制语句 : if  while  for 等 属于 复合语句

                              4.1   if 语句用于条件执行 :


if_stmt ::=  "if" expression ":" suite             ( "elif" expression ":" suite )*             ["else" ":" suite]
i.e:

>>> x = int(input("enter an integer:"))enter an integer:23>>> if x <0:...  print('<0')... elif x==0:...  print('=0')... else:...  print('>0')...>0>>>

  

                         4.2 while 语句用于重复执行只要表达式为 true

while_stmt ::=  "while" expression ":" suite                ["else" ":" suite]


                         4.3 for 语句用于循环集合

for_stmt ::=  "for" target_list "in" expression_list ":" suite              ["else" ":" suite]

i.e:

>>> animals = ['cat','bird','elephant']>>> for animal in animals:...  print(animal,len(animal))...cat 3bird 4elephant 8>>>
or

>>> for i in range(len(animals)):...  print(animals[i],len(animals[i]))...cat 3bird 4elephant 8>>>

                           4.4 range() 函数用于遍历数字序列

生成数字序列:

>>> for i in range(5):...  print(i)...01234>>>

从2 开始 ,到10 之前结束 ,步长为 2

>>> for i in range(2,10,2):...  print(i,end=',')...2,4,6,8,>>>

                            4.5 break  continue

break : 跳出当前循环

i.e:

>>> for n in range(2,10):...  for m in range(2,n):...   if n%m == 0:...    print(n,'equals',m,'*',n//m)...    break...  else:...   print(n,'is a prime number')...2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 equals 3 * 3>>>

continue : 继续执行下一次循环


                         4.6 pass  什么也不做

>>> while True:...     pass  # 一直等待直到手动停止(ctrl+c)...

创建最小的类

>>> class MyEmptyClass:...     pass...

                           4.7 定义函数 (def

                                    使用 def 定义一个函数,其后必须跟有函数名和以括号标明的形式参数列表。组成函数体的语句从下一行开始,且必须缩进

定义一个斐波那契函数:

>>> def fib(n):...  a,b=0,1...  while a<n:...   print(a,end=',')...   a,b=b,a+b...  print()...>>> fib(3000)0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,>>>

函数名重命名

>>> fib<function fib at 0x02E177C8>>>> f = fib>>> f(3000)0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,>>>

不打印而保存在列表中返回

>>> def fibR(n):...  result = [] #用以保存数据...  a,b = 0,1...  while a<n:...   result.append(a)...   a,b=b,a+b...  return result...>>> f100 = fibR(100)>>> f100[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]>>>

                              4.7.1 默认参数值定义函数

                                     在定义函数时,就已经对参数进行了赋值

i.e:

>>> o = 5>>> def aa(aa = o):...  print(aa)...>>> aa()5>>> o = 6>>> aa()5>>>

                                但是这在默认值是列表、字典或大部分类的实例等易变的对象的时候又有所不同。例如,下面的函数在后续调用过程中会累积传给它的参数:

>>> def list(a,l=[]):...  l.append(a)...  return l...>>> print(list(1))[1]>>> print(list(2))[1, 2]>>> print(list(3))[1, 2, 3]>>>

                          如果不需要共享,可以如下写法:

>>> def f(a,l=None):    ...  if l is None:      ...   l=[]              ...  l.append(a)        ...  return l           ...                     >>> print(f(1))         [1]                     >>> print(f(2))         [2]                     >>>                     

                   4.7.2 关键字参数

                              参数:当调用函数时 ,一个值被传递给函数(或者方法),这个值就叫做参数 。有两种类型的参数

                                   ★关键字参数(keyword argument) :在函数调用中,通过标识符指定参数 ;或者在 ** 后 通过字典传递参数

调用 complex() 函数:

complex(real=3, imag=5)complex(**{'real': 3, 'imag': 5})

                                   ★位置参数 (potional argument): 以参数列表的形式出现  或者 通过 * ,

complex(3, 5)complex(*(3, 5))

                在函数调用中,关键字参数必须跟随在位置参数的后面


5. 数据结构

      5.1 更多关于 Lists


           5.1.1 作为栈使用

           5.1.2 作为队列使用


      5.2  del 语句

               移除 列表中某个元素 ,清空列表等。


       5.3  Tuples(元组) 和序列

                      元组由逗号分割的若干值组成。元组是不可变的,元组是可嵌套的

>>> t = 12,43,'hello'>>> t(12, 43, 'hello')>>> u = t,(2,5,'everyone')>>> u((12, 43, 'hello'), (2, 5, 'everyone'))>>> t[0]12>>> t[0] = 666Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment>>>

 构造包含0个和1个元素的元组

>>> empty = () # 构造包含0个元素的元组>>> len(empty)0>>> singleton = 'hello', #构造包含1个元素的元组>>> len(singleton)1>>>

              5.4 Sets( 集合)   {  }

                       特点 :不会重复 , 没有顺序 ,

                      可操作 : 交集,并集 ,差

>>> basket = {'egg','apple','egg','orange'}>>> basket{'egg', 'orange', 'apple'}>>> 'egg' in basketTrue>>> 'pear' in basketFalse>>> a = set('aabccd')>>> b = set('bbcdde')>>> a{'a', 'b', 'c', 'd'}>>> b{'b', 'd', 'c', 'e'}>>> a-b #在 a 中不在b 中{'a'}>>> a | b # 在 a中或在b中{'b', 'a', 'e', 'd', 'c'}>>> a & b # 既在a 中又在b 中{'b', 'd', 'c'}>>> a ^ b # 在 a中或者 b中,去除同时包含的{'a', 'e'}>>>

              5.5 字典

                    无序的键值对集合 ,键必须是唯一的

>>> tel = {'jack': 4098, 'sape': 4139}>>> tel['guido'] = 4127>>> tel{'sape': 4139, 'guido': 4127, 'jack': 4098}>>> tel['jack']4098>>> del tel['sape']>>> tel['irv'] = 4127>>> tel{'guido': 4127, 'irv': 4127, 'jack': 4098}>>> list(tel.keys())['irv', 'guido', 'jack']>>> sorted(tel.keys())['guido', 'irv', 'jack']>>> 'guido' in telTrue>>> 'jack' not in telFalse

                   dict() 构造器根据键值对的序列创建字典

>>> dict([('liming',2343),('zhangsan',5632)]){'zhangsan': 5632, 'liming': 2343}>>>
                    还可以:
>>> dict(sape=4139, guido=4127, jack=4098){'jack': 4098, 'guido': 4127, 'sape': 4139}>>> {x: x**2 for x in (2, 4, 6)}{2: 4, 4: 16, 6: 36}>>>

               5.6 循环

                     循环 字典 的键 和 值 ,可以使用 items() 方法

i.e

>>> tels = {'bob':4323,'jone':8732,'lili':1974}>>> tels{'jone': 8732, 'bob': 4323, 'lili': 1974}>>> for k,v in tels.items():...  print(k,v)...jone 8732bob 4323lili 1974>>>

                     循环序列 的 index 和 value,可以使用 enumerate() 方法

i.e

>>> for i,v in enumerate([33,44,55]):...  print(i,v)...0 331 442 55>>>

 或者  使用  range() 方法

>>> for i in range(len(ints)):...  print(i,ints[i])...0 331 442 55>>>

                   循环序列的 value

i.e

>>> ints = [33,44,55]>>> for v in ints:...  print(v)...334455>>>


                    循环 两个或者两个以上的序列 , 可以使用 zip() 方法

i.e

>>> questions = ['name','color']>>> answers = ['bob','blue']>>> for q,a in zip(questions,answers):...  print('what is your {0}? it is {1}'.format(q,a))...what is your name? it is bobwhat is your color? it is blue>>>

                    倒序循环序列  ,可以使用 reversed() 方法

i.e

>>> for i in reversed([11,22,33]):...  print(i)...332211>>>

                  给序列排序后循环 , 可以使用 sorted() 方法

i.e

>>> for i in sorted([55,33,44]):...  print(i)...334455>>>

            5.7 更多关于条件

innot inisis not  仅仅针对于可变对象,比如 lists ,比较运算符优先级低于数值运算符a < b == c  级联比较 :a 小于 b 并且 b 等于cand or   短路运算符

i.e 短路运算,并赋值

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' # 分别给 三个变量赋值>>> non_null = string1 or string2 or string3 # 短路运算, string1 or string2 不为空,不再继续运算,赋值给 non_null>>> non_null'Trondheim'>>>

            Python 在表达式内部不能赋值


0 0
原创粉丝点击