语句块缩进

python概述

    python 简介

        python起源

        python的特点

     环境

        安装

        python运行环境

        导入tab模块

        vim编辑器使用

    python起步

        python语法结构

            语句块缩进

            程序输出

            程序输入

            注释

            文档字符串

        python变量

            变量定义

            变量赋值

            运算符

python 代码块通过缩进对齐表达代码逻辑而不是使用大括号
缩进表达一个语句属于哪个代码块
缩进风格:
    - 1 或 2:可能不够,很难确定代码语句属于哪个块
    - 8 至 10:可能太多,如果代码内嵌的层次太多,就会使得代码很难阅读
    - 4个空格:非常流行,范。罗萨姆支持的风格

注意区别:
>>> print 'hello world!'
hello world!
>>> print 'hello','world'
hello world
>>> print 'hello''world'
helloworld
>>> print 'hello'+'world'
helloworld
>>> print 'hello'+' world'
hello world

程序输入
使用raw_input()函数读取用户输入数据

>>> user = raw_input("Enter your name: ")
Enter your name: bob
>>> print "Your name is:", user
Your name is: bob
>>> i = raw_input("input a number: ")
input a number: 10
>>> i + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> i + '1'
'101'
>>> int(i) + 1
11
>>> import tab
>>> type(i)
<type 'str'>

程序输入输出小练习:
1.创建~/bin/login.py文件
2.提示用户输入用户名
3.获得到相关用户名后,将其保存在变量中
4.在屏幕上输出Welcome用户名

#!/usr/bin/env python 
user_name = raw_input("Enter the user name: " )  
print "Welcome",user_name

注释:
和大部分脚本及Unix-shell语言一样,python也是用#符号标示注释
从#开始,直到一行结束的内容都是注释
良好的注释习惯可以:
- 方便其他人了解程序功能
- 方便自己在日后读懂代码 
>>> import string
>>> help(string) # 获取帮助/使用方法

文档字符串
可以当作一种特殊的注释
在模块、类或者函数的起始添加一个字符串,起到在线文档的功能
简单的说明可以使用单引号或双引号
较长的文字说明可以使用三引号
自制模块/帮助文档
# vim /home/qihang/PycharmProjects/day01/star.py
#!/usr/bin/env python
# -- coding: utf-8 --
"""示例程序

仅仅是一个测试 只有一个函数
"""

def pstar():
    "用于打印20个型号“"
    print '*' * 20
 
 # cd /home/qihang/PycharmProjects/day01/
 # python
 >>> import star
 >>> help(star)
 Help on module star:

NAME
    star - 示例程序

FILE
    /home/qihang/PycharmProjects/day01/star.py

DESCRIPTION
    仅仅是一个测试 只有一个函数

FUNCTIONS
    pstar()
        用于打印20个型号“

注意 两种格式的差距
>>> a = '''hello
... xiaoming'''
>>> a
'hello\nxiaoming'
>>> print a
hello
xiaoming

>>> b = 'hello\nworld!'
>>> b
'hello\n world!'
>>> print b
hello
world!

变量定义

    - 第一个字符只能是大小写字母或下划线
    - 后续字符只能是大小写字母或数字或下划线
    - 区分大小写
python是动态类型语言,即不需要预先声明变量的类型
:
1、有意义(pythonstring)
2、简短(pystr)
3、多个单词之间用下划线(py_str)
4、变量用名词(phone),函数使用谓词(动词+名词) update_phone
5、类名:每个单词首字母大写(MyClass)


  变量的类型和值在赋值那一刻被初始化
  变量的赋值通过等号来执行
    >>> counter = 0 
    >>> name = 'bob'
  python也支持增量赋值
    >>> n+= 1 #等价于n = n + 1(n之前必须赋值)
    >>> n*= 1 #等价于n = n * 1
    >>> i++
  File "<stdin>", line 1
    i++
      ^
SyntaxError: invalid syntax
    python中没有 a--
    python 中的 --a 表示负号,++a 表示正号,不会是a的值发生变化。
 >>> a 
15
>>> --a
15
>>> ++a
15
>>> a--
  File "<stdin>", line 1
    a--
      ^
SyntaxError: invalid syntax
>>> a++
  File "<stdin>", line 1
    a++
      ^
SyntaxError: invalid syntax


