Python base(一)

1.Python安装

Download Python:https://www.python.org/downloads/

windos

1、下载安装包
    https://www.python.org/ftp/python/3.5.1/python-3.5.1-amd64.exe
2、安装
    默认安装路径:C:python35
3、配置环境变量
    【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【Python安装目录追加到变值值中,用 ; 分割】
    如:原来的值;C:python35,切记前面有分号

linux

查看默认Python版本
python -V

1、安装gcc,用于编译Python源码
    yum install gcc gcc-c++ openssl-devel -y
2、下载源码包
    wget https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tar.xz
3、解压并进入源码文件
    xz -d Python-2.7.11.tar.xz
    tar fvx Python-2.7.11.tar
    cd Python-2.7.11
4、编译安装
    ./configure --prefix=/usr/local/company/python2.7
    make all
    make install
5、查看版本
    /usr/local/company/bin/python2.7
6、修改默认Python版本
    mv /usr/bin/python /usr/bin/python2.6
    ln -s /usr/local/company/bin/python2.7 /usr/bin/python
7、防止yum执行异常,修改yum使用的Python版本
    vi /usr/bin/yum
    将头部 #!/usr/bin/python 修改为 #!/usr/bin/python2.6

Easy_install 安装方式为

wget https://bootstrap.pypa.io/ez_setup.py
python2.7 ez_setup.py
#如果安装3.0以上版本时请确认openssl-devel的版本

2.设计哲学与定位

Python的设计哲学是“优雅”、“明确”、“简单"
Python开发者的哲学是“用一种方法,最好是只有一种方法来做一件事”
在设计Python语言时,如果面临多种选择,Python开发者一般会拒绝花俏的语法,而选择明确没有或者很少有歧义的语法。
这些准则被称为“Python格言”。
在Python解释器内运行import this可以获得完整的列表

Python格言

  • Beautiful is better than ugly.
    --优美胜于丑陋(Python 以编写优美的代码为目标)
  • 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.
    --不要包容所有错误,除非你确定需要这样做(精准地捕获异常,不写 except:pass 风格的代码)
  • 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.
    --虽然这并不容易,因为你不是 Python 之父(这里的 Dutch 是指 Guido )
  • 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!
    --命名空间是一种绝妙的理念,我们应当多加利用(倡导与号召)

3.成功的奥秘-推荐读物

硅谷黑历史
爆裂鼓手

4.语言的开始"hello world"

JIT技术实时编译,速度可以匹配C语言
Python2.7+

print "hello world"

Python3.0+

print ("hello world")

5.解释器与内存容编码

  • Python编写的脚本通常以".py"结尾

以".py"结尾的文件:文件的开部通常会指定解释器,解释器指定的方式有两种

#!/usr/bin/python
以系统的Python所在路径为头部
#!/usr/bin/env python
以系统的Python本地环境变量为头部[推荐使用]

  • Python的内容编码

Python2.7内置的内容编码为ASCII
Python3.0内置的内容编码为Unicode

So.当使用Python2.7输出中文时会出现异常,需要在头部指定编码格式

#_*_ coding:utf-8 _*_

6.Python2、Python3的简单区别[此处不做详细比较]

  • 使用__future__模块
  • print函数
  • 整数除法
  • Unicode
  • xrange
  • 触发异常
  • 处理异常
  • next()函数和.next()方法
  • For循环变量与全局命名空间泄漏
  • 比较无序类型
  • 使用input()解析输入内容
  • 返回可迭代对象,而不是列表

7.Python的注释及引号

当行注释:# 被注释内容

#This is nots

单引号:''输出一行内容[多字符]

print('OK')

双引号:“”输出一行内容[多字符]

print("OK")

三引号[注释&格式化输出]:包含一行或多行内容[三对单引号或三对双引号]

print("""line1 line2 line3""")
print("""
line1
line2
line3
""")
print('''
line1
line2
line3
''')
"""
note1
note2
note3
"""

8.变量

8.1.变量的作用

  • 重复调用
  • 存储数据的容器[内存存储]

8.2.变量的书写方式

变量名 = 变量值[变量值可以是一串数据或一个变脸]

#!/usr/bin/env python
author='Yorick'

or

#!/usr/bin/env python
name='Yorick'
author=name

8.3.变量定义的规则

  • 变量名只能是 字母、数字或下划线的任意组合
  • 变量名的第一个字符不能是数字
  • 以下关键字不能声明为变量名

['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']

8.4.变量的赋值

