python 基础语法

python 有5个标准的数据类型

  • Number(数字) 
    • int
    • long
    • float
    • complex(复数)
  • striing(字符串)
  • list(列表) 
    • 列表使用的标识符是 [ ]
    • +是连接运算符
    • *是重复运算符
  • tuple(元组) 
    • 元组使用的标识符是(),内部元素用逗号隔开,元组不能进行二次赋值
  • dictionary(字典) 
    • 字典是无须对象的集合,而列表是有序对象的集合
    • 使用的标识符{ }
    • 字典是由索引(KEY)和他对应的value值组成

 

运算符(相对与C++多出了两条) 
- ** 是幂运算 例如2**3=8 
- //是整除,返回商的整数部分9//2=4 
a=9.0/2 
b=9.0//2 
print a 
print b
输出a=4.5 b=4.0


成员运算符 
符号:in / not in 如果这个序列当中,就返回值1


身份运算符 
符号:is/is not is用来判断两个标识符是不是一样,如果一样返回值是1。


注释 
单行注释 是用的# 
多行注释 ”’ 这里是多行注释部分””


IF 语句

形式1:

if 判断条件:
   执行语句...
else:
   执行语句...
  • 1
  • 2
  • 3
  • 4

形式2:

if 判断条件1:
   执行语句1...
elif 判断条件2:
   执行语句2...
elif 判断条件3...
   执行语句3...
else:
   执行语句4...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

循环语句 
while 
形式1:

while 判断条件:
   执行语句...
  • 1
  • 2

形式2:

while 判断条件:
    执行语句1...
else:
    执行语句2...
  • 1
  • 2
  • 3
  • 4

形式3:简单语句的时候

while (判断条件):执行的一条语句
  • 1

for循环语句

for val in squence
 执行语句...
  • 1
  • 2

举例

for letter in 'abc'
   print '当前字母是:',letter
  • 1
  • 2

continue是跳出本次循环,break是跳出整个循环。 
pass语句是空语句


删除列表中的元素

list1=['a','b','c']
del list1[0]
  • 1
  • 2

那么就吧list1[0]的元素给删除了

列表的排序问题

list1=['a','b','c']
print list1[-1]
  • 1
  • 2

输出结果是c

列表函数

  • cmp(list1,list2)比较两个列表的元素
  • len(list)列表中元素的个数
  • max(list)列表中元素的最大值
  • min(list)列表中元素的最小值
  • list(seq)将元组转化成列表 
    list 当中包含的方法
  • list.append(obj)在列表末尾添加新的对象
  • list.count(obj)统计某个元素在列表当中出现的次数
  • list.insert(index,obj)在对位位置添加
  • list.reverse()将列表当中元素反向

元组和列表的不同之处在与,元组的元素不能修改,元组用圆括号,列表用方括号

创建一个空元组tup1=(); 
当元组只有一个元素的时候,需要在元素的后面添加逗号tup1=(50,); 
值得注意的一点是:python语句末尾可以加分号也可以不加,我的风格是加分号

同样删除元组 
del tup;


字典的格式

d={key1:value1,key2:value2}key的值必须唯一,value不用唯一
  • 1

修改字典

#建立字典
dict={'name'='David','Age'=8,'Sex'='man'}
#修改字典
dict['Age']=24;
#删除字典某个条目
del dict=['Age'];
#删除字典的所有条目
dict.clear();
#删除字典
del dict;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

字典的内置函数 
除了cmp、len之外还有 
str(dict)输出字典用字符串表示


python提供了一个time和calendar模块用于格式化日期和时间,时间间隔是以秒为单位的浮点小数。 
函数time.time()用于获取当前的时间戳。


函数

def function(参数)
  执行语句1...
  返回值类型
  • 1
  • 2
  • 3

模块 
能够让你有逻辑组织你的python 代码


文件的I/O 
读取键盘的输入: 
raw_input函数是从便装输入里面读取一行,并且返回一个字符串

#!/usr/bin/python
# -*- coding: UTF-8 -*-
str=raw_input("please input :");
print "the output is:",str;
  • 1
  • 2
  • 3
  • 4

input函数

#!/usr/bin/python
# -*- coding: UTF-8 -*- 
str = input("请输入:");
print "你输入的内容是: ", str
  • 1
  • 2
  • 3
  • 4

input函数和raw_input函数之间的差别:input的函数可以将表达式做为输入,例如 1+1


使用open函数来打开文件 
参数表说明: 
这里写图片描述 
file对象的属性 
这里写图片描述 
例子:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name
print "是否已关闭 : ", fo.closed
print "访问模式 : ", fo.mode
print "末尾是否强制加空格 : ", fo.softspace
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

close函数 
用来关闭文件

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name

# 关闭打开的文件
fo.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

