Python全栈之路系列之基础篇

Python的诞生

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

guide

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

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_in...windows

咱们还能够再解释下下经过import this查看Python语言的设计哲学:bash

>>> 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要快不少。less

在Win10下安装Python3

下载Python解释器编程语言

64位下载地址:https://www.python.org/ftp/py...
32位下载地址:https://www.python.org/ftp/py...ide

安装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 False:

交互式输入

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!

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

原文连接
Python全栈之路系列文章

相关文章
相关标签/搜索