#!/usr/bin/env python
name='Yorick'
author=name

print(name)
print(author)
print(id(name))
print(id(author))

变量名name、author调用过程如上所示:理论来讲当修改name的值之后author值也应该一起变化,看接下来的实验

#!/usr/bin/env python
name='Yorick'
author=name
name='Bill'

print(name)
print(author)
#打印name、author的内存编址编号
print(id(name))
print(id(author))

根据实验Python执行后显示name值是变化了,但author值依然为'Yorick',由此推断Python变量调用实际上指向的为内存编址,不为变量本身

9.模块的导入

9.1.自己编写一个Python脚本

vi/vim hello.py

#!/usr/bin/env python
print("hello world")

9.2.再编写一个Python脚本

vi/vim call.py

#!/usr/bin/env python
#导入上面编写的hello脚本可以不写".py"后缀
import hello
print("finish")

import 为导入模块的指令:模块的简单分类

  • Python内部提供的模块
  • 业内开源的模块
  • 程序员自己开发的模块

9.3.后缀为".pyc"的文件

执行Python代码时,如果导入了其他的 .py 文件,那么,执行过程中会自动生成一个与其同名的 .pyc 文件,该文件就是Python解释器编译之后产生的字节码。

PS:代码经过编译可以产生字节码;字节码通过反编译也可以得到代码。

10.输入

  • 默认使用input输入为展示传参[输入的内容会回显]

Python3.0的input()

#!/usr/bin/env python
#使用input可以供户输入,将用户输入的内容传给username变量
username=input("input your username:")
print(username)

Python2.7的raw_input()

#!/usr/bin/env python
#_*_coding:utf-8_*_
#使用raw_input可以供户输入,将用户输入的内容传给username变量
username=raw_input("input your username:")
print(username)
  • 调用内部提供的参数getpass不展示传参[输入的内容不会回显]

Python的getpass

#!/usr/bin/env python
#导入getpass模块
import getpass
#使用getpass.getpass可以供户输入,将用户输入的内容传给password变量
password=getpass.getpass("input your password:")
print(username)

11.OS模块常用命令

Python os模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的(一语中的)

os.name
#输出字符串指示正在使用的平台
os.getcwd()
#得到当前工作目录,即当前Python脚本工作的目录路径。
os.remove()
#删除一个文件
os.listdir()
#返回指定目录下的所有文件和目录名
os.system()
#运行shell命令并返回状态码[传参为状态码]
os.popen()
#运行shell命令并返回结果[传参为返回的结果]
os.path.split()
#函数返回一个路径的目录名和文件名
os.path.isfile()
#检验给出的路径是一个文件
os.path.isdir()
#检验给出的路径是一个目录
os.path.exists()
#检验给出的路径是否真地存在
os.path.abspath(name)
#获得绝对路径
os.path.getsize(name)
#获得文件大小
os.path.splitext()
#分离文件名与扩展名
os.path.join(path,name)
#连接目录与文件名或目录
os.path.basename(path)
#返回文件名
os.path.dirname(path)
#返回文件路径

12.Tab补全语法

#!/usr/bin/env python
# python startup file
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter

13.流程控制:猜数字

  • 流程控制
#/usr/bin/env python
#_*_ coding:utf-8 _*_
__author__ = "Yorick"


age = 22

#输入你猜测的数字
guess_num = int(input("input your guess num:"))

#流程控制if else 判断
if guess_num == age:
    print("Congratulations! you got is.")
elif guess_num > age:
    print("think smaller!")
else:
    print("think bigger")
  • 加入迭代器for[其实在Python中for是一个迭代器,它只会按顺序调取对应参数,不会做其它判断,不是循环]
#/usr/bin/env python
#_*_ coding:utf-8 _*_
__author__ = "Yorick"

age=40
counter=0

#迭代器for
for i in range(10):
    if counter < 3:
        guess_num = int(input("input your guess num:"))

        if guess_num == age:
            print("Congratulations!you got it.")
            #跳出当前循环
            break
        elif guess_num > age:
            print("notice:number is too big,think again!")
        else:
            print("notice:number is too small,think again!")
        counter +=1
    else:
        continue_confirm = input("Do you want to continue?_")
        if continue_confirm == "y":
            counter = 0
        else:
            print("bye")
            break

14循环内常用语句


break    :break语句用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。
continue :continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。
pass     :pass 不做任何事情,一般用做占位语句
原文地址:https://www.cnblogs.com/yorickwu/p/5486563.html