标准算数运算符
  + - × /() //(地板除) %(求模) **(幂运算)
/(除法的注意事项)
>>> 5 / 3
1
>>> 5./ 3
1.6666666666666667
 //(地板除,取靠近商的最小值。)
 >>> print 5. //3
1.0
>>> print -5. //3
-2.0

比较运算符
  < <= > >= == != <>
  连比(尽量少用,可读性差)
    >>> 3 < 5 < 10
    True
    >>> 10 < 20 > 15
    True
    >>> 10 < 20 and 20 >15
    True
逻辑运算符
  and not or
:不用死记硬背优先级的顺序,可以依靠括号来明确定义先算那些,后算那些



  数字:基本数字类型
         - int: 有符号整数
         - long:长整数
           >>> a
           10
           >>> a = 10L
           >>> a
           10L
         - bool:布尔值
            - True:1
            - False:0
            >>> True + 1
            2
            >>> False * 10
            0
            >>> type(True)
            <type 'bool'>

         - float:浮点数
         - complex:复数
       数字的表达方式
         python默认以十进制数显示
         数字以0开头表示为8进制数
         数字以0x开头表示16进制数
         数字以0b或0B开头表示2进制数
         >>> 11
         11
         >>> 011
         9
         >>> 0x11
         17
         >>> 0b11
         3
         进制之间的转换,是个问题(2进制转16进制的技巧:四位二进制换成一位16进制)
         >>> 0x53
         83
         >>> 0xA3
         163
         >>> bin(163)
         '0b10100011'
         >>> 0B11101011
         235
         >>> hex(235)
         '0xeb'
         
  字符:定义字符串
          python 中字符串被定义为引号之间的字符集合
          python支持使用成对的单引号或双引号
          无论单引号,还是双引号,表示的意义相同
          python还支持三引号(三个连续的单引号或者双引号),可以用来包含特殊字符
          python 不区分字符和字符串
          
         字符串切片
           使用索引运算符[]和切片运算符[:] 可得到子字符串
           第一个字符的索引是0,最后一个字符的所以十-1
           
             >>> pyStr = 'python'
             >>> pyStr[0]
             'p'
             >>> pyStr[-2]
             'o'
             >>> pyStr[-4]
             't'
             >>> pyStr[2:]
             'thon'
             >>> pyStr[::2](设置步长为2)
             'pto'
             >>> pyStr[1::2](从下标为1开始取,步长为2)
             'yhn'
             >>> pyStr[::-1](从下标为0开始取,步长为-1)
             'nohtyp'
             >>> pyStr[:4]
             'pyth'
             >>> 'python'[6]
             Traceback (most recent call last):
               File "<stdin>", line 1, in <module>
             IndexError: string index out of range
             >>> 'python'[0]
             'p'
             >>> len(pyStr)
             6
         
         字符串连接操作
           使用+号可以将多个字符串拼接在一起
           使用*号可以将一个字符串重复多次
             >>> pyStr = 'python'
             >>> isCool = 'is Cool'
             >>> print pyStr + '' + isCool
             pythonis Cool
             >>> print pyStr + ' ' + isCool
             python is Cool
             >>> pyStr * 2
             'pythonpython'
  列表:定义列表
         可以将列表当成普通的“数组”,它能保存任意数量任意类型的python对象
         像字符串一样,列表也支持下标和切片操作
         列表中的项目可以改变(项目可以使数字/字符串/列表/字典)
           >>> aList=[1,'tom',2,'alice']
           >>> aList
           [1, 'tom', 2, 'alice']
           >>> aList[1] = 'bob'
           >>> aList
           [1, 'bob', 2, 'alice']
           >>> aList[2:]
           [2, 'alice']
           >>> aList = [1,'bob',[10,20]]
           >>> len(aList)
           3
           >>> aList[2][0]
           10

       列表操作
         使用in或not in 判断成员关系(字符串同样适用)
         使用append方法向列表中追加元素
           >>> aList
           [1, 'bob', [10, 20]]
           >>> 'bob' in aList
           True
           >>> 'alice' not in aList
           True
           >>> aList.append(3)
           >>> aList
           [1, 'bob', [10, 20], 3]
           >>> aList[5] = 'tom'
           Traceback (most recent call last):
             File "<stdin>", line 1, in <module>
           IndexError: list assignment index out of range

  元组:元组的定义及操作
         可以认为元组是“静态”的列表
         元组一旦定义,不能改变
           >>> aTuple = (1,'tom',2,'alice')
           >>> 'tom' in aTuple
           True
           >>> aTuple[0]=3
           Traceback (most recent call last):
             File "<stdin>", line 1, in <module>
           TypeError: 'tuple' object does not support item assignment
         元组的特殊性(“可变”)
           >>> atuple = ('1','bob',[10,20])
           >>> atuple
           ('1', 'bob', [10, 20])
           >>> atuple[2] = [100,20]
           Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
           TypeError: 'tuple' object does not support item assignment
           >>> atuple[2][0] = 100
           >>> atuple
           ('1', 'bob', [, 20]) 
           >>> atuple[2].append(300)
           >>> atuple
           ('1', 'bob', [100, 20, 300])


  字典:字典的定义及操作
          字典是由键-值(key-value)对构成的映射数据类型
          通过键取值,不支持下标操作
          字典是无序集合
          >>> userDict = {'name':'bob','age':23}
          >>> userDict
          {'age': 23, 'name': 'bob'}
          >>> userDict['gender'] = 'male'(如果字典中本身有这个key,就将该key的value修改,如果没有这个key,就新增这个key-alue
          >>> userDict
          {'gender': 'male', 'age': 23, 'name': 'bob'}
          >>> 'bob' in userDict
          False
          >>> 'name' in userDict
          True
          >>> userDict[0]
          Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
          KeyError: 0
          >>> len(userDict)
          3            

  按存储模型分类
    - 标量类型: 数值、字符串
    - 容器类型: 列表、元组、字典
  按更新模型分类
    - 可变类型: 列表、字典
    - 不可便类型: 数字、字符串、元组
  按访问模型分类
    - 直接访问: 数字
    - 顺序访问: 字符串、列表、元组、
    - 映射访问: 字典
    
关于变量与内存的引用关系
  >>> aList
  [1, 'bob', [10, 20], 3]
  >>> bList=aList(将bList这个变量与aList变量指向同一个内存)
  >>> bList
  [1, 'bob', [10, 20], 3]
  >>> aList[0] = 1000
  >>> aList
  [1000, 'bob', [10, 20], 3]
  >>> bList
  [1000, 'bob', [10, 20], 3](因为是指向同一块内存,所以aList变了,bList也跟着变了)
如果不想指向同一块内存,可以把aList的内容取出来,重新赋值给新的变量
  >>> cList = aList[:]
  >>> cList
  [1000, 'bob', [10, 20], 3]
  >>> cList.append('tom')
  >>> aList
  [1000, 'bob', [10, 20], 3]
  >>> cList
  [1000, 'bob', [10, 20], 3, 'tom']
  
判断语句
  if 语句
    if 语句语法结构
      标准if 条件语句语法
        if expression:
          if_suite
        else:
          else_suite
      如果表达式的值非0、非空、none或者为布尔值True,则代码组if_suite被执行;否则就去执行else_suite
        >>> if 3:
        ...  print 'ok'
        ... 
        ok
        >>> if 0:
        ...  print 'ok'
        ... 
        >>>
        >>> if -1:
        ...   print "ok"
        ... 
        ok
        >>> if ' ':
        ...  print 'ok'
        ... 
        ok
        >>> if '':
        ...   print 'ok'
        ...
        >>>
        >>> if 3 > 10:
        ...   print 'ok'
        ... else:
        ...   print 'no'
        ... 
        no
        
      代码组是一个python术语,它由一条或多条语句组成,表示一个子代码块
      注意:同一级子语句,缩进必须相同,如果不同,则报错
        >>> if 3 > 1:
        ...   print 'yes'
        ...   print 'ok'
        ... 
        yes
        ok
        >>> if 3 > 1:
        ...   print 'yes'
        ...     print 'ok'
          File "<stdin>", line 3
            print 'ok'
            ^
        IndentationError: unexpected indent
    if 语句示例解析
      判断合法用户
       1、创建~/bin/login2.py文件
       2、提示用户输入用户名和密码
       3、获得到相关信息后,将其保存在变量中
       4、如果用户输的用户名为bob,密码为123456,则输出Login successful,否则输出Login incorrect
       自己写的:
        #!/usr/bin/env python
        # -- coding: utf-8 --
        user_name = raw_input("Enter the user_name: ")
        pass_word = raw_input("Enter the password: ")
        if user_name == "bob":
            if pass_word == '123456':
                print "Login successful"
            else:
                print "Login incorrect"
        else:
            print "Login incorrect"
        老师写的:
        #!/usr/bin/env python
        # -- coding: utf-8 --
        import getpass
        user_name = raw_input("Enter the user_name: ")
        pass_word = getpass.getpass("Enter the password: ") #无回显
        if user_name == "bob" and  pass_word == '123456':
            print "Login successful"
        else:
            print "Login incorrect"
  扩展if 语句
    扩展if 语句结构
      扩展if条件语句的语法
        if expression1:
          if_suite
        elif expression2:
          elif_suite
        else:
          else_suite
      只有满足相关条件,相应的子语句才会执行
      没有Swith/case这样的替代品
    扩展if 语句示例解析
      对于多个分支,只有一个满足条件的分支被执行
      >>> x = 9
      >>> if x > 0:
      ...  print "Positive"
      ... elif x < 0:
      ...  print "Negative"
      ... else:
      ...  print "Zero"
      ... 
      Positive
      编写判断成绩的程序
        创建 ~/bin/grade.py脚本,根据用户输入的成绩分档,要求如下:
          1、如果成绩大于60分,输出“及格”
          2、如果成绩大于70分,输出“良好”
          3、如果成绩大于80分,输出“好”
          4、如果成绩大于90分,输出“优秀”
          5、否则输出“你要努力了”
          自己写的:
            #!/usr/bin/env python
            # -- coding: utf-8 --
            grade = int(raw_input("input the grade(0-100): "))
            if grade >= 60 and grade < 70:
                print "及格"
            elif grade >= 70 and grade < 80:
                print "良好"
            elif grade >= 80 and grade < 90:
                print "好"
            elif grade >= 90 and grade <=100:
                print "优秀"
            else:
                print "你需要努力了"
          老师给的(可以使用连等):
            #!/usr/bin/env python
            # -- coding: utf-8 --
            score = int(raw_input("score: "))
            if score >=90:
                print "优秀"
            elif score >= 80:
                print "好"
            elif score >= 70:
                print "良"
            elif score >=60:
                print "及格"
            else:
                print "你要挨打了!"
     编写一个程序,和计算机玩石头、剪刀、布猜拳游戏
       思路:
         计算机随机出石头剪刀步的方法
           >>> import random
           >>> random.choice('abcdef')
           'a'
           >>> random.choice('abcdef')
           'f'
           >>> random.choice(['bob','tom','lee'])
           'bob'
           >>> random.choice(['bob','tom','lee'])
           'tom'
           >>> random.choice(['bob','tom','lee'])
           'lee'


         根据计算机出的,来和人出的进行比较
         相关知识点:输出不同颜色的字体
         shell/命令行下
         # echo [ok]
         # echo -e "\e[32;43;1m[ok]" #此处没有0m结束,接下来输出的颜色都是和这个相同
         # echo -e "\e[32;43;1m[ok]\e[0m" 
         代码如下:
            #!/usr/bin/env python
            # -- coding: utf-8 --
            
            import random
            ch_list = ["石头","剪刀","布"]
            #列出人赢的组合
            win_list = [["石头","剪刀"],["剪刀","布"],["布","石头"]]
            prompt = """(0) 石头
            (1) 剪刀
            (2) 布
            请选择(0/1/2): """
            #计算机的选择
            computer = random.choice(ch_list)
            #人的选择方式
            ind = int(raw_input(prompt))
            player = ch_list[ind]
            #输出 人机 选择
            print "Your choice: %s,Computer's choice: %s" % (player,computer)
            #判断输赢
            if [player,computer] in win_list:
                #设置输出字符颜色“\033[31;1m,其中\033是特定写法,31,表示字符本身颜色(30+都是字体本身颜色),1m 表示开启,0m表示关闭”
                print "\033[31;1mYou Win!\033[0m"
            elif player == computer:
                print "\033[32;1m平局\033[0m"
            else:
                print "\033[34:1mYou Lose\033[0m"