V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ansheng
V2EX  ›  Python

Python 全栈之路系列之基础篇

  •  
  •   ansheng ·
    anshengme · 2017-01-06 19:52:57 +08:00 · 2539 次点击
    这是一个创建于 2670 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Python 的诞生

    Python 是著名的"龟叔"Guido van Rossum(吉多·范罗苏姆)在 1989 年圣诞节期间,为了打发无聊的圣诞节而编写的一个编程语言。

    guide

    Python 语法很多来自 C ,但又受到 ABC 语言的强烈影响,来自 ABC 语言的一些规定直到今天还富有争议,比如强制缩进,但这些语法规定让 Python 变得更易读。

    Guido van Rossum著名的一句话就是**Life is short, you need Python,译为:人生苦短,我用 Python**,一直到现在,无论在任何介绍 Python 这门强大的语言时,都会有提到。

    截至到目前2017 年 1 月 6 日, Python 在Tiobe的排名还是很靠前的,而且近几年来说 Python 上升的趋势还是特别稳定的,这两年一直保持在第四位,甚至已经超越 PHP 和 C#。

    Tiobe

    查询网站: http://www.tiobe.com/tiobe_index?page=index

    我们还可以再解释下下通过import this查看 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!
    

    Python 唯一的缺点就是他的性能,它达不到像 C 和 C++这种编译性语言运行的那么快,但是我们通常都不需要考虑这个问题,因为有PYPY,它的运行速度比默认的Cpython要快很多。

    在 Win10 下安装 Python3

    下载 Python 解释器

    64 位下载地址: https://www.python.org/ftp/python/3.5.2/python-3.5.2-amd64.exe 32 位下载地址: https://www.python.org/ftp/python/3.5.2/python-3.5.2.exe

    安装 Python 解释器

    下载下来之后双击安装,在安装的时候稍微需要注意一下就是需要修改默认的安装路径和和自动注册到系统环境变量勾选上。

    python

    python

    然后就可以点击Install按钮进行安装了。

    python

    因为我们已经勾选自动注册环境变量,所以在这里就不需要修改环境变量,直接运行即可;

    DOS 测试

    右键开始菜单选择命令提示符,打开 CMD 窗口,

    python

    python

    在 cmd 窗口中输入python -V指令查看安装的 Python 版本:

    python

    如果你得到的结果和我一样,那么你就安装好了windows下的python环境。

    因为在Mac os和其他unixLinux版本下都已经自带了 Python ,这里我就不做太多介绍了。

    Python 实现方式

    Python 身为一门编程语言,但是他是有多种实现方式的,这里的实现指的是符合 Python 语言规范的 Python 解释程序以及标准库等。

    Python 的实现方式主要分为三大类

    1. Cpython
    2. Jpython
    3. IronPython

    CPython

    Cpython是默认的 Python 解释器,这个名字根据它是可移植的ANSI C语言代码编写而成的这事实而来的。

    当执行 Python 执行代码的时候,会启用一个 Python 解释器,将源码(.py)文件读取到内存当中,然后编译成字节码(.pyc)文件,最后交给 Python 的虚拟机(PVM)逐行解释并执行其内容,然后释放内存,退出程序。

    python-day01-04

    当第二次在执行当前程序的时候,会先在当前目录下寻找有没有同名的 pyc 文件,如果找到了,则直接进行运行,否则重复上面的工作。

    pyc 文件的目的其实就是为了实现代码的重用,为什么这么说呢?因为 Python 认为只要是 import 导入过来的文件,就是可以被重用的,那么他就会将这个文件编译成 pyc 文件。

    python 会在每次载入模块之前都会先检查一下 py 文件和 pyc 文件的最后修改日期,如果不一致则重新生成一份 pyc 文件,否则就直接读取运行。

    Jython

    Jython 是个 Python 的一种实现方式, Jython 编译 Python 代码为 Java 字节码,然后由 JVM ( Java 虚拟机)执行,这意味着此时 Python 程序与 Java 程序没有区别,只是源代码不一样。此外,它能够导入和使用任何 Java 类像 Python 模块。

    IronPython

    IronPython 是 Python 的 C#实现,并且它将 Python 代码编译成 C#中间代码(与 Jython 类似),然后运行,它与.NET 语言的互操作性也非常好。

    Python 简单入门

    Hello Word

    一般情况下程序猿的第一个小程序都是简单的输出Hello Word!,当然 Python 也不例外,下面就让我们来用 Python 输出一句Hello Word!吧!

    创建一个以 py 结尾的文件

    [root@ansheng python_code]# touch hello.py
    

    其内容为

    #!/usr/vin/env python
    
    print "Hello Word!"
    

    用 Python 执行

    [root@ansheng python_code]# python hello.py
    Hello Word!
    

    输出的内容为Hello Word!, OK ,你的第一次一句木有了^_^

    指定 Python 解释器

    在 Python 文件的开头加入以下代码就制定了解释器。

    第一种方式

    #!/usr/bin/python
    

    告诉 shell 这个脚本用/usr/bin/python执行

    第二种方式

    #!/usr/bin/env python
    

    在操作系统环境不同的情况下指定执行这个脚本用 python 来解释。

    执行 Python 文件

    执行 Python 文件的方式有两种

    例如hello.py的文件内容为

    #!/usr/bin/env python
    print "Life is short, you need Pytho"
    

    第一种执行方式

    [root@ansheng python_code]# python my.py
    Life is short, you need Pytho
    

    如果使用python my.py这种方式执行,那么#!/usr/bin/python会被忽略,等同于注释。

    第二种执行方式

    [root@ansheng python_code]# chmod +x my.py 
    [root@ansheng python_code]# ./my.py 
    Life is short, you need Pytho
    

    如果使用./my.py来执行,那么#!/usr/bin/python则是指定解释器的路径,在执行之前my.py这个文件必须有执行权限。

    python my.py 实则就是在my.py文件顶行加入了#!/usr/bin/python

    指定字符编码

    python 制定字符编码的方式有多种,而编码格式是要写在解释器的下面的,常用的如下面三种:

    第一种

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    

    第二种

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    

    第三种

    #!/usr/bin/env python
    # coding:utf-8
    

    代码注释

    单行注释

    单行注释只需要在代码前面加上#

    # 注释内容
    

    多行注释

    多行注释用三个单引号或者三个双引号躲起来

    """
    注释内容
    """
    

    实例

    py脚本原文件内容

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    
    print "My name is Ansheng"
    print "I'm a Python developer"
    print "My blog URL: https://blog.ansheng.me"
    print "Life is short, you need Pytho"
    

    源文件输出的内容

    [root@ansheng python_code]# python note.py 
    My name is Ansheng
    I'm a Python developer
    My blog URL: https://blog.ansheng.me
    Life is short, you need Pytho
    

    单行注释演示

    代码改为

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    
    print "My name is Ansheng"
    print "I'm a Python developer"
    print "My blog URL: https://blog.ansheng.me"
    #print "Life is short, you need Pytho"
    

    执行结果

    [root@ansheng python_code]# python note.py 
    My name is Ansheng
    I'm a Python developer
    My blog URL: https://blog.ansheng.me
    

    结果Life is short, you need Pythoprint 出来

    多行注释演示

    代码改为

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    
    print "My name is Ansheng"
    """
    print "I'm a Python developer"
    print "My blog URL: https://blog.ansheng.me"
    print "Life is short, you need Pytho"
    """
    

    执行结果

    [root@ansheng python_code]# python note.py 
    My name is Ansheng
    

    结果I'm a Python developerMy blog URL: https://blog.ansheng.meLife is short, you need Pytho都没有 print 出来

    print 输出多行

    既然用单个单引号或者多引号可以注释多行,那么能不能 print 多行呢?

    代码

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    
    print """
    My name is Ansheng
    I'm a Python developer
    My blog URL: https://blog.ansheng.me
    Life is short, you need Python.
    """
    

    执行结果

    [root@ansheng python_code]# python note.py 
    
    My name is Ansheng
    I'm a Python developer
    My blog URL: https://blog.ansheng.me
    Life is short, you need Python.
    
    

    显然这是可以得 ^_^

    变量

    变量的命名规则:

    1. 变量名只能包含数字、字幕、下划线
    2. 不能以数字开头
    3. 变量名不能使 python 内部的关键字

    Python 内部已占用的关键字

    ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
    

    定义变量

    >>> name = "ansheng"
    >>> print name
    ansheng
    

    基本的数据类型

    字符串(str)

    定义字符串类型是需要用单引号或者双引号包起来的

    >>> name = "ansheng"
    >>> print(type(name))
    <type 'str'>
    

    或者

    >>> name = 'ansheng'
    >>> print(type(name))
    <type 'str'>
    

    数字(int)

    整数类型定义的时候变量名后面可以直接跟数字,不要用双引号包起来。

    >>> age = 20
    >>> print(type(age))
    <type 'int'>
    

    布尔值

    布尔值就只有True(真)Flash(假)

    >>> if True:
    ...  print("0")
    ... else:
    ...  print("1")
    ...
    0
    

    解释:如果为真则输出 0 ,否则输出 1

    流程控制

    if 语句

    if语句是用来检查一个条件:如果条件为真(true),我们运行一个语句块(你为 if 块),否则(else),我们执行另一个语句块(称为 else 块), else 子语句是可选的。

    单条件

    例题:如果 num 变量大于 1 ,那么就输出 num 大,否则就输出 num 小, num 值为 5 。

    代码

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    num = 5
    
    if num > 1:
     print("num 大")
    else:
     print("num 小")
    

    结果

    [root@ansheng python_code]# python num.py
    num 大
    

    多条件

    例题:如果 num 变量大于 5 ,那么就输出 num 大于 5 ,如果 num 变量小于 5 ,那么就输出 num 小于 5 ,否则就输出 num 等于 5 , num 值为 5 。

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    num = 5
    
    if num > 5:
     print("num 大于 5")
    elif num < 5:
     print("num 小于 5")
    else:
     print("num 等于 5")
    

    结果

    [root@ansheng python_code]# python num.py
    num 等于 5
    

    while 循环

    while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。 执行流程图如下

    while

    实例:

    定义一个变量 count ,默认值为 1 ,然后进去 while 循环,让其输出 1-10 ,如果大于 10 则退出。

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    
    count = 1
    
    print "Start...."
    
    while count < 11:
     print "The count is:",count
     count += 1
    
    print "End...."
    

    执行结果如下

    [root@ansheng python_code]# python while.py
    Start....
    The count is: 1
    The count is: 2
    The count is: 3
    The count is: 4
    The count is: 5
    The count is: 6
    The count is: 7
    The count is: 8
    The count is: 9
    The count is: 10
    End....
    

    break

    跳出当前循环体,下面代码不再执行,继续执行循环后面的代码

    实例

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    
    count = 1
    
    print "Start...."
    
    while count < 11:
     if count == 5:   #如果 count 等于 5 ,那么我就退出当前循环体
      break
     print "The count is:",count
     count += 1
    
    print "End...."
    

    输出结果

    [root@ansheng python_code]# python while.py
    Start....
    The count is: 1
    The count is: 2
    The count is: 3
    The count is: 4
    End....
    

    continue

    跳出本次循环,继续下一次循环

    代码

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    
    count = 1
    
    print "Start...."
    
    while count < 11:
     if count == 5:		#如果 count 等于 5 ,那么我就让其+1 ,然后不执行下面的代码,继续下一次循环
      count += 1
      continue
     print "The count is:",count
     count += 1
    
    print "End...."
    

    输出结果

    [root@ansheng python_code]# python while.py
    Start....
    The count is: 1
    The count is: 2
    The count is: 3
    The count is: 4
    The count is: 6
    The count is: 7
    The count is: 8
    The count is: 9
    The count is: 10
    End....
    

    条件判断

    条件判断适用于ifwhile等。

    等于

    if 1 == 1:
    

    不等于

    if 1 != 2:
    

    小于

    if 1 < 1
    

    大于

    if 1 > 1:
    

    并且

    if 1 == 1 and 1 > 0:
    

    或者

    if 2 > 1 or 2 = 2:
    

    永远为真

    if True:
    

    永远为假

    if Flase:
    

    交互式输入

    Python 的交互式输入使用的是input()函数实现的,注意在Python2.7.x版本的时候可以使用raw_input()input()函数,但是在Python3.5.x版本的时候就没有raw_input()函数了,只能够使用input()

    例题:用户在执行脚本的时候,让他输入自己的名字,然后打印出来。

    代码

    #!/usr/bin/env python
    # _*_ coding:utf-8 _*_
    
    username = input("请输入你的名字:")
    print("你的名字是:", username)
    

    执行结果

    [root@ansheng python_code]# python input.py
    请输入你的名字:安生   # 输入你的名字
    你的名字是: 安生      # 打印出你的名字
    

    练习题

    使用 while 循环输入 1 2 3 4 5 6 8 9 10

    思路: 首先定义一个变量 num,值为 1,然后用 while 循环输出 1-10 的内容,在 while 循环内加入 if 语句,判断当前的值如果是 7,那么就让 7+1,加完之后跳出本次循环,不执行下面的 print,7 跳出本次循环之后,第二轮的时候 num 就是 8 了,而不是 7.

    代码

    #!/use/bin/env python
    # _*_ coding:utf-8 _*_
    
    num = 1
    while num < 11:
        if num == 7:
            num += 1
            continue
        print(num)
        num += 1
    

    输出内容为:

    1
    2
    3
    4
    5
    6
    8
    9
    10
    

    求 1-100 的所有数的和

    **思路:**定义两个变量,分别是 count 和 num ,利用 while 语句循环输出 1-100 ,然后每次就让 count+num ,这样循环一百次之后相加的结果就是 1 到 100 的和了。

    代码

    #!/use/bin/env python
    # _*_ coding:utf-8 _*_
    
    count = 1
    num = 0
    while count < 101:
        num = num + count
        count += 1
    
    print(num)
    

    输出结果

    5050
    

    输出 1-100 内的所有奇数

    思路: 利用%整数相除的余,如果余数是 1 那么当前的 count 就是奇数,如果余 0 ,那么当前的 count 就是偶数。

    代码

    #!/use/bin/env python
    # _*_ coding:utf-8 _*_
    
    count = 1
    
    while count < 101:
        num = count % 2
        if num == 1:
            print(count)
        count += 1
    

    结果自己执行看

    输出 1-100 内的所有偶数

    代码

    #!/use/bin/env python
    # _*_ coding:utf-8 _*_
    
    count = 1
    
    while count < 101:
        num = count % 2
        if num == 0:
            print(count)
        count += 1
    

    结果自己执行看

    求 1-2+3-4+5 ... 99 的所有数的和

    #!/use/bin/env python
    # _*_ coding:utf-8 _*_
    
    count = 1
    
    while count < 100:
        if count == 1:
            num = count
        elif count % 2 == 1:
            num = num + count
        elif count % 2 == 0:
            num = num - count
        count += 1
    
    print(num)
    

    结果

    50 
    

    用户登陆

    需求:写一个脚本,用户执行脚本的时候输入用户名和密码,如果用户米或者密码连续三次输入错误则退出,如果输入正确则显示登陆成功,然后退出。

    用户名和密码自己定义

    • 图解用户登录流程

    python-day01-10

    • 代码
    #!/use/bin/env python
    # _*_ coding:utf-8 _*_
    import getpass
    
    # username : ansheng
    # userpass : 666666
    
    count = 3
    
    while count > 0:
        username = input("User Name:")
        userpass = getpass.getpass("pass:")
        if username == "ansheng" and userpass == "666666":
            print "User:", username, ",login successful!"
            break
        else:
            count -= 1
            if count != 0:
                print "Login failed", count
            else:
                print("The maximum number of login!")
    

    登陆成功演示

    User Name:ansheng  #输入用户名
    pass:              #输入密码,密码是看不到的,因为调用了 getpass 模块
    User: ansheng ,login successful!  #显示用户 ansheng ,登陆成功
    

    登陆失败演示

    User Name:as
    pass:
    Login failed 2
    User Name:an
    pass:
    Login failed 1
    User Name:ansea
    pass:
    The maximum number of login!
    

    账号或密码连续三次输入错误则退出程序,并且每次提醒用户升序多少次登陆的机会。

    原文地址: https://blog.ansheng.me/article/python-full-stack-way-basics/ Python全栈之路系列文章

    4 条回复    2017-01-10 18:48:37 +08:00
    2014CD2014
        1
    2014CD2014  
       2017-01-10 14:40:54 +08:00
    牛牛
    ansheng
        2
    ansheng  
    OP
       2017-01-10 16:11:02 +08:00
    @2014CD2014 其实我很菜,不要告诉别人
    prorigor
        3
    prorigor  
       2017-01-10 17:15:28 +08:00
    已经收藏,看到有声明还没系列更新完?
    ansheng
        4
    ansheng  
    OP
       2017-01-10 18:48:37 +08:00
    @prorigor 还在更,主要是整理下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5333 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 07:37 · PVG 15:37 · LAX 00:37 · JFK 03:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.