码迷,mamicode.com
首页 > 编程语言 > 详细

runoob_python

时间:2019-07-13 13:26:34      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:hat   sep   chdir   filename   元素   系统   全面   闭包   替换   

#-*-coding:utf-8-*-
import keyword
print(keyword.kwlist) #关键字

#反斜杠可以用来转义,使用r可以让反斜杠不发生转义。。 如 r"this is a line with \n" \n会显示,并不是换行。
#字符串有两种索引方式,从左往右以 0 开始,从右往左以 -1 开始。
#字符串的截取的语法格式如下:变量[头下标:尾下标:步长]
import sys

for i in sys.argv:
print(i)
print("\n python path", sys.path)

def getpair(dict):
for e ,y in dict.items():
print(e,y,sep=":")
getpair({ x : x**3 for x in (1,2,3,4)})

1:1
2:8
3:27
4:64


import time
print("hello")
time.sleep(2)
print("selen")


不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。
type()不会认为子类是一种父类类型。
isinstance()会认为子类是一种父类类型。

使用del语句删除一些对象引用。

列表截取可以接收第三个参数,参数作用是截取的步长


def reverseWords(input):
#通过空格将字符串分隔符,把各个单词分隔为列表
inputword = input.split(" ")
print(inputword)
# 第一个参数 -1 表示最后一个元素
# 第二个参数为空,表示移动到列表末尾
# 第三个参数为步长,-1 表示逆向
inputword = inputword[-1::-1]
print(inputword)
output = ‘ ‘.join(inputword)
#序列中的元素以指定的字符连接生成一个新的字符串
return output
if __name__ == "__main__":
input = "I like runboob"
rw = reverseWords(input)
print(rw)

#元组写在小括号 () 里,元素之间用逗号隔开

#stringlist tuple 都属于 sequence(序列)。
#集合(set)是由一个或数个形态各异的大小整体组成的,构成集合的事物或对象称作元素或是成员。

#<class ‘__main__.son‘> super()函数是用来调用父类(超类)的一个方法
#PATH=$PATH:/usr/local/python3/bin/python3
#Python 解释器可不止一种哦,有 CPythonIPythonJythonPyPy
#is 用于判断两个变量引用对象是否为同一个, == 用于判断引用变量的值是否相等。

a=0
b=20
print(a and b) #若所有值均为真,则返回最后一个值,若存在假,返回第一个假值;
import random
print(random.randint(1000,9999))

lst=random.sample("*&%&%#",4) # 4
print(lst)
#首先要导入运算符模块
import operator
print(operator.gt(2,6))
#decimal 模块提供了一个 Decimal 数据类型用于浮点数计算,拥有更高的精度。

import decimal
decimal.getcontext().prec = 4
print(decimal.Decimal(1)/decimal.Decimal(3)) #0.3333

#str.find(str, beg=0, end=len(string))

#list_2d = [[0 for col in range(cols)] for row in range(rows)] 创建二维列表

list_2d = [[5 for col in range(0,5)] for row in range(0,5)]

print(list_2d)

#[(5, 9), (7, 9), (9, 9)]
print ([ (x, y) for x in range(10) if x % 2 if x > 3 for y in range(10) if y > 7 if y != 8 ])

#键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行,

s = set()
s.add("4")
#参数可以是列表,元组,字典等
s.update([‘hhh‘])
#元素不存在,不会发生错误。
s.discard("ooo")
print(s)


#print("================= welcome ============================")
conl = "N"
while conl==‘N‘:
try:
age1 = int(input())


if age1 == 1:
print(" ok")
except ValueError:
print("input error"+ValueError)



var = 1
while var == 1: # 表达式永远为 true
num = int(input("输入一个数字 :"))
print("你输入的数字是: ", num)

print("Good bye!")



# 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。 迭代器有两个基本的方法:iter() next()
#字符串,列表或元组对象都可用于创建迭代器:
import sys
list = [1,4,7,9]
it = iter(list) # 创建迭代器对象
while True:
# try:
print(next(it))
# except StopIteration:
# sys.exit()

#使用了 yield 的函数被称为生成器(generator)。
#生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。
#yield有点像断点。 加了yield的函数,每次执行到有yield的时候,

#strings, tuples, numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象。
# 不可变类型:类似 c++ 的值传递,如 整数、字符串、元组。如funa),传递的只是a的值,没有影响a对象本身。比如在 funa)内部修改 a 的值,只是修改另一个复制的对象,不会影响 a 本身。

