您的位置:首页 > 编程语言 > Python开发

看懂这些例子,一天之内学会python2

2016-03-01 19:15 726 查看
本文系笔者学习python之初,写的一些实例测试代码,其内容涵盖了python2的大部分内容,看完本文中的例子,编写一般的python程序,不成问题,若想深入学习python,本文也将是很好的入门实例教程。

# -*- coding: utf-8 -*-
########################变量不用定义,直接使用###############
str='hello,I am a string!'
print str
########################字符串简单输出######################
print "good"
print "\\\\_v//"
print "stay hungry,\nsttay foolish.\n--Steve Jobs"
print "*\n***\n****\n***\n*"
########################input()函数测试####################
print "please input a number:"
you=input()
print you
########################循环测试###########################
for c in me:
print c
if c is 'o':
print "c==o"
for i in range(0,11):
print i
while you<10000:
print you
you+=500

##########################输出相关操作#####################
str1="string1"
str2="string2"
#print后面加上逗号,不换行 但是自动加上空格
print str1,
print str2
print "**********"
print str1+str2
print str1.__add__("new")
print str1+str(you)
print "my age is %s"%you
print "my age is %d"%you
print "my age is %f"%you
print "%s has %s $"%(str1,you)
#保留三位小数
print "my age is %.3f"%you
#十六进制输出
print "my age is %o"%you
#十六进制输出
print "my age is %x"%you
#十六进制大写输出
print "my age is %X"%you
#类型转换
print int(you)
print float(you)
print str(you)
print bool(you)
#注意bool("False")结果为True,因为系统把False作为一个不为空的字符串处理
print bool("False")
#############################嵌套循环测试#################
for i in range(1,6):
for j in range(0,5):
if j<i:
print "*",
print "\n"
##############################函数定义调用################
#参数不用声明变量类型,有返回值可以直接返回,可给传递的参数的默认值
def myfunc(a=10,b=20):
return a+b
print myfunc(5,6)
print myfunc()
###############################list操作#################
list=["liurui",222,"jianhuo",1111]
list.append("dapeng")
list.append(666)
print list
#删除元素只能使用索引
del(list[2])

print list
#################################字符串操作###############
sentence="hello everyone,my name is du jiaoshou"
l1=sentence.split(' ')
print l1
l1=sentence.split('e')
print l1
newsen=''.join(l1)
print newsen
print newsen[2:]
print newsen[2:5]
print newsen[2:8:1]
##################################文件操作###############
############读操作
f=file("Rnn训练参数设置")
#data=f.read()
#print dataS
print "****************************************************************************"
#读一行
data2=f.readline()
print data2
print "************************************************"
#将所有的行读入到list中,
l2=f.readlines()
print l2
for i in range(0,len(l2)):
print l2[i]
print "****************"
f.close()
############写操作
#"w"会覆盖原来的内容,但"a"不会,会追加
f2=file("out.txt","w")
f2.write("hello,i am writing into this file")
f2.close()
#open方法与file用法相同
f3=open("out2.txt","w")
f3.write("hello,i am writing into this file")
f3.close()
print "****************************************************************************"
########################break continue测试#################
i=0
while i<5:
i+=1;
for j in range(3):
print j
if j==2:
break
for k in range(3):
if k==2:
continue
print k
if i>3:
break
print i
print "****************"
print "****************************************************************************"
################################异常处理#####################
try:
print int("fds")
except:
print "there is an exception"
print "****************************************************************************"
'''
'''
################################字典########################
score={"dujian":60,"dapeng":100,"jingke":0}
#读取
print score
print score["dujian"]
#修改
score["dujian"]=70
print score
#删除
del(score["dujian"])
print score
print "**********************"
#置空
score={}
#或者 del score
#添加元素方法一(当字典中不存在该索引的元素时自动添加到字典)
score["newdujian"]=12
#添加元素方法二
score.setdefault("newdapeng",14)
print score

#################################模块#######################
import random
#查看某个模块的函数集合
print dir(random)
#查看某个函数的帮助文档
help("_random")
print random.randint(0,10)
from random import randint as randomint
print randomint(5,7)

########json数据处理小程序
import urllib2
web=urllib2.urlopen("http://202.207.12.246/ZhongYangGuanLi/peiZhongAction!datagrid.action")
content=web.read()
import json
#此时data是一个字典
data=json.loads(content)
#print data
totalrows=data["total"]
rows=data["rows"]
#print totalrows
#print rows
#print type(rows)

items={}
#将json数据放入items的字典中,每个项目的内容个又是一个字典
for i in range(0,totalrows):
items[i+1]=rows[i]
print items[1]
print items[1]["note"]
#help(list)
#################################面相对象#######################
#def __init__()是构造函数(init前后有两个下划线),
#类中所有的方法都至少包含self参数,
#子类中若重写了__init__()函数,则覆盖父类中的构造函数
#一个类中只能有一个构造函数,当一个类中有多个构造函数时,最后一个构造函数将覆盖之前的函数
class object:
def __init__(self,name):
self.name=name
def showname():
print self.name

class animal(object):
def jiao(self):
print "the animal is jiaojiao~"
def showname(self):
print "the animal's name is:%s"%self.name

class human(object):

#会被四个参数的构造函数覆盖
def __init__(self,name,age):
self.name=name
self.age=age

def __init__(self,name,age,height):
self.name=name
self.age=age
self.height=height

def showname(self):
print "the human's name is:%s and age is:%s"%(self.name,self.age)

def show(self):
print self.name+" "+str(self.age)+" "+str(self.height)

def study(self):
print "%s is studing"%self.name

dog=animal("doudou")
dog.showname()
dog.jiao()

dapeng=human("dapeng",15,165)
dapeng.showname()
dapeng.study()

xpeng=human("xiaopeng",10,170)
xpeng.showname()
xpeng.study()
xpeng.show()
#################################python中的and-or#######################
a="i am a"
b="i am b"
c=True and a or b
d=False and a or b
print c
print d

a=0
b="i am b"
c=True and a or b
d=False and a or b
print c
print d
print "*******************"
#这里的and-or相当于 判别式?结果一:结果二
#二者相同的前提是 结果一 不能为假
#保险的做法是将a b封装成list集合[a],[b]然后再运算
#具体如下可以封装为一个函数:
def choose(bool,a,b):
return (bool and [a] or [b])[0]

c=choose(True,a,b)
print c

'''

#################################python中的正则表达式#######################

import re
text="sHis,I am hi Shirley his Hilton His. I eHi am his wife sHie."

#模糊匹配hi,区分大小写
#r表示不进行转义,元字符串本身是什么样就是什么样
m=re.findall(r"hi",text)
if m:
print m
else:
print "not match"
print "*********"
4000

#匹配以hi开头,区分大小写
m=re.findall(r"\bhi",text)
if m:
print m
else:
print "not match"
print "*********"
#严格匹配以hi结尾的词,区分大小写
m=re.findall(r"\bhi\b",text)
if m:
print m
else:
print "not match"
print "*********"
#严格匹配hi,区分大小写
m=re.findall(r"\bhi\b",text)
if m:
print m
else:
print "not match"
print "*********"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息