write函数 
是将任何字符串写入到一个打开的文件当中

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开一个文件
fo = open("foo.txt", "wb")
fo.write( "www.runoob.com!\nVery good site!\n");

# 关闭打开的文件
fo.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

read函数 
从一个已经打开的文件中读取一个字符串

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是 : ", str
# 关闭打开的文件
fo.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

tell函数:告诉你文件的当前的位置 
seek函数改变当前文件的位置seek(offset,[,form])offset表示要移动的字节数,From变量指定开始移动字节的参考位置。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是 : ", str

# 查找当前位置
position = fo.tell();
print "当前文件位置 : ", position

# 把指针再次重新定位到文件开头
position = fo.seek(0, 0);
str = fo.read(10);
print "重新读取字符串 : ", str
# 关闭打开的文件
fo.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

rename函数重命名当前文件的参数。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os

# 重命名文件test1.txt到test2.txt。
os.rename( "test1.txt", "test2.txt" )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

remove 函数删除文件

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os

# 删除一个已经存在的文件test2.txt
os.remove("test2.txt")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

mkdir函数用于创建一个新的目录

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os

# 删除一个已经存在的文件test2.txt
os.remove("test2.txt")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

chdir函数用于改变当前目录 
(就是一个cd)

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os

# 将当前目录改为"/home/newdir"
os.chdir("/home/newdir")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

getcwd函数用于显示当前的工作目录

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os

# 给出当前的目录
os.getcwd()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

rmdir函数用于删除目录

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os

# 删除”/tmp/test”目录
os.rmdir( "/tmp/test"  )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

异常处理 
异常是一个事件,捕捉这个事件用try/except语句, 
基本语法:

try:
<语句>        #运行别的代码
except <名字>:
<语句>        #如果在try部份引发了'name'异常
except <名字>,<数据>:
<语句>        #如果引发了'name'异常,获得附加的数据
else:
<语句>        #如果没有异常发生
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
#!/usr/bin/python
# -*- coding: UTF-8 -*-