# 可变类型:类似 c++ 的引用传递,如 列表,字典。如 funla),则是将 la 真正的传过去,修改后fun外部的la也会受影响


必需参数
关键字参数
默认参数
不定长参数
def ChangeNumber(a):
a=10
b=2
ChangeNumber(b)

print(b)

使用关键字参数允许函数调用时参数的顺序与声明时不一致,

加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。






def printinfor(arg1,*vartuple):
print(arg1)
print(vartuple)
printinfor(14,32,65,34,322)
#14 (32, 65, 34, 322)

#加了两个星号 ** 的参数会以字典的形式导入。 如果单独出现星号 * 后的参数必须用关键字传入。
#所谓匿名,意即不再使用 def 语句这样标准的形式定义一个函数。

sum = lambda arg1, arg2: arg1 + arg2
print(sum("aa","bb")


num = 1
def fun1():
global num
num = 123

fun1()
print(num)

g_count = 0 # 全局作用域
def outer():
o_count = 1 # 闭包函数外的函数中
def inner():
i_count = 2 # 局部作用域



#列表推导式提供了从序列创建列表的简单途径。
#把这些定义存放在文件中,为一些脚本或者交互式的解释器实例使用,这个文件被称为模块。

import thread
if __name__ == "__main__":
print("self")
else:
print("other")



str(): 函数返回一个用户易读的表达形式。


repr(): 产生一个解释器易读的表达形式。

字符串对象的 rjust() 方法, 它可以将字符串靠右,
方法 zfill(), 它会在数字的左边填充 0


f = open("path.txt","r")

str = f.read()

# pickle.dump(obj,file,[,protocol]) pickle.load(file)



from urllib import request
import pickle
import os

res = request.urlopen("http://www.baidu.com/")
#print(str(res.read()))


datafile="person.data"

line = "========================="

message = r
=========================
welcom bookmark
press 1 to show
press 2 to add
press 3 to edit
press 4 to delete
press 5 to search
press 6 to show all
press 0 to exit

print(message)

class Person(object):
def __init__(self,name,number):
self.name = name
self.number = number
def get_data(filename = datafile):
if os.path.exists(filename) and os.path.getsize(filename):
with open(filename,"rb") as f:
return pickle.load(f)
return None

def set_data(name,number,filename = datafile):
personList = {} if get_data() == None else get_data()
with open(filename,"wb") as f:
personList[name] = Person(name,number)
pickle.dump(personList,f)

def save_data(dictPerson,filename = datafile):
with open(filename,"wb") as f:
pickle.dump(dictPerson,f)
def show_all():
personList = get_data()
print(type(personList))
if personList:
for v in personList.values():
print(v.name,v.number)
print(line)
else:
print("there is emperty")
def add_person(name,number):
set_data(name,number)
print("sucess add person")
print(line)
def edit_person(name, number):
personList = get_data()
if personList:
personList[name] = number
save_data(personList)
print("sucess edit person")
print(line)
def delete_person(name):
personList = get_data()
if personList:
if name in personList:
del personList[name]
print("del sucess")

else:
print("the name is not exists")
print(line)
else:
print("the personMark is empty")

def search_person(name):
personList = get_data()
if personList:
if name in personList.keys():
print(name,end="")
print(personList.get(name)) #value

# print(personList.get(name).name,personList.get(name).number)
else:
print("No this person of ",name)
print(line)

while True:
num = input(‘>>‘)
if num == ‘1‘:
print("show all personList:")
show_all()
elif num == ‘2‘:
print("add person:")
name = input("input name>>")
number = input("number>>")
add_person(name,number)
elif num ==‘3‘:
print("edit person:")
name = input("input name>>")
number = input("input number")
edit_person(name,number)
elif num == ‘4‘:
print("delete person:")
name = input("input name:")
delete_person(name)
elif num == ‘5‘:
print("search :")
name = input("input name>>")
search_person(name)
elif num == ‘6‘:
print(message)
elif num == ‘0‘:
break
else:
print("input error ,please retry")


#file 对象使用 open 函数来创建,
f = open("person.data",‘rb‘)
print(f.fileno())

# strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列



import os

def Replace(filename,rep_word,new_word):
with open(filename,‘r‘) as f:
content = []
count = 0

for eachline in f:
if rep_word in eachline:
count += eachline.count(rep_word)
print("count: ",count)
eachline = eachline.replace(rep_word,new_word)
content.append(eachline)
decide = input(r‘file {0} has {1} word [ {2}] are you sur to repalce {3} to {4} ? [yes\no]:‘.format\
(filename,count,rep_word,rep_word,new_word))
if decide in [‘yes‘,‘y‘,‘YES‘,‘Y‘]:
print(content)
with open(filename,"w") as f:
f.writelines(content)
print("sucess")
else:
print("Exit")
if __name__ == "__main__":
while True:
filename = input("filename:>>")
if filename in os.listdir():
rep_word=input(" old_word:")
new_word = input("new_word:")
Replace(filename,rep_word,new_word)
break
else:
print("Do not find such file {}".format(filename))


import os
str = os.chdir(‘/home‘)
print(str)



class MyError(Exception):
def __init__(self,value):
self.value = value
def __str__(self):
return repr(self.value) #__str__()函数就可以帮助我们打印对象中具体的属性值


try:
raise MyError(2*2)
except MyError as e:
print("MyError except :",e.value)


类变量:类变量在整个实例化的对象中是公用的。


class Parent(object):
def myMethod(self):
print("Parent")
class Child(Parent):
pass
c = Child()
super(Child,c).myMethod()

支持运算符重载
class vec(object):
def __init__(self,a,b):
self.a = a
self.b = b
def __str__(self):
return ‘Vector(%d,%d)‘%(self.a,self.b)
def __add__(self,other):
return vec(self.a+other.a, self.b + other.b)
def __

v1 = vec(2,19)
v2 = vec(2,19)
print(v1+v2)


class Text(object):
def Instance(self):
print("Instancefun")
print(self)
@classmethod #类方法
def ClassFun(cls):
print("classFun")
print(cls)
@staticmethod
def StaticFun():
print("StaticFun")

t = Text()
t.ClassFun()
t.Instance()
Text.StaticFun()




class People(object):
name =""
age =0
__weight=0
def __init__(self,name,age,weight):
self.name = name
self.age = age
self.__weight =weight
def speck(self):
print("%s say : i an %d"%(self.name,self.age))

class Student(People):
grade = " "
def __init__(self,n,a,w,g):
People.__init__(self,n,a,w)
self.grade = g

def speak(self):
print("%s say i %d in %d "%(self.name,self.age,self.grade))




p = People("python",10,20)
p.speck()
print(p.name,p.age)


import shutil
import os
import glob

print(glob.glob(‘*.py‘))

shutil.copy("runoob.py",‘copy2.py‘)
print(os.getcwd()) # 返回当前的工作目录

print(glob.glob("*.py"))

os.chdir("/home/selen/")
#os.system("ls") #执行系统命令
print(dir(glob))

import sys
print(sys.argv)

import re
# f开头所有单词
str=re.findall(r‘\bf[a-z]*‘,‘which foot or hand fell fastet‘)
print(str)

str=re.sub(r‘(\b[a-z]+)\1‘,r‘\1‘,‘cat in the the hat‘)
print(str)
re.sub(pattern, repr,string, count=0,flags=0)
patten1 : 一个字符串也可以是一个正则
repl是将会被替换的值
\g<1> 代表前面pattern里面第一个分组,



import math


import random

print(random.choice([‘apple‘,‘pear‘,‘banana‘]))

print(random.sample(range(100),10))

print(random.randrange(6))

import zlib
from urllib.request import urlopen
num = ‘百度推广
for line in urlopen("http://www.baidu.com"):
line = line.decode(‘utf-8‘)
if num in line:
#print(line)

#line = urlopen(‘http://www.baidu.com‘)
#line=line.decode(‘utf-8‘)
print(len(line))
line = b‘line‘
t = zlib.compress(line)
print(len(t))
print(t)




from timeit import Timer

t=Timer(‘t=a;a=b;b=t‘,‘a=1;b=2‘).timeit()
print(t)


def average(values):



return sum(values)/len(values)

import doctest
#doctest.testmod()
# unittest模块不像 doctest模块那么容易使用,不过它可以在一个独立的文件里提供一个更全面的测试集:

runoob_python

标签:hat   sep   chdir   filename   元素   系统   全面   闭包   替换   

原文地址:https://www.cnblogs.com/countryboy666/p/11180258.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!