try:
    fh = open("testfile", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print "Error: 没有找到文件或读取文件失败"
else:
    print "内容写入文件成功"
    fh.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

面向对象编程 
python 来创建一个类 
注意类名后面的冒号 
我觉得python 当中双引号和单引号的效果是一样的

class ClassName:
   '类的帮助信息'   #类文档字符串
   class_suite  #类体
  • 1
  • 2
  • 3
#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Employee:
    '所有员工的基类'
    empCount = 0

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
        Employee.empCount += 1
    def displayCount(self):
        print "Total Employee %d" % Employee.empCount

    def displayEmployee(self):
        print "Name : ", self.name, ", Salary: ", self.salary
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

实例化对象

"创建 Employee 类的第一个对象"
emp1 = Employee("Zara", 2000)
"创建 Employee 类的第二个对象"
emp2 = Employee("Manni", 5000)
  • 1
  • 2
  • 3
  • 4

访问属性

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
  • 1
  • 2
  • 3

类的继承:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Parent:        # 定义父类
   parentAttr = 100
   def __init__(self):
      print "调用父类构造函数"

   def parentMethod(self):
      print '调用父类方法'

   def setAttr(self, attr):
      Parent.parentAttr = attr

   def getAttr(self):
      print "父类属性 :", Parent.parentAttr

class Child(Parent): # 定义子类
   def __init__(self):
      print "调用子类构造方法"

   def childMethod(self):
      print '调用子类方法 child method'

c = Child()          # 实例化子类
c.childMethod()      # 调用子类的方法
c.parentMethod()     # 调用父类方法
c.setAttr(200)       # 再次调用父类的方法
c.getAttr()          # 再次调用父类的方法
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

继承多个类

class A:        # 定义类 A
.....

class B:         # 定义类 B
.....

class C(A, B):   # 继承类 A 和 B
.....
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

方法重写

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Parent:        # 定义父类
   def myMethod(self):
      print '调用父类方法'

class Child(Parent): # 定义子类
   def myMethod(self):
      print '调用子类方法'

c = Child()          # 子类实例
c.myMethod()         # 子类调用重写方法
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

类的私有属性

__private_method:两个下划线开头,声明该方法为私有方法,不能在类地外部调用。在类的内部调用 self.__private_methods
  • 1
#!/usr/bin/python
# -*- coding: UTF-8 -*-

class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0    # 公开变量

    def count(self):
        self.__secretCount += 1 #私有属性的调用
        self.publicCount += 1 #公开属性的调用
        print self.__secretCount

counter = JustCounter()
counter.count()
counter.count()
print counter.publicCount
print counter.__secretCount  # 报错,实例不能访问私有变量
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

正则表达式 
是一个特殊的字符序列,用于方便检查一个字符串是否与某个模式匹配。 
re.match函数 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none 
函数的语法:

re.match(pattern,string,flags=0)
  • 1

pattern是匹配的正则表达式 
string是匹配的字符串 
flags 是标志位,用于控制正则表达式的匹配方式。

#!/usr/bin/python
# -*- coding: UTF-8 -*- 

import re
print(re.match('www', 'www.runoob.com').span())  # 在起始位置匹配
print(re.match('com', 'www.runoob.com'))         # 不在起始位置匹配
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

re.search函数 
用于扫描整个字符串并且返回第一个成功的匹配。

re.search(pattern, string ,flags=0)
  • 1

同样,如果匹配成功的花,返回一个匹配对象,否则返回none

#!/usr/bin/python
# -*- coding: UTF-8 -*- 

import re
print(re.search('www', 'www.runoob.com').span())  # 在起始位置匹配
print(re.search('com', 'www.runoob.com').span())         # 不在起始位置匹配
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

re.match和re.search的区别 
re.match只是匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回none,re.search是匹配整个字符串,直到找到一个匹配。

检索和替换 
re.sub(pattern,repl,string, max=0)

#!/usr/bin/python
import re

phone = "2004-959-559 # This is Phone Number"

# Delete Python-style comments
num = re.sub(r'#.*$', "", phone)
print "Phone Num : ", num

# Remove anything other than digits
num = re.sub(r'\D', "", phone)    
print "Phone Num : ", num
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

CGI编程 
CGI,是通用网关接口,他是一段程序,运行在服务器上。 
简单来说就是做网页


python与mysql数据库 
python的标准数据库的接口是python DB-API 
python DB-API的使用流程:

  1. 引入API模块
  2. 获取与数据库的连接
  3. 执行SQL语句和存储过程
  4. 关闭数据库连接 
    如何安装mysql 
    这里是数据库的部分,暂时还不需要

网络编程 
socket也叫做 套接字 ,应用程序通过socket向网络发出请求或者应答网络请求,使得主机之间和电脑之间进程可以相互通信。


多线程 
python中使用线程有两种方式:函数或者用类来包装线程的对象。 
采用函数的方式: 
调用thread模块中start_new_thread函数来产生新的线程 
thread.start_new_thread(function,args[,kwargs]) 
function是线程函数,args是传递给线程函数的参数,这个参数必须是tuple类型 
kwargs是可选参数

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import thread
import time

# 为线程定义一个函数
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

# 创建两个线程
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

采用线程模块 
python通过两个标准库thread和threading提供对线程的支持,thread提供了低级的,原始的线程和一个简单的锁

  • threading.currentThread():返回当前的线程变量
  • run()用来表示线程活动的方法
  • start()启动线程活动
  • join([time])等待至线程终止 
    线程同步 
    使用thread对象的Lock和Rlock可以实现简单的线程同步

XML解析 
常用的XML变成接口有DOM和SAX


GUI编程 
python 提供了多个图形开发的界面

  • Tkinter模块是(Tk接口)Tkinter模块内置到python的安装包当中
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import Tkinter
top = Tkinter.Tk()
# 进入消息循环
top.mainloop()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

常用库 
GUI 图形界面

wxpython - Python下的GUI编程框架,与MFC的架构相似 
下载地址:http://wxpython.org/download.php 
PyQt - 用于Python的QT开发库 
下载地址:http://www.riverbankcomputing.com/software/pyqt/download 
Web框架 
Django - 开源web开发框架,它鼓励快速开发,并遵循MVC设计 
下载地址: http://www.djangoproject.com/ 
web2py - 一个小巧灵活的Web框架,虽然简单但是功能强大 
下载地址:http://web2py.com/ 
科学计算 
Matplotlib - 用Python实现的类matlab的第三方库,用以绘制一些高质量的数学二维图形 
下载地址:http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/ 
SciPy - 基于Python的matlab实现,旨在实现matlab的所有功能 
下载地址:http://pypi.python.org/pypi/scipy/ 
NumPy - 基于Python的科学计算第三方库,提供了矩阵,线性代数,傅立叶变换等等的解决方案 
下载地址:http://pypi.python.org/pypi/numpy/ 
网页处理 
BeautifulSoup,强大的容错功能,网页处理非常强大的包 
下载地址:http://www.crummy.com/software/BeautifulSoup/ 
PyQuery,在Python中如网页的 jQuery一样处理文档 
下载地址:https://pypi.python.org/pypi/pyquery 
文档地址:https://pythonhosted.org/pyquery/ 
其他函数库 
MySQLdb - 用于连接MySQL数据库 
下载地址:http://pypi.python.org/pypi/MySQL-python/ 
PIL - 基于Python的图像处理库,功能强大,对图形文件的格式支持广泛 
下载地址:http://effbot.org/zone/pil-index.htm 
PyGame - 基于Python的多媒体开发和游戏软件开发模块 
下载地址:http://www.pygame.org/download.shtml

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值