python部分内容存档
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python部分内容存档相关的知识,希望对你有一定的参考价值。
笨办法学python. 1
Ec6字符串和文本... 1
ec7. 1
ec8. 1
Ec9. 1
Ec10 转义字符... 1
Ec11提问... 1
raw_input和input的区别... 1
Ec12提示别人... 1
ec13 参数,解包,变量... 1
ec14提示和传递... 1
Ec15读取文件... 1
Ec16读写文件... 1
ec17更多文件操作... 1
ec18命名,变量,代码,函数... 1
ec19函数和变量... 1
ec20函数和文件... 1
ec21函数可以返回东西... 1
ec24. 1
Ec25自己写函数作为脚本,文档注释... 1
Ec31 if & raw_input() 1
ec33while. 1
ec35用函数写的一个小的选择游戏... 1
ec39列表的操作... 1
ec40字典... 1
map 函数应用... 1
ec41函数写小型地图游戏,raw_input提示给答案... 1
ec随机数用法... 1
getattr用法... 1
Ec42class写ec41的游戏... 1
ec处理异常try & except 1
From实验楼... 1
Pathbao.py. 1
sy1 glob. 1
Sy2 os包... 1
shutil包... 1
Pickle包... 1
subprocess包... 1
thread包... 1
multiprocessing包... 1
读取中文... 1
Sy6.py线程实验售票系统... 1
sy6.py用类实现... 1
ascii.py argparse操作分解... 1
sy8.py argparse 操作最终... 1
pic_change_str.py 实验楼图片转字符画课程... 1
2048系列代码... 1
主程序代码... 1
2048cp zip/for的用法... 1
2048cp1 curse的颜色设置。。... 1
2048cp2研究curses的一些用法,很奇怪,还不精... 1
2048cp3#边框的画法,控制数组大小和里面值是否出现... 1
2048cp4学习defaultdict的用法... 1
2048read_input.py. 1
2048hasatta的用法... 1
2048format的用法... 1
2048clear 1
Jianming. 1
Cat 1
class_inherit 1
class_init 1
finally. 1
gui 1
gui2. 1
inherit 1
Lambda. 1
list_comprehension. 1
method. 1
my_module. 1
my_module1. 1
Pickling. 1
powersum.. 1
print_one_line. 1
threading. 1
threading2. 1
try_except 1
菜鸟教程... 1
Using_copy. 1
using_dict 1
using_file. 1
using_list 1
using_name. 1
Using_slice. 1
using_str 1
using_tuple. 1
菜鸟教程例子... 1
sl1. 1
sl2. 1
sl3. 1
sl4. 1
sl5. 1
Sl6. 1
sl7. 1
sl11. 1
sl12. 1
sl13. 1
sl14. 1
sl17. 1
sl18. 1
sl19. 1
sl20. 1
sl21. 1
Sl22. 1
sl23. 1
Sl24. 1
Sl25. 1
Sl26. 1
Sl27. 1
sl28. 1
Sl29. 1
Sl30. 1
Mysql教程... 1
1.创建数据库... 1
2.删除数据库... 1
3.创建表... 1
4.删除表... 1
5修改表... 1
(1) 修改表类型,语法如下:... 1
(2)增加表字段,语法如下:... 1
(3)删除表字段,语法如下:... 1
(4)字段改名,语法如下:... 1
(5)修改字段排列顺序... 1
(6)表改名,语法如下:... 1
DML 语句... 1
插入记录... 1
更新记录... 1
删除记录... 1
查询记录... 1
(1) 查询不重复的记录。... 1
(2)条件查询... 1
(3)排序和限制... 1
(4)聚合... 1
Asdghjgu
Ashdgasbjdb
Asdhgajsd
笨办法学python
Ec6字符串和文本
x=‘there are %d types of people‘ % 10
binary=‘binary‘
do_not="don‘t"
y=‘those who know %s and those who %s.‘%(binary,do_not)
print(x)
print(y)
print(‘I saied: %r.‘ % x)
print("I also said: ‘%s‘."% y)
hilarious = False
joke_evaluation="Isn‘t that joke so funny?! %r"
print(joke_evaluation % hilarious)
w="this is the left side of.."
e=‘a string with a right side.‘
print(w+e)
ec7
print(‘Mary had a little lamb.‘)
print("its fleece was white as %s."% ‘snow‘)
print("And everywhere that Mary went.")
print ("." * 10) #what the fk这边是出现10次
end1="C"
end2=‘h‘
end3=‘e‘
end4=‘e‘
end5=‘s‘
end6=‘e‘
end7=‘B‘
end8=‘u‘
end9=‘r‘
end10=‘g‘
end11=‘e‘
end12=‘r‘
print(end1+end2+end3+end4+end5+end6,)
print(end7+end8+end9+end10+end11+end12)
ec8
formatter=‘%r %r %r %r‘
print(formatter %(1,2,3,4))
print(formatter %(‘one‘,‘two‘,‘three‘,‘four‘))
print(formatter %(True,False,False,True))
print(formatter %(formatter,formatter,formatter,formatter))
print(formatter % (
"I had this thing.",
‘That you could type up right.‘,
"But it didn‘t sing.",
"So I said goodnight."
))
Ec9
days ="\nMon Tue Wed Thu Fri Sat Sun"
months="\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print("Here are the days:",days)
print("\n\nHere are the months:",months)
#print(‘what fc‘)#这样写就不会换行,很正常的写法
print(‘‘‘
what fc
‘‘‘)#这样写就会换行,应该是‘‘‘起作用
Ec10 转义字符
#--coding:utf-8 --
tabby_cat ="\tI‘m tabbed in."
persian_cat ="I‘m split\non a line."
backslash_cat="I‘m \\ a \\ cat."
fat_cat="""
I‘ll do a list:
\t* Cat food
\t* Fishes
\t* Catnip\n\t* Grass
"""
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)
‘‘‘
所有的转义字符和所对应的意义:
转义字符
意义
ASCII码值(十进制)
\a
响铃(BEL)
007
\b
退格(BS) ,将当前位置移到前一列
008
\f
换页(FF),将当前位置移到下页开头
012
\n
换行(LF) ,将当前位置移到下一行开头
010
\r
回车(CR) ,将当前位置移到本行开头
013
\t
水平制表(HT) (跳到下一个TAB位置)
009
\v
垂直制表(VT)
011
\\
代表一个反斜线字符‘‘\‘
092
\‘
代表一个单引号(撇号)字符
039
\"
代表一个双引号字符
034
\?
代表一个问号
063
\0
空字符(NULL)
000
\ooo
1到3位八进制数所代表的任意字符
三位八进制
\xhh
1到2位十六进制所代表的任意字符
二位十六进制
注意:区分,斜杠:"/" 与 反斜杠:"\" ,此处不可互换
Ec11提问
print "How old are you?",
age=raw_input()
print "How tall are you?",
height =raw_input()
print "How much do you weigh?",
weight =raw_input()
print "So,you‘re %r old,%r tall and %r heavy." %(age,height,weight)
raw_input和input的区别
1 >>> raw_input_A = raw_input("raw_input: ")
2 raw_input: abc
3 >>> input_A = input("Input: ")
4 Input: abc
5
6 Traceback (most recent call last):
7 File "<pyshell#1>", line 1, in <module>
8 input_A = input("Input: ")
9 File "<string>", line 1, in <module>
10 NameError: name ‘abc‘ is not defined
11 >>> input_A = input("Input: ")
12 Input: "abc"
13 >>>
复制代码
复制代码
1 >>> raw_input_B = raw_input("raw_input: ")
2 raw_input: 123
3 >>> type(raw_input_B)
4 <type ‘str‘>
5 >>> input_B = input("input: ")
6 input: 123
7 >>> type(input_B)
8 <type ‘int‘>
9 >>>
复制代码
例子 1 可以看到:这两个函数均能接收 字符串 ,但 raw_input() 直接读取控制台的输入(任何类型的输入它都可以接收)。而对于 input() ,它希望能够读取一个合法的 python 表达式,即你输入字符串的时候必须使用引号将它括起来,否则它会引发一个 SyntaxError 。
例子 2 可以看到:raw_input() 将所有输入作为字符串看待,返回字符串类型。而 input() 在对待纯数字输入时具有自己的特性,它返回所输入的数字的类型( int, float );同时在例子 1 知道,input() 可接受合法的 python 表达式,举例:input( 1 + 3 ) 会返回 int 型的 4 。
就是说input处理数字的时候会确定类型,而raw_input全都是字符型,无所谓。
Ec12提示别人
age=raw_input("How old are you?")
height =raw_input("How tall are you?")
weight =raw_input("How much do you weigh?")
print "So,you‘re %r old, %r tall and %r heavy."%(age,height,weight)
ec13 参数,解包,变量
from sys import argv
script, first, second, third = argv
print "The script is called:" , script
print "Your first variable is:",first
print "Your second variable is:",second
print "Your third variable is:",third
ec14提示和传递
from sys import argv
script, user_name=argv
prompt = ‘‘
print "Hi %s, I‘m the %s script." %(user_name,script)
print "I‘d like to ask you a few questions."
print "Do you like me %r?" %user_name
likes=raw_input(prompt)
print "Where do you live %s?" % user_name
lives =raw_input(prompt)
print "What kind of computer do you have?"
computer =raw_input(prompt)
print """
Alright, so you said %r about likeing me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" %(likes,lives,computer )
#搞清楚了%r和%s的区别,r是后面引用字符串的时候会接引号,而s不会接引号
Ec15读取文件
#coding=utf-8 #添加这个可以使用中文注释
from sys import argv
script, filename= argv#"获取文件名"
txt=open(filename)#Python -m pydoc open来查看相关意思
print("Here‘s your file %r:")% filename
print txt.read()
print(txt.closed)
txt.close()
print(txt.closed)
# print "Type the filename again:"
# file_again=raw_input(">>>>")
# txt_again= open(file_again)
# print txt_again.read()
Ec16读写文件
#coding=utf-8
from sys import argv
script,filename=argv
print"We‘re going to erase %r." %filename
print"If you don‘t want that,hit CTRL-C (^C)."
print"If you do want that,hit RETURN."
raw_input("?")
print"Opening the file..."
target=open(filename,‘w‘)
print"Truncating the file. Goodbye!"
target.truncate()
print"Now I‘m going to ask you for three lines."
line1=raw_input("line1:")
line2=raw_input("line2:")
line3=raw_input("line3:")
print"I‘m going to write these to the file."
#target.write(line1 & "\n" & line2 & "\n" & line3 )#这种连接的用法找找看
target.write("%s\n%s\n%s" %(line1,line2,line3))#此刻我想说还是我大结构化靠谱!
print"And finally, we close it."
target.close()
ec17更多文件操作
#coding=utf-8
from sys import argv
from os.path import exists
script,from_file,to_file = argv
print "Copying from %s to %s" %(from_file,to_file)
#we could do these two on one line too,how?
input =open(from_file)
indata=input.read()
print ‘‘‘The input file is %d bytes long,
Does the output file exist?%r,
Ready,hit RETURN to continue,CTRL-C to abort.
‘‘‘%(len(indata),exists(to_file))#用了‘‘‘分行显示,格式化不晓得能不能分行。
raw_input()
output=open(to_file,‘w‘)
output.write(indata)
print"Alright,all done."
output.close()
input.close()
ec18命名,变量,代码,函数
#coding=utf-8
#This one is like your scripts with argv
def print_two(*args):
arg1,arg2,arg3=args
print"arg1:%r,arg2:%r,arg3;%s" %(arg1,arg2,arg3)
#ok \, that *args is actually pointless, we can just do this
def print_two_again(arg1,arg2):
print "arg1:%r.arg2:%r" %(arg1,arg2)
#注意区分上下两个的用法
#this just take one arguement
def print_one(arg1):
print"arg1:%r" % arg1
#this one takes no arguement
def printnone():
print "I got nothin‘."
print_two("Zed","Shaw",‘wtf‘)
print_two_again("Zed","Shaw")
print_one("First!")
printnone()
ec19函数和变量
#coding=utf-8
def cheese_and_crackers(cheese_count,boxes_of_crackers):
print"You have %d cheeses!"% cheese_count
print"You have %d boxes of crackers!"% boxes_of_crackers
print"Man that‘s enough for a party!"
print"Get a blanket.\n"
print"We can just give the function numbers directly:"
cheese_and_crackers(20,30)
print"Or, we can use variables from our scripts:"
amount_of_cheese=10
amount_of_crackers=50
cheese_and_crackers(amount_of_cheese,amount_of_crackers)
print"We can even do math inside too:"
cheese_and_crackers(10+20,5+6)
print"And we can combine the two,variables and math:"
cheese_and_crackers(amount_of_cheese+100,amount_of_crackers+1000)
ec20函数和文件
#coding=utf-8
from sys import argv
script,input_file=argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count,f):
print line_count,f.readline()#这个是如何实现每一行都读取,是个问题
current_file=open(input_file)
print "First let‘s print the whole file:\n"
print_all(current_file)
print"\nNow let‘s rewind,kind of like a tape."
rewind(current_file)
print"Let‘s print three lines:"
current_line=1
print_a_line(current_line,current_file)
current_line=10
print_a_line(current_line,current_file)
# current_line=current_line+1
# print_a_line(current_line,current_file)
print_a_line(3,current_file)
print_a_line(3,current_file)
print_a_line(3,current_file)#果然不是按照行号来的
ec21函数可以返回东西
#coding=utf-8
def add(a,b):
print"Adding %d+%d"%(a,b)
return a+b
def subtract(a,b):
print"Suntracting%d-%d"%(a,b)
return a-b
def multiply(a,b):
print"Multiplying%d*%d"%(a,b)
return a*b
def divide(a,b):
print"Dividing%d/%d"%(a,b)
return a/b
print"let‘s do some math with just functions!"
age=add(30,5)
height=subtract(78,4)
weight=multiply(90,2)
iq=divide(100,2)
print"Age: %d, Height: %d, Weight: %d, IQ: %d"%(age,height,weight,iq)
#A puzzle for the extra credit, type it in anyway.
print"Here is a puzzle."
what = add(age,subtract(height,multiply(weight,divide(iq,2))))
print "That becomes:", what, "Can you do it by hand?"
ec24
#coding=utf-8
print"Let‘s practice everything."
print"You\‘d neen to know \‘bout escape with \\ theat do \n newlines and \t tabs"
poem="""
\t The lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intution
and requires an explanation
\n\twhere there is none.
"""
print"------"
print poem
print"------"
five = 10-2+3-6
print"This should be five:%s"% five
def secret_formula(started):
jelly_beans=started * 500
jars=jelly_beans / 1000
crates=jars / 100
return jelly_beans, jars, crates
start_point=10000
beans, jars, crates = secret_formula(start_point)
print "With a starting point of: %d" % start_point
print "We‘d have %d beans, %d jars, and %d crates."% (beans, jars, crates)
start_point = start_point /10
print "We can also do that this way:"
print "We‘d have %d beans, %d jars, and %d crates."% secret_formula(start_point)
#函数return的几个值都可以用作结格式数据里面里面
Ec25自己写函数作为脚本,文档注释
#coding=utf-8
def break_words(stuff):
‘‘‘This function will break up words for us.‘‘‘
#这些东西是放在‘‘‘之间的,文档注解,documentation commnets,大型项目可供查阅!
# 如何查阅?python -m pydoc ec25
words = stuff.split(‘ ‘)
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)#对单个词进行排序
def print_first_word(words):
"""Prints the first word after popping if off."""
word =words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping if off."""
word =words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)#句子排序,先拆分词。
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words=break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words=sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
#这一节学完,知道可以以后自己写函数作为脚本,然后不停的import就行,
# 注意函数之间写文档注释,这个也很屌。
Ec31 if & raw_input()
#coding=utf-8
print"You enter a dark room with two doors. "
print"Do you go through door #1 or door #2?"
door =raw_input(">>>>>>")
if door == "1":
print"There‘s a giant bear here eating a cheese cake. What do you do?"
print"1. Take the cake."
print"2. Scream at the bear."
bear = raw_input(">>>>>>")
if bear == "1":
print"The bear eats your face off. Good job!"
elif bear == "2":
print"The bear eats your legs off. Good job!"
else:
print"Well, doing %s is probably better. Bear runs away."% bear
elif door == "2":
print"You stare into the endless abyss at Cthulhu‘s retina."
print"1. Blueberries.\n2. Yellow jacket clothespins."
print"3. Understanding revolvers yelling melodies."
insanity = raw_input(">>>>>>")
if insanity == "1" or insanity =="2":
print"Your body survies powered by a mind of jello. Good job!"
else:
print"The insanity rots your eyes into a pool of muck. Good job!"
else:
print"Your stumble around and fall on a knife and die. Good job!"
ec33while
#coding=utf-8
i=0
numbers=[]
while i<6:
print"At the top i is %d"% i
numbers.append(i)
i=i+1
print"Numbers Now:",numbers
print"At the bottom i is %d" % i
print"The numbers:"
for num in numbers:
print num
ec35用函数写的一个小的选择游戏
#coding=utf-8
from sys import exit
def gold_room():
print"This room is full of gold. How much do you take?"
next =raw_input(">~>")
if "0" in next or "1" in next:#判断输入是否有0或1,要包含所有的数字
how_much = int(next)
else:
dead("Man, learn to type a number.")
if how_much < 50:
print"Nice, you‘re not greedy, you win!"
exit()
else:
dead("You greedy bastard!")
def bear_room():
print"There is a bear here."
print"The bear has a bunch of honey."
print"The fat bear is in front of another door."
print"How are you going to move the bear?"
bear_moved=False
while True:
next =raw_input(">~>")
if next == "take honey":
dead("The bear looks at you then slaps your face off.")
elif next == "taunt bear" and not bear_moved:
print"The bear has moved from the door. You can go through it now."
bear_moved=True
elif next == "taunt bear" and bear_moved:
dead("The bear gets pissed off and chews your leg off.")
elif next == "open door" and bear_moved:
gold_room()
else:
print"I got no idea what that means."
def cthulhu_room():
print"Here you see the great evil Cthulhu."
print"He, it, whatever stares at you and you go insane."
print"Do you flee for your life or eat your head?"
next = raw_input(">~>")
if "flee" in next:
start()#这边就起到回调的作用,游戏中的返回。。。很好用啊
elif "head" in next:
dead("Well that was tasty!")
else:
cthulhu_room()
def dead(why) :
print why, "Good job!"
exit(0)
def start():
‘‘‘Game start from here!‘‘‘
print"You are in a dark room."
print"There is a door to your right and left."
print"which one do you take?"
next = raw_input(">~>")
if next == "left":
bear_room()
elif next =="right":
cthulhu_room()
else:
dead("You stumble around the room until you starve.")
start()
ec39列表的操作
#coding=utf-8
ten_things="Apples Oranges Crows Telephone Light Sugar"
print"Wait there‘s not 10 things in that list,let‘s fix that."
stuff = ten_things.split(‘ ‘)
more_stuff = ["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]
print "stuff is %r\nand it‘s lens is %d"% (stuff,len(stuff))
while len(stuff) != 10:
next_one = more_stuff.pop()#从more_stuff的最后一项挑出来放到stuff中
print "Adding:", next_one
stuff.append(next_one)#这种用法非常适合两个List之间互换
print "There‘s %d items now."% len(stuff)
print"there we go: ",stuff
print"Let‘s do some things with stuff."
print stuff[1]
print stuff[-1]
print stuff.pop()
print ‘<>‘.join(stuff)#join的用法
print ‘#‘.join(stuff[3:6])#下限是不包含的
ec40字典
#coding=utf-8
stuff={1:"dahu",2:"daqing",3:"tech"}
#print stuff[2]
stuff[‘city‘]=‘jianhu‘
#print stuff[‘city‘]
stuff[55]=2
#print stuff
cities={"CA": ‘San Francisco‘, "MI": ‘Detroit‘, "FL": ‘Jacksonville‘}
cities["NY"]="New York"
cities["OR"]="Portland"
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return"Not found."
#OK pay attention!
# cities["_find"]=find_city#函数也可以作为一个变量
while True:
print "State?(Enter to quit)",
state = raw_input(">>>")
if not state:break
#this line is the most important
# city_found=cities["_find"](cities,state)
#这个运行时会在字典里建立_find键,其实没必要
city_found=find_city(cities,state)
print city_found
print cities
map 函数应用
def add100(x):
return x+100
hh=[11,22,33]
a=map(add100,hh)
print "a is " ,a
def abc(a,b,c):
return a*10000+b*100+c
list1=[11,22,33]
list2=[44,55,66]
list3=[77,88,99]
b=map(abc,list1,list2,list3)
print b
c=map(None,list1)
print c
d=map(None,list1,list2,list3)
print d
ec41函数写小型地图游戏,raw_input提示给答案
#coding=utf-8
from sys import exit
from random import randint
def death():
quips = ["You died. You kinda suck at this.",
"Nice job, you died ...jackass.",
"Such a loser.",
"I have a small puppy that‘s better at this."]
print quips[randint(0,len(quips)-1)]
exit()
def central_corridor():
print"The Gothons of Planet Percal #25 have invaded your ship and destroyed"
print"your entire crew. You are the last surviving member and your last"
print"mission is to get the neutron destruct bomb from the Weapons Armory,"
print"put it in the bridge, and blow the ship up after getting into an"
print"escape pod.\n"
print"You‘re running down the central corridor to the Weapons Armory when"
print"a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
print"flowing around his hate filled body. He‘s blocking the door to the"
print"Armory and about to pull a weapon to blast you."
action=raw_input(‘‘‘\nI‘l give you some advice>>
\n shoot!\t dodge!\t tell a joke\t\n>>‘‘‘)
if action == "shoot!":
print "Quick on the draw you yank out your blaster and fire it at the Gothon."
print "His clown costume is flowing and moving around his body, which throws"
print "off your aim. Your laser hits his costume but misses him entirely. This"
print "completely ruins his brand new costume his mother bought him, which"
print "makes him fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats you."
return ‘death‘
elif action == "dodge!":
print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon‘s blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "bang your head on the metal wall and pass out."
print "You wake up shortly after only to die as the Gothon stomps on"
print "your head and eats you."
return ‘death‘
elif action == "tell a joke":
print "Lucky for you they made you learn Gothon insults in the academy."
print "You tell the one Gothon joke you know:"
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
print "The Gothon stops, tries not to laugh, then busts out laughing and can‘t move."
print "While he‘s laughing you run up and shoot him square in the head"
print "putting him down, then jump through the Weapon Armory door."
return ‘laser_weapon_armory‘
else:
print "DOES NOT COMPUTE!"
return ‘central_corridor‘
def laser_weapon_armory():
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It‘s dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There‘s a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can‘t"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" %(randint(1,9),randint(1,9),randint(1,9))
print"Code is %s" % code
guess=raw_input("[keypad]> ")
guesses=0
while guess != code and guesses <10:
print "BZZZEDD!"
guesses +=1
guess =raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return ‘the_bridge‘
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return ‘death‘
def the_bridge():
print "You burst onto the Bridge with the neutron destruct bomb"
print "under your arm and surprise 5 Gothons who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven‘t pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don‘t want to set it off."
action=raw_input(‘‘‘\nI‘l give you some advice>>
\n throw the bomb\t slowly place the bomb\t\n>>‘‘‘)
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return ‘death‘
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can‘t get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return ‘escape_pod‘
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
def escape_pod():
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don‘t have time to look. There‘s 5 pods, which one"
print "do you take?"
good_pod = randint(1,5)
print "good_pod is %d" % good_pod
guess = raw_input("[pod #]> ")
if int(guess) !=good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return ‘death‘
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
exit(0)
Rooms={
‘death‘: death,
‘central_corridor‘:central_corridor,
‘laser_weapon_armory‘:laser_weapon_armory,
‘the_bridge‘:the_bridge,
‘escape_pod‘:escape_pod}
def runner(map, start):
next = start
while True:
room = map[next]
print "\n------"
next = room() #这句话操作层面算是理解了,
# 但是按顺序应该在---的后面,但在powersheel中出现在前面,这是为什么
print">>next<<",next
runner(Rooms,‘central_corridor‘)
ec随机数用法
#coding=utf-8
from sys import exit
from random import randint
def death():
quips = ["You died. You kinda suck at this.",
"Nice job, you died ...jackass.",
"Such a loser.",
"I have a small puppy that‘s better at this."]
# print len(quips)-1
a= randint(0,3) #取随机数的两端都可以取到!
print a
print quips[a]
exit()
death()
getattr用法
#coding=utf-8
class A:
def __init__(self):
self.name = ‘zhangjing‘
self.age=‘24‘
def method(self):
print"method print"
Instance = A()
print getattr(Instance , ‘name‘) #如果Instance 对象中有属性name则打印self.name的值,否则打印‘not find‘
print getattr(Instance , ‘age‘) #如果Instance 对象中有属性age则打印self.age的值,否则打印‘not find‘
print getattr(Instance, ‘method‘, ‘default‘)
#如果有方法method,打印其地址,否则打印default
print getattr(Instance, ‘method‘, ‘default‘)()
#如果有方法method,运行函数并打印None否则打印default
Ec42class写ec41的游戏
#coding=utf-8
from sys import exit
from random import randint
class Game(object):
def __init__(self,start):
self.quips=["You died. You kinda suck at this.",
"Nice job, you died ...jackass.",
"Such a loser.",
"I have a small puppy that‘s better at this."
]
self.start = start
def play(self):
next =self.start
while True:
print"\n-----"
room = getattr(self,next)
next = room()
def death(self):
print self.quips[randint(0,len(self.quips)-1)]
exit()
def central_corridor(self):
print"The Gothons of Planet Percal #25 have invaded your ship and destroyed"
print"your entire crew. You are the last surviving member and your last"
print"mission is to get the neutron destruct bomb from the Weapons Armory,"
print"put it in the bridge, and blow the ship up after getting into an"
print"escape pod.\n"
print"You‘re running down the central corridor to the Weapons Armory when"
print"a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
print"flowing around his hate filled body. He‘s blocking the door to the"
print"Armory and about to pull a weapon to blast you."
action=raw_input(‘‘‘\nI‘l give you some advice>>
\n shoot!\t dodge!\t tell a joke\t\n>>‘‘‘)
if action == "shoot!":
print "Quick on the draw you yank out your blaster and fire it at the Gothon."
print "His clown costume is flowing and moving around his body, which throws"
print "off your aim. Your laser hits his costume but misses him entirely. This"
print "completely ruins his brand new costume his mother bought him, which"
print "makes him fly into an insane rage and blast you repeatedly in the face until"
print "you are dead. Then he eats you."
return ‘death‘
elif action == "dodge!":
print "Like a world class boxer you dodge, weave, slip and slide right"
print "as the Gothon‘s blaster cranks a laser past your head."
print "In the middle of your artful dodge your foot slips and you"
print "bang your head on the metal wall and pass out."
print "You wake up shortly after only to die as the Gothon stomps on"
print "your head and eats you."
return ‘death‘
elif action == "tell a joke":
print "Lucky for you they made you learn Gothon insults in the academy."
print "You tell the one Gothon joke you know:"
print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
print "The Gothon stops, tries not to laugh, then busts out laughing and can‘t move."
print "While he‘s laughing you run up and shoot him square in the head"
print "putting him down, then jump through the Weapon Armory door."
return ‘laser_weapon_armory‘
else:
print "DOES NOT COMPUTE!"
return ‘central_corridor‘
def laser_weapon_armory(self):
print "You do a dive roll into the Weapon Armory, crouch and scan the room"
print "for more Gothons that might be hiding. It‘s dead quiet, too quiet."
print "You stand up and run to the far side of the room and find the"
print "neutron bomb in its container. There‘s a keypad lock on the box"
print "and you need the code to get the bomb out. If you get the code"
print "wrong 10 times then the lock closes forever and you can‘t"
print "get the bomb. The code is 3 digits."
code = "%d%d%d" %(randint(1,9),randint(1,9),randint(1,9))
print"Code is %s" % code
guess=raw_input("[keypad]> ")
guesses=0
while guess != code and guesses <10:
print "BZZZEDD!"
guesses +=1
guess =raw_input("[keypad]> ")
if guess == code:
print "The container clicks open and the seal breaks, letting gas out."
print "You grab the neutron bomb and run as fast as you can to the"
print "bridge where you must place it in the right spot."
return ‘the_bridge‘
else:
print "The lock buzzes one last time and then you hear a sickening"
print "melting sound as the mechanism is fused together."
print "You decide to sit there, and finally the Gothons blow up the"
print "ship from their ship and you die."
return ‘death‘
def the_bridge(self):
print "You burst onto the Bridge with the neutron destruct bomb"
print "under your arm and surprise 5 Gothons who are trying to"
print "take control of the ship. Each of them has an even uglier"
print "clown costume than the last. They haven‘t pulled their"
print "weapons out yet, as they see the active bomb under your"
print "arm and don‘t want to set it off."
action=raw_input(‘‘‘\nI‘l give you some advice>>
\n throw the bomb\n slowly place the bomb\t\n>>‘‘‘)
if action == "throw the bomb":
print "In a panic you throw the bomb at the group of Gothons"
print "and make a leap for the door. Right as you drop it a"
print "Gothon shoots you right in the back killing you."
print "As you die you see another Gothon frantically try to disarm"
print "the bomb. You die knowing they will probably blow up when"
print "it goes off."
return ‘death‘
elif action == "slowly place the bomb":
print "You point your blaster at the bomb under your arm"
print "and the Gothons put their hands up and start to sweat."
print "You inch backward to the door, open it, and then carefully"
print "place the bomb on the floor, pointing your blaster at it."
print "You then jump back through the door, punch the close button"
print "and blast the lock so the Gothons can‘t get out."
print "Now that the bomb is placed you run to the escape pod to"
print "get off this tin can."
return ‘escape_pod‘
else:
print "DOES NOT COMPUTE!"
return "the_bridge"
def escape_pod(self):
print "You rush through the ship desperately trying to make it to"
print "the escape pod before the whole ship explodes. It seems like"
print "hardly any Gothons are on the ship, so your run is clear of"
print "interference. You get to the chamber with the escape pods, and"
print "now need to pick one to take. Some of them could be damaged"
print "but you don‘t have time to look. There‘s 5 pods, which one"
print "do you take?"
good_pod = randint(1,5)
print "good_pod is %d" % good_pod
guess = raw_input("[pod #]> ")
if int(guess) !=good_pod:
print "You jump into pod %s and hit the eject button." % guess
print "The pod escapes out into the void of space, then"
print "implodes as the hull ruptures, crushing your body"
print "into jam jelly."
return ‘death‘
else:
print "You jump into pod %s and hit the eject button." % guess
print "The pod easily slides out into space heading to"
print "the planet below. As it flies to the planet, you look"
print "back and see your ship implode then explode like a"
print "bright star, taking out the Gothon ship at the same"
print "time. You won!"
exit(0)
a_game = Game("central_corridor")
a_game.play()
ec处理异常try & except
#coding=utf-8
def convert_number(s):
try:
return int(s)
except ValueError:
return None
s=raw_input("PLZ>>")
print(convert_number(s))
From实验楼
Pathbao.py
#coding=utf-8
import os.path
path=‘H:\python_program\shiyanlou\saile.txt‘
‘‘‘
print‘‘
print(os.path.basename(path))
print(os.path.dirname(path))
info = os.path.split(path)
print‘‘
path2=os.path.join(‘/‘,‘python_program‘,‘shiyanlou‘,‘saile.txt‘)
print path2
# 这里的斜杠注意下,win7里面是"\",而实验楼里面的是"/",这个影响大不大
‘‘‘
a=‘H:\python_program\shiyanlou\..‘
# print(os.path.normpath(a))
print"path is %r" % path
print(‘exit?‘,os.path.exists(path))
print(‘size?‘,os.path.getsize(path))
print(‘last read time?‘,os.path.getatime(path))
print(‘last edit time?‘,os.path.getmtime(path))
print(‘path to file?‘,os.path.isfile(path))
print(‘path to dir?‘,os.path.isdir(path))
sy1 glob
#coding=utf-8
import glob
print(glob.glob("H:\python_program\shiyanlou\*"))
#该命令找出文件夹下所有文件。
Sy2 os包
#coding=utf-8
import os
path=‘H:\python_program\shiyanlou\wc‘
#这里需要注意下,用mkdir创建文件目录时,最后一个不用\
# os.mkdir(path)#创建新目录
# os.rmdir(path)#删除空目录
# a=os.listdir(path)#返回目录中所有文件。相当于$ls命令,存起来
# print a
# path=‘H:\python_program\shiyanlou\wc\saile.txt‘
# os.remove(path)#删除 path指向的文件。path指向某个文件,注意文件名与\的作用。
# path1=‘H:\python_program\shiyanlou\wc2\saile.txt‘
# path2=‘H:\python_program\shiyanlou\wc2\what.txt‘
# os.rename(path1, path2)
#重命名文件,src和ds为两个路径,分别表示重命名之前和之后的路径。
#重命名后,path1消失了,path2产生了,就是重命名文件夹,试试重命名文件,文件也是可以的。
print(os.getcwd())#查询当前工作路径
shutil包
#coding=utf-8
import shutil
import os
print(os.getcwd())
shutil.copy(‘a.txt‘,‘b.txt‘)
# copy(src, dst) 复制文件,从src到dst。相当于$cp命令。
# move(src, dst) 移动文件,从src到dst。相当于$mv命令。
#运用此命令需要先确定文件的位置,一开始确定工作区也是可行的!
Pickle包
#coding=utf-8
import pickle
class Bird(object):
have_feather=True
way_of_reproduction = ‘egg‘
summer = Bird()
picklestring = pickle.dumps(summer)
print picklestring
#coding=utf-8
import pickle
class Bird(object):
have_feather = True
way_of_reproduction = ‘egg‘
summer = Bird()
fn = ‘a.pkl‘
with open(fn,‘w‘) as f:
picklestring = pickle.dump(summer, f)
print picklestring
#这个最后结果是none,不知哪里wrong
print summer
#是放在summer里面的。握草,那为什么picklestring 里面是none?
#coding=utf-8
import pickle
class Bird(object):
have_feather = True
way_of_reproduction = ‘egg‘
fn =‘a.pkl‘
with open(fn,‘r‘) as f:
summer = pickle.load(f)
print summer
subprocess包
import subprocess
child =subprocess.Popen(["ping","www.baidu.com"])
# child.wait()
print"parent process"
import subprocess
out=subprocess.call("ls -l",shell=True)
out=subprocess.call("cd ..",shell=True)
import subprocess
import os
child1 = subprocess.Popen(["print","abcd"], stdout=subprocess.PIPE)
child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE)
out = child2.communicate()
print(out)
thread包
#coding=utf-8
# A program to simulate selling tickets in multi-thread way
# Written by Vamei
import threading
import time
import os
# This function could be any function to do other chores.
def doChore():
time.sleep(0.2)
# Function for each thread
def booth(tid):
global i
global lock
while True:
lock.acquire() # Lock; or wait if other thread is holding the lock
if i != 0:
i = i - 1 # Sell tickets
print(tid,‘:now left:‘,i) # Tickets left
doChore() # Other critical operations
else:
print("Thread_id",tid," No more tickets")
os._exit(0) # Exit the whole process immediately
lock.release() # Unblock
doChore() # Non-critical operations
# Start of the main function
i = 100 # Available ticket number
lock = threading.Lock() # Lock (i.e., mutex)
# Start 10 threads
for k in range(10):
new_thread = threading.Thread(target=booth,args=(k,)) # Set up thread; target: the callable (function) to be run, args: the argument for the callable
new_thread.start() # run the thread
用类写的
import threading
import time
import os
# This function could be any function to do other chores.
def doChore():
time.sleep(0.5)
# Function for each thread
class BoothThread(threading.Thread):
def __init__(self, tid, monitor):
self.tid = tid
self.monitor = monitor
threading.Thread.__init__(self)
def run(self):
while True:
monitor[‘lock‘].acquire() # Lock; or wait if other thread is holding the lock
if monitor[‘tick‘] != 0:
monitor[‘tick‘] = monitor[‘tick‘] - 1 # Sell tickets
print(self.tid,‘:now left:‘,monitor[‘tick‘]) # Tickets left
doChore() # Other critical operations
else:
print("Thread_id",self.tid," No more tickets")
os._exit(0) # Exit the whole process immediately
monitor[‘lock‘].release() # Unblock
doChore() # Non-critical operations
# Start of the main function
monitor = {‘tick‘:100, ‘lock‘:threading.Lock()}
# Start 10 threads
for k in range(10):
new_thread = BoothThread(k, monitor)
new_thread.start()
multiprocessing包
import multiprocessing as mul
def proc1(pipe):
pipe.send(‘hello‘)
print(‘proc1 rec:‘,pipe.recv())
def proc2(pipe):
print(‘proc2 rec:‘,pipe.recv())
pipe.send(‘hello, too‘)
# Build a pipe
pipe = mul.Pipe()
# Pass an end of the pipe to process 1
p1 = mul.Process(target=proc1, args=(pipe[0],))
# Pass the other end of the pipe to process 2
p2 = mul.Process(target=proc2, args=(pipe[1],))
p1.start()
p2.start()
p1.join()
p2.join()
读取中文
#coding=gbk
‘‘‘
s = "中文"
s1 = u"中文"
s2 = unicode(s, "gbk") #省略参数将用python默认的ASCII来解码
s3 = s.decode("gbk") #把str转换成unicode是decode,unicode函数作用与之相同
print len(s)
print len(s1)
print len(s2)
print len(s3)
‘‘‘
import codecs
# print open("file.txt").read().decode("utf-8")
print open("file.txt").read()
#文本类型的文件读取,在utf-8和ANSI编码之间的切换。
Sy6.py线程实验售票系统
#coding=utf-8
# A program to simulate selling tickets in multi-thread way
# Written by Vamei
import threading
import time
import os
# This function could be any function to do other chores.
def doChore():
time.sleep(0.01)#这边可以用来调节时间,快慢
# Function for each thread
def booth(tid):
global i
global lock
while True:
lock.acquire() # Lock; or wait if other thread is holding the lock
if i != 0:
i = i - 1 # Sell tickets
print(tid,‘:now left:‘,i) # Tickets left
doChore() # Other critical operations
else:
print("Thread_id",tid," No more tickets")
os._exit(0) # Exit the whole process immediately
lock.release() # Unblock
doChore() # Non-critical operations
# Start of the main function
i = 100 # Available ticket number
lock = threading.Lock() # Lock (i.e., mutex)
# Start 10 threads
for k in range(10):
new_thread = threading.Thread(target=booth,args=(k,)) # Set up thread; target: the callable (function) to be run, args: the argument for the callable
new_thread.start() # run the thread
sy6.py用类实现
import threading
import time
import os
# This function could be any function to do other chores.
def doChore():
time.sleep(0.5)
# Function for each thread
class BoothThread(threading.Thread):
def __init__(self, tid, monitor):
self.tid = tid
self.monitor = monitor
threading.Thread.__init__(self)
def run(self):
while True:
monitor[‘lock‘].acquire() # Lock; or wait if other thread is holding the lock
if monitor[‘tick‘] != 0:
monitor[‘tick‘] = monitor[‘tick‘] - 1 # Sell tickets
print(self.tid,‘:now left:‘,monitor[‘tick‘]) # Tickets left
doChore() # Other critical operations
else:
print("Thread_id",self.tid," No more tickets")
os._exit(0) # Exit the whole process immediately
monitor[‘lock‘].release() # Unblock
doChore() # Non-critical operations
# Start of the main function
monitor = {‘tick‘:100, ‘lock‘:threading.Lock()}
# Start 10 threads
for k in range(10):
new_thread = BoothThread(k, monitor)
new_thread.start()
ascii.py argparse操作分解
#coding=utf-8
from PIL import Image
import argparse
ascii_char = list("[email protected]%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`‘. ")#字符全放在表里面,注意他们的使用方式
# print ascii_char
# print len(ascii_char)
# a=list("[email protected]#$%")#fk,居然直接连起来就OK
# print a
def get_char(r,g,b,alpha = 256):#RGB值输进去,能转换成对应的字符编码
if alpha == 0:
return ‘ ‘
length = len(ascii_char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unit = (256.0 + 1)/length
return ascii_char[int(gray/unit)]
a=get_char(32,32,32,256)
# print a
#~~~~~argparse部分学习
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print args.echo
#~~~~~~~~~~~
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
print "verbosity turned on"
#~~~~~~~
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
action="store_true")
args = parser.parse_args()
if args.verbose:
print "verbosity turned on"
#~~~~~~~
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity",
action="store_true")
args = parser.parse_args()
if args.verbose:
print "verbosity turned on"
#~~~~~~~~~~~~~
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbose:
print "the square of {} equals {}".format(args.square, answer)
else:
print answer
‘‘‘Run
这个例子有点大彻大悟的感觉啊,可以不停的加简写,多个参数就都输入,再试试别的,很好!
$ python prog.py
usage: prog.py [-h] [-v] square
prog.py: error: the following arguments are required: square
$ python prog.py 4
16
$ python prog.py 4 --verbose
the square of 4 equals 16
$ python prog.py --verbose 4
the square of 4 equals 16‘‘‘
#~~~~~~~~~~~~~
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int,
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer
‘‘‘运行:
$ python prog.py 4
16
$ python prog.py 4 -v
usage: prog.py [-h] [-v VERBOSITY] square
prog.py: error: argument -v/--verbosity: expected one argument
$ python prog.py 4 -v 1
4^2 == 16 握草,这是给cerbosity赋值来操作啊,我就想到VBA里面各种参数的东西
$ python prog.py 4 -v 2
the square of 4 equals 16
$ python prog.py 4 -v 3
16‘‘‘
#~~~~~~~~~~~~~
# 除了最后一个暴露了一个bug,其他的看起都来运行良好。让我们通过限制--verbosity后面跟的值来修正:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer
‘‘‘
运行:
$ python prog.py 4 -v 3
usage: prog.py [-h] [-v {0,1,2}] square
prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
$ python prog.py 4 -h
usage: prog.py [-h] [-v {0,1,2}] square
positional arguments:
square display a square of a given number
optional arguments:
-h, --help show this help message and exit
-v {0,1,2}, --verbosity {0,1,2}
increase output verbosity‘‘‘
#~~~~~~~~~~~~
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display the square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer
‘‘‘我们引入了另一个关键词count来统计可选参数出现的次数:
$ python prog.py 4
16
$ python prog.py 4 -v
4^2 == 16
$ python prog.py 4 -vv
the square of 4 equals 16
$ python prog.py 4 --verbosity --verbosity
the square of 4 equals 16
$ python prog.py 4 -v 1
usage: prog.py [-h] [-v] square
prog.py: error: unrecognized arguments: 1
$ python prog.py 4 -h
usage: prog.py [-h] [-v] square
positional arguments:
square display a square of a given number
optional arguments:
-h, --help show this help message and exit
-v, --verbosity increase output verbosity
$ python prog.py 4 -vvv
16 ‘‘‘
#~~~~~~~~
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
# bugfix: replace == with >=
if args.verbosity >= 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity >= 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer
# 运行如下:
# $ python prog.py 4 -vvv
# the square of 4 equals 16
# $ python prog.py 4 -vvvv
# the square of 4 equals 16
# $ python prog.py 4
# Traceback (most recent call last):
# File "prog.py", line 11, in <module>
# if args.verbosity >= 2:
# TypeError: unorderable types: NoneType() >= int()
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count", default=0,
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity >= 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity >= 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer
#~~~~~~~~~
# 如果我们想扩展程序的功能,而不仅仅是求平方:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbosity >= 2:
print "{} to the power {} equals {}".format(args.x, args.y, answer)
elif args.verbosity >= 1:
print "{}^{} == {}".format(args.x, args.y, answer)
else:
print answer
# 输出:
# $ python prog.py
# usage: prog.py [-h] [-v] x y
# prog.py: error: the following arguments are required: x, y
# $ python prog.py -h
# usage: prog.py [-h] [-v] x y
# positional arguments:
# x the base
# y the exponent
# optional arguments:
# -h, --help show this help message and exit
# -v, --verbosity
# $ python prog.py 4 2 -v
# 4^2 == 16
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbosity >= 2:
print "Running ‘{}‘".format(__file__)
if args.verbosity >= 1:
print "{}^{} ==".format(args.x, args.y),
print answer
# 输出:
# $ python prog.py 4 2
# 16
# $ python prog.py 4 2 -v
# 4^2 == 16
# $ python prog.py 4 2 -vv
# Running ‘prog.py‘
# 4^2 == 16
#命名的时候不要乱写
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y
if args.quiet:
print answer
elif args.verbose:
print "{} to the power {} equals {}".format(args.x, args.y, answer)
else:
print "{}^{} == {}".format(args.x, args.y, answer)
sy8.py argparse 操作最终
import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y
if args.quiet:
print answer
elif args.verbose:
print "{} to the power {} equals {}".format(args.x, args.y, answer)
else:
print "{}^{} == {}".format(args.x, args.y, answer)
pic_change_str.py 实验楼图片转字符画课程
#coding=utf-8
from PIL import Image
import argparse
#命令行输入参数处理
parser = argparse.ArgumentParser()
parser.add_argument(‘file‘) #输入文件
parser.add_argument(‘-o‘, ‘--output‘) #输出文件
parser.add_argument(‘-w‘,‘--width‘, type = int, default = 80) #输出字符画宽
parser.add_argument(‘-he‘,‘--height‘, type = int, default = 80) #输出字符画高
#获取参数ascii_dora.png
args = parser.parse_args()
IMG = args.file
WIDTH = args.width
HEIGHT = args.height
OUTPUT = args.output
ascii_char = list("[email protected]%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`‘. ")
# 将256灰度映射到70个字符上
def get_char(r,g,b,alpha = 256):
if alpha == 0:
return ‘ ‘
length = len(ascii_char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unit = (256.0 + 1)/length
return ascii_char[int(gray/unit)]
if __name__ == ‘__main__‘:
im = Image.open(IMG)
im = im.resize((WIDTH,HEIGHT), Image.NEAREST)
txt = ""
for i in range(HEIGHT):
for j in range(WIDTH):
txt += get_char(*im.getpixel((j,i))) #获取相应的像素
txt += ‘\n‘
print txt
#字符画输出到文件
if OUTPUT:#如果加了output的选项,其实就相当于你定义一个输出的名字和类型
with open(OUTPUT,‘a+‘) as f:#打开只写文件,这边也可以考虑用‘a+‘的形式,我觉得就像是日志一样(log),所有的操作都附着在最后,做个记录,我试试,果然是OK的。
f.write(txt)
else:
with open("output.txt",‘a+‘) as f:#你这边不定义-o的话,就会输出output.txt
f.write(txt)
2048系列代码
主程序代码
#-*- coding:utf-8 -*-
import curses
from random import randrange, choice # generate and place new tile
from collections import defaultdict
letter_codes = [ord(ch) for ch in ‘WASDRQwasdrq‘]#chr和ord互为相反操作,别的进制有特殊的格式
letter_codes =letter_codes+[259,260,258,261,114,113]
actions = [‘Up‘, ‘Left‘, ‘Down‘, ‘Right‘, ‘Restart‘, ‘Exit‘]
actions_dict = dict(zip(letter_codes, actions * 3))#将输入与行为进行关联:
#游戏经过改装,加了方向键,nice!↑←↓→
def get_user_action(keyboard):
‘‘‘用户输入处理,阻塞+循环,直到获得用户有效输入才返回对应行为:‘‘‘
char = "N"
while char not in actions_dict:
char = keyboard.getch()#获取输入一遍使用getch()方法,这个方法暂停等待用户输入,getch()返回一个整数 ,在0到255之间,表示输入字符的ASCII值
#也就是说getch()得到的数字和ord的数字格式一致
return actions_dict[char]
def transpose(field):
‘‘‘矩阵转置‘‘‘
return [list(row) for row in zip(*field)]
def invert(field):
‘‘‘矩阵逆转,不是逆矩阵‘‘‘
return [row[::-1] for row in field]
class GameField(object):
‘‘‘创建棋盘,初始化棋盘的参数,可以指定棋盘的高和宽以及游戏胜利条件,默认是最经典的 4x4~2048。‘‘‘
def __init__(self, height=4, width=4, win=2048):
self.height = height
self.width = width
self.win_value = 2048
self.score = 0
self.highscore = 0
self.reset()
def reset(self):
‘‘‘重置棋盘‘‘‘
if self.score > self.highscore:
self.highscore = self.score
self.score = 0
self.field = [[0 for i in range(self.width)] for j in range(self.height)]#创建4*4的棋盘
self.spawn()
self.spawn()#初始化的过程,刚开始生成两个随机数
def move(self, direction):
‘‘‘棋盘走一步,通过对矩阵进行转置与逆转,可以直接从左移得到其余三个方向的移动操作‘‘‘
def move_row_left(row):
‘‘‘棋盘一行向左合并‘‘‘
def tighten(row): # squeese non-zero elements together,变紧
new_row = [i for i in row if i != 0] # 快速循环,并排除某一项,循环对象是i
new_row += [0 for i in range(len(row) - len(new_row))] #循环对象是0
return new_row
def merge(row): # 合并
pair = False
new_row = []
for i in range(len(row)):
if pair:
new_row.append(2 * row[i])
self.score += 2 * row[i]
pair = False
else:
if i + 1 < len(row) and row[i] == row[i + 1]:
pair = True
new_row.append(0)
else:
new_row.append(row[i])
assert len(new_row) == len(row)
return new_row
return tighten(merge(tighten(row)))
moves = {}
moves[‘Left‘] = lambda field: \
[move_row_left(row) for row in field]
moves[‘Right‘] = lambda field: \
invert(moves[‘Left‘](invert(field)))
moves[‘Up‘] = lambda field: \
transpose(moves[‘Left‘](transpose(field)))
moves[‘Down‘] = lambda field: \
transpose(moves[‘Right‘](transpose(field)))
if direction in moves:
if self.move_is_possible(direction):
self.field = moves[direction](self.field)
self.spawn()
return True
else:
return False
def is_win(self):
‘‘‘判断输赢‘‘‘
return any(any(i >= self.win_value for i in row) for row in self.field)#any的用法,只要有一个true就是true
def is_gameover(self):
return not any(self.move_is_possible(move) for move in actions)
def draw(self, screen):
‘‘‘绘制游戏界面‘‘‘
help_string1 = ‘(W)Up (S)Down (A)Left (D)Right‘
help_string2 = ‘ (R)Restart (Q)Exit‘
gameover_string = ‘ GAME OVER‘
win_string = ‘ YOU WIN!‘
def cast(string):#换行显示对应字符
screen.addstr(string + ‘\n‘)
def draw_hor_separator():#画分隔符
line = ‘+‘ + (‘+------‘ * self.width + ‘+‘)[1:]
separator = defaultdict(lambda: line)#separator就是字典,line就为默认值
if not hasattr(draw_hor_separator, "counter"):#如果没有这个属性或方法
draw_hor_separator.counter = 0
cast(separator[draw_hor_separator.counter])
draw_hor_separator.counter += 1 #分隔符计数
def draw_row(row):
cast(‘‘.join(‘|{: ^5} ‘.format(num) if num > 0 else ‘| ‘ for num in row) + ‘|‘)#主要网格的绘制,数组里面要是有东西,就显示出来,没有就空着,用空字符隔开
#重点掌握了{}.format的用法
screen.clear()
cast(‘SCORE: ‘ + str(self.score))
if 0 != self.highscore:
cast(‘HGHSCORE: ‘ + str(self.highscore))
for row in self.field:
draw_hor_separator()
draw_row(row)
draw_hor_separator()
if self.is_win():
cast(win_string)
else:
if self.is_gameover():
cast(gameover_string)
else:
cast(help_string1)
cast(help_string2)
def spawn(self):
‘‘‘棋盘操作,随机生成1个2或4‘‘‘
new_element = 4 if randrange(100) > 89 else 2
(i,j) = choice([(i,j) for i in range(self.width) for j in range(self.height) if self.field[i][j] == 0])
self.field[i][j] = new_element
def move_is_possible(self, direction):
‘‘‘判断能否移动‘‘‘
def row_is_left_movable(row):
def change(i): # true if there‘ll be change in i-th tile
if row[i] == 0 and row[i + 1] != 0: # Move
return True
if row[i] != 0 and row[i + 1] == row[i]: # Merge
return True
return False
return any(change(i) for i in range(len(row) - 1))
check = {}
check[‘Left‘] = lambda field: \
any(row_is_left_movable(row) for row in field)
check[‘Right‘] = lambda field: \
check[‘Left‘](invert(field))
check[‘Up‘] = lambda field: \
check[‘Left‘](transpose(field))
check[‘Down‘] = lambda field: \
check[‘Right‘](transpose(field))
if direction in check:
return check[direction](self.field)
else:
return False
def main(stdscr):
def init():
#重置游戏棋盘
game_field.reset()
return ‘Game‘
def not_game(state):
#画出 GameOver 或者 Win 的界面
game_field.draw(stdscr)
#读取用户输入得到action,判断是重启游戏还是结束游戏
action = get_user_action(stdscr)
responses = defaultdict(lambda: state) #默认是当前状态,没有行为就会一直在当前界面循环
responses[‘Restart‘], responses[‘Exit‘] = ‘Init‘, ‘Exit‘ #对应不同的行为转换到不同的状态
return responses[action]
def game():
#画出当前棋盘状态
game_field.draw(stdscr)
#读取用户输入得到action
action = get_user_action(stdscr)
if action == ‘Restart‘:
return ‘Init‘
if action == ‘Exit‘:
return ‘Exit‘
if game_field.move(action): # move successful
if game_field.is_win():
return ‘Win‘
if game_field.is_gameover():
return ‘Gameover‘
return ‘Game‘
state_actions = {
‘Init‘: init,
‘Win‘: lambda: not_game(‘Win‘),
‘Gameover‘: lambda: not_game(‘Gameover‘),
‘Game‘: game
}
curses.use_default_colors()
game_field = GameField(win=32)
state = ‘Init‘
#状态机开始循环
while state != ‘Exit‘:
state = state_actions[state]()
curses.wrapper(main)
2048cp zip/for的用法
# coding=utf-8
import curses
# from random import randrange, choice
# from collections import defaultdict
ta = [1,2,3,4,5,6]
tb = [9,8,7]
tx = ta+tb
print "tx is \n",tx
xx=ta*2 #数组扩展
print xx
tc = [‘a‘,‘b‘,‘c‘]
bb=zip(ta,tc)
print bb
aa=dict(zip(ta,tc * 2)) #实验可知,tc这边重复了,就用*2来表示。zip表示交叉对应
print aa
actions = [‘Up‘, ‘Left‘, ‘Down‘, ‘Right‘, ‘Restart‘, ‘Exit‘]
letter_codes = [ord(ch) for ch in ‘WASDRQwasdrq‘] #返回字母对应的数字
x=5
for i in range(5):
x +=10
print x
ne = any(i <= -1 for i in range(5) )
# ne.append(5)
print "ne is ",ne
print letter_codes
letter_codes =letter_codes+[259,260,258,261,114,113]
print "code is \n",letter_codes
actions_dict = dict(zip(letter_codes, actions * 3))
print actions_dict
2048cp1 curse的颜色设置。。
#-*- coding: UTF-8 -*-
import curses
stdscr = curses.initscr() #初始化
def display_info(str, x, y, colorpair=4):
‘‘‘‘‘使用指定的colorpair显示文字‘‘‘
global stdscr
stdscr.addstr(y, x,str, curses.color_pair(colorpair))
stdscr.refresh()
def get_ch_and_continue():
‘‘‘‘‘演示press any key to continue‘‘‘
global stdscr
#设置nodelay,为0时会变成阻塞式等待
stdscr.nodelay(0)
#输入一个字符
ch=stdscr.getch()
#重置nodelay,使得控制台可以以非阻塞的方式接受控制台输入,超时1秒
stdscr.nodelay(1)
return True
def set_win():
‘‘‘‘‘控制台设置‘‘‘
global stdscr
#使用颜色首先需要调用这个方法
curses.start_color()
#文字和背景色设置,设置了两个color pair,分别为1和2
curses.init_pair(3, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_CYAN, curses.COLOR_WHITE)
#关闭屏幕回显
curses.noecho()
#输入时不需要回车确认
curses.cbreak()
#设置nodelay,使得控制台可以以非阻塞的方式接受控制台输入,超时1秒
stdscr.nodelay(1)
def unset_win():
‘‘‘控制台重置‘‘‘
global stdstr
#恢复控制台默认设置(若不恢复,会导致即使程序结束退出了,控制台仍然是没有回显的)
curses.nocbreak()#关闭字符终端功能(只有回车时才发生终端)
stdscr.keypad(0)
curses.echo()#打开输入回显功能
curses.endwin()#结束窗口,恢复默认设置
if __name__==‘__main__‘:
try:
set_win()
display_info(‘Hola, curses!‘,10,20,5)#第一个参数是y,第二个是x
display_info(‘Press any key to continue...‘,0,10,3)
get_ch_and_continue()
except Exception,e:
raise e
finally:
unset_win()
2048cp2研究curses的一些用法,很奇怪,还不精
#-*- coding: UTF-8 -*-
import curses
stdscr = curses.initscr() #初始化
begin_x = 20; begin_y = 27
height = 15; width = 40
win = curses.newwin(height, width, begin_y, begin_x)
pad = curses.newpad(100, 100)
# These loops fill the pad with letters; this is
# explained in the next section
for y in range(0, 10):
for x in range(0, 10):
try:
pad.addch(y,x, ord(‘a‘) + (x*x+y*y) % 26)
except curses.error:
pass
# Displays a section of the pad in the middle of the screen
pad.refresh(0,0, 5,5, 20,75)#refreshe重绘窗口
#研究curses的一些用法
2048cp3#边框的画法,控制数组大小和里面值是否出现
#-*- coding:utf-8 -*-
import curses
from random import randrange, choice # generate and place new tile
from collections import defaultdict
letter_codes = [ord(ch) for ch in ‘WASDRQwasdrq‘]
actions = [‘Up‘, ‘Left‘, ‘Down‘, ‘Right‘, ‘Restart‘, ‘Exit‘]
actions_dict = dict(zip(letter_codes, actions * 2))
def transpose(field):
‘‘‘矩阵转置‘‘‘
return [list(row) for row in zip(*field)]
a = [[i**3 for i in range(4)] for j in range(4)] #这边是控制数组大小的
print "a is \n",a,‘type is‘,type(a)
a.clear()
print "a is \n",a,‘type is‘,type(a)
def draw_row(row):
b=‘‘.join(‘|{: ^5} ‘.format(num) if num >= 0 else ‘| ‘ for num in row) + ‘|‘
print b #这边是控制里面的数字出不出现的
def draw_row1(row):
b=‘‘.join(‘|{: ^5} ‘.format(num) if num > 1 else ‘| ‘ for num in row)
print b
for row in a:
# draw_row(row)
draw_row1(row)
x=‘‘.join(‘|{: ^5} ‘.format(num) if num >= 0 else ‘| ‘ for num in [1,2,3,4])
print "\n",x
line = ‘+‘ + (‘+------‘ * 4 + ‘+‘)[1:]
print "line is \n",line
lin = (‘+------‘ * 4 + ‘+‘)
print "lineing is \n",lin
#矩阵转换的一些用法
2048cp4学习defaultdict的用法
# coding=utf-8
import curses
from random import randrange, choice
# from collections import defaultdict
# 学习defaultdict的用法
#-------一开始,字典里是空的就会报错
# counts = dict()
# counts[‘puppy‘] += 1
‘‘‘
#-------试试if条件判断
strings = (‘puppy‘, ‘kitten‘, ‘puppy‘, ‘puppy‘,
‘weasel‘, ‘puppy‘, ‘kitten‘, ‘puppy‘)
counts = {}
for kw in strings:
if kw not in counts:#一开始字典counts里是空的,所以第一个字符出现的时候肯定是没有的,那统计数量就会出错,这里进行if判断就OK了。
counts[kw] = 1
print ‘not in ‘,counts
else:
counts[kw] += 1
print counts
‘‘‘
"""
#--------使用dict.setdefault()方法设置默认值
strings = (‘puppy‘, ‘kitten‘, ‘puppy‘, ‘puppy‘,
‘weasel‘, ‘puppy‘, ‘kitten‘, ‘puppy‘)
counts = {}
# dict.setdefault()方法接收两个参数,第一个参数是健的名称,第二个参数是默认值。假如字典中不存在给定的键,则返回参数中提供的默认值;反之,则返回字典中保存的值。
for kw in strings:
counts.setdefault(kw, 0)
counts[kw] += 1
print counts
"""
‘‘‘
#--------上述方法更简洁一点
strings = (‘puppy‘, ‘kitten‘, ‘puppy‘, ‘puppy‘,
‘weasel‘, ‘puppy‘, ‘kitten‘, ‘puppy‘)
counts = {}
for kw in strings:
counts[kw] = counts.setdefault(kw, 0) + 1
print counts
‘‘‘
"""
#---------使用collections.defaultdict类
from collections import defaultdict
dd = defaultdict(list)
print dd
dd[‘foo‘]
print dd
dd[‘bar‘].append(‘quux‘)
print dd
"""
‘‘‘
#---------
from collections import defaultdict
dd = defaultdict(list)
print(‘something‘ in dd)
# dd.pop(‘something‘)
dd.get(‘something‘)
print dd[‘something‘]
print dd
‘‘‘
"""
#---------使用zero后不用初始化
from collections import defaultdict
def zero():
return 0
dd = defaultdict(zero)
# print dd
print dd[‘foo‘]
print dd
"""
#---------
from collections import defaultdict
strings = (‘puppy‘, ‘kitten‘, ‘puppy‘, ‘puppy‘,
‘weasel‘, ‘puppy‘, ‘kitten‘, ‘puppy‘)
counts = defaultdict(lambda: 10) # 使用lambda来定义简单的函数,设定默认值
for s in strings:
counts[s] += 1
print counts
line = ‘+‘ + (‘+------‘ * 4 + ‘+‘)[1:]
print "line is \n",line
lin = (‘+------‘ * 4 + ‘+‘)
print "lineing is \n",lin
#---------
# from collections import defaultdict
# print defaultdict.__missing__.__doc__
2048read_input.py
#-*- coding:utf-8 -*-
import curses
from random import randrange, choice # generate and place new tile
from collections import defaultdict
letter_codes = [ord(ch) for ch in ‘WASDRQwasdrq‘]
actions = [‘Up‘, ‘Left‘, ‘Down‘, ‘Right‘, ‘Restart‘, ‘Exit‘]#(259,260,258,261,114,113)
actions_dict = dict(zip(letter_codes, actions * 2))
def get_user_action(keyboard):
‘‘‘用户输入处理,阻塞+循环,直到获得用户有效输入才返回对应行为:‘‘‘
char = "N"
while char not in actions_dict:
char = keyboard.getch()
print char
return actions_dict[char]
def main(stdscr):
a=get_user_action(stdscr)
curses.wrapper(main)
2048hasatta的用法
#coding = utf-8
#coding=gbk
class test():
name="xiaohua"
def run(self):
return "HelloWord"
t=test()
print t.name
print t.run()
# Python的hasattr() getattr() setattr() 函数使用方法详解
print(hasattr(t, "name"))
print(hasattr(t, "run"))
‘‘‘
#------
>>> class test():
2 ... name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> getattr(t, "name") #获取name属性,存在就打印出来。
8 ‘xiaohua‘
9 >>> getattr(t, "run") #获取run方法,存在就打印出方法的内存地址。
10 <bound method test.run of <__main__.test instance at 0x0269C878>>
11 >>> getattr(t, "run")() #获取run方法,后面加括号可以将这个方法运行。
12 ‘HelloWord‘
13 >>> getattr(t, "age") #获取一个不存在的属性。
14 Traceback (most recent call last):
15 File "<stdin>", line 1, in <module>
16 AttributeError: test instance has no attribute ‘age‘
17 >>> getattr(t, "age","18") #若属性不存在,返回一个默认值。
18 ‘18‘
19 >>>
‘‘‘
"""
#------------
setattr(object, name, values)
给对象的属性赋值,若属性不存在,先创建再赋值。
复制代码
1 >>> class test():
2 ... name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> hasattr(t, "age") #判断属性是否存在
8 False
9 >>> setattr(t, "age", "18") #为属相赋值,并没有返回值
10 >>> hasattr(t, "age") #属性存在了
11 True
12 >>>
"""
‘‘‘
#------------
综合运用
一种综合的用法是:判断一个对象的属性是否存在,若不存在就添加该属性。
复制代码
1 >>> class test():
2 ... name="xiaohua"
3 ... def run(self):
4 ... return "HelloWord"
5 ...
6 >>> t=test()
7 >>> getattr(t, "age") #age属性不存在
8 Traceback (most recent call last):
9 File "<stdin>", line 1, in <module>
10 AttributeError: test instance has no attribute ‘age‘
11 >>> getattr(t, "age", setattr(t, "age", "18")) #age属性不存在时,设置该属性
12 ‘18‘
13 >>> getattr(t, "age") #可检测设置成功
14 ‘18‘
15 >>>
‘‘‘
2048format的用法
#coding=utf-8
# 通过位置
# In [1]: ‘{0},{1}‘.format(‘kzc‘,18)
# Out[1]: ‘kzc,18‘
# In [2]: ‘{},{}‘.format(‘kzc‘,18)
# Out[2]: ‘kzc,18‘
# In [3]: ‘{1},{0},{1}‘.format(‘kzc‘,18)
# Out[3]: ‘18,kzc,18‘
a=‘{0},{1}‘.format(‘kzc‘,18)
print a
a=‘{},{}‘.format(‘kzc‘,18)
print a
a=‘{1},{0},{1}‘.format(‘kzc‘,18)
print a
# 通过关键字参数
# In [5]: ‘{name},{age}‘.format(age=18,name=‘kzc‘)
# Out[5]: ‘kzc,18‘
a=‘{name},{age}‘.format(age=18,name=‘kzc‘)
print a
# 通过对象属性
class Person:
def __init__(self,name,age):
self.name,self.age = name,age
def __str__(self):
return ‘This guy is {self.name},is {self.age} old‘.format(self=self)
a=str(Person(‘kzc‘,18))
print "\na is>>>",a
#通过下标
# In [7]: p=[‘kzc‘,18]
# In [8]: ‘{0[0]},{0[1]}‘.format(p)
# Out[8]: ‘kzc,18‘
p=[‘kzc‘,18]
q=[‘kzc‘,183]
b=‘{0[0]},{0[1]}‘.format(q)
print "\nb is>>>",b
# 填充与对齐
# 填充常跟对齐一起使用
# ^、<、>分别是居中、左对齐、右对齐,后面带宽度
# :号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
# 比如
# In [15]: ‘{:>8}‘.format(‘189‘)
# Out[15]: ‘ 189‘
# In [16]: ‘{:0>8}‘.format(‘189‘)
# Out[16]: ‘00000189‘
# In [17]: ‘{:a>8}‘.format(‘189‘)
# Out[17]: ‘aaaaa189‘
a=‘{:>8}‘.format(‘189‘)
print "\na is>>>",a
a=‘{:0>8}‘.format(‘189‘)
print "\na is>>>",a
a=‘{: >8}‘.format(‘189‘)
print "\na is>>>",a
# 精度与类型f
# 精度常跟类型f一起使用
# In [44]: ‘{:.2f}‘.format(321.33345)
# Out[44]: ‘321.33‘
a=‘{:.2f}‘.format(321.33345)
print "\na is>>>",a
# 用,号还能用来做金额的千位分隔符。
# In [47]: ‘{:,}‘.format(1234567890)
# Out[47]: ‘1,234,567,890‘
a=‘{:,}‘.format(1234567890)
print "\na is>>>",a
2048clear
#coding=utf-8
# for i in xrange(500):
# print #这个方法有点二
import sys
import os
os.system(‘cls‘)
#这才是对的
Jianming
Cat
#coding=utf-8
import sys
def readfile(filename):
‘‘‘Print a file to the standard output.‘‘‘
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line, # notice comma
f.close()
# Script starts from here
if len(sys.argv) < 2:
print ‘No action specified.‘
sys.exit()
if sys.argv[1].startswith(‘--‘):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == ‘version‘:
print ‘Version 1.2‘
elif option == ‘help‘:
print ‘‘‘\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help‘‘‘
else:
print ‘Unknown option.‘
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename) #读取文件内容
class_inherit
#coding=utf-8
class woman():
def __init__(self,a,b):
self.name=a
self.age=b*2
print self.name,self.age
class man():
def __init__(self,a,b):
self.name=a
self.age=b
print self.name,self.age
class boy(woman,man):
def sayhi():
print "wtf?"
#可以继承多个类,但是两者相冲突的话,选择放在前面的执行
xiaoming=boy(‘xm‘,13)
class_init
#coding=utf-8
class Person:
def __init__(self,name):
self.name= name
def sayHi(self):
print "Hello,my name is",self.name
p=Person("swaroop")
p.sayHi()
finally
#coding=utf-8
#coding=gbk
import time
import sys
try:
f=file(‘poem.txt‘)
while True:
line =f.readline()
if len(line)==0:
break
for i in range(len(line)):
if line[i]==‘ ‘:
time.sleep(0.1)
sys.stdout.write(line[i]) #如何让一行显示?
time.sleep(0.05)
#这个想办法如何做成一个模拟打字显示的样子?
#----print和sys.stdout.write的区别!!后者可以无缝接着输出! nice
finally:
f.close()
print ‘Closed the file.‘
gui
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import Tkinter
top = Tkinter.Tk()
# 进入消息循环
top.mainloop()
gui2
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from Tkinter import * # 导入 Tkinter 库
root = Tk() # 创建窗口对象的背景色
# 创建两个列表
li = [‘C‘,‘python‘,‘php‘,‘html‘,‘SQL‘,‘java‘]
movie = [‘CSS‘,‘jQuery‘,‘Bootstrap‘]
listb = Listbox(root) # 创建两个列表组件
listb2 = Listbox(root)
for item in li: # 第一个小部件插入数据
listb.insert(1,item)
for item in movie: # 第二个小部件插入数据
listb2.insert(0,item)
listb.pack() # 将小部件放置到主窗口中
listb2.pack()
root.mainloop() # 进入消息循环
inherit
#coding=utf-8
class SchoolMember:
‘‘‘Represents any school member.‘‘‘
def __init__(self, name, age):
self.name = name
self.age = age
print ‘(Initialized SchoolMember: %s)‘ % self.name
def tell(self):
‘‘‘Tell my details.‘‘‘
print ‘Name:"%s" Age:"%s"‘ % (self.name, self.age),
class Teacher(SchoolMember):
‘‘‘Represents a teacher.‘‘‘
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print ‘(Initialized Teacher: %s)‘ % self.name
def tell(self):
SchoolMember.tell(self)
print ‘Salary: "%d"‘ % self.salary
class Student(SchoolMember):
‘‘‘Represents a student.‘‘‘
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print ‘(Initialized Student: %s)‘ % self.name
def tell(self):
SchoolMember.tell(self)
print ‘Marks: "%d"‘ % self.marks
t = Teacher(‘Mrs. Shrividya‘, 40, 30000)
s = Student(‘Swaroop‘, 22, 75)
print ""# prints a blank line
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students
#调用子类方法时,现在子类中进行调用,如果子类没有,然后再在父类中调用
Lambda
#coding=utf-8
def make_repeater(n):
return lambda s:s*n#lambda语句用来创建函数对象,返回表达式的值
twice = make_repeater(2)
print twice(‘word‘)
print twice(5)
list_comprehension
#coding=utf-8
listone=[2,3,4]
listtwo=[2*i for i in listone if i >2]
print listtwo
method
#coding=utf-8
class Person:
def sayHi(self):
print "Hello,wtf?"
p=Person()
p.sayHi()
my_module
#coding=utf-8
def sayhi():
print "Hi, this is my module speaking!"
version = ‘0.1‘
my_module1
# import my_module
# my_module.sayhi()
# print ‘version‘,my_module.version
from my_module import *
sayhi()
print ‘version‘,version
#这边注意,import的*用法,前面需要加对应库,有* 的则不需要
Pickling
#coding=utf-8
import cPickle as p
#import pickle as p
shoplistfile = ‘shoplist.data‘
# the name of the file where we will store the object
shoplist = [‘apple‘, ‘mango‘, ‘carrot‘]
# Write to the file
f = file(shoplistfile, ‘w‘)
p.dump(shoplist, f) # dump the object to a file储存
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)#读取
print storedlist
powersum
#coding=utf-8
def powersum(power,*args):
total=0
for i in args:
total +=pow(i,power)
return total
print(powersum(2,3,4))
print(powersum(2,10,10,10))
print_one_line
#coding=utf-8
import sys
print"I",
print"love",
print‘you!‘
sys.stdout.write("I")
sys.stdout.write("love")
sys.stdout.write(‘you!‘)
threading
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
import time
exitFlag = 0
class myThread (threading.Thread): #继承父类threading.Thread
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self): #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
print "Starting " + self.name
print_time(self.name, self.counter, 5)
print "Exiting " + self.name
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
thread.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 开启线程
thread1.start()
thread2.start()
print "Exiting Main Thread"
threading2
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# 获得锁,成功获得锁定后返回True
# 可选的timeout参数不填时将一直阻塞直到获得锁定
# 否则超时后将返回False
threadLock.acquire()
print_time(self.name, self.counter, 5)
# 释放锁
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
threadLock = threading.Lock()
threads = []
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 开启新线程
thread1.start()
thread2.start()
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有线程完成
for t in threads:
t.join()
print "Exiting Main Thread"
try_except
#coding=utf-8
import sys
# s=raw_input("Enter something>>")
# print s
try:
s=raw_input("Enter something>>")
except EOFError:
print "\nWhy did you do an EOF on me?"
sys.exit()
except:
print ‘\n Something unexpected occurred.‘
print "Done."
菜鸟教程
Using_copy
#coding=utf-8
a=[‘apple‘,‘mango‘,‘carrot‘,‘banana‘]
b=a
print "a is", a
print "b is", b
del a[0]#可变数据结构,两个list都跟着变
print ">>\na is", a
print "b is", b
c=a[:]#采用切片操作符运用
print "a is", a
print "c is", c
del c[0]
print ">>\na is", a
print "c is", c
using_dict
#coding=utf-8
d={‘jh‘:‘jianhu‘,‘yc‘:‘yancheng‘,‘js‘:‘jiangsu‘,1:55}
print">>>>>\n d is",d
ax=d.copy()
print "ax is",ax
for a,b in d.items():
print‘a is %s,b is %s‘%(a,b)
ax.clear()
print "ax is",ax
seq = (‘name‘, ‘age‘, ‘sex‘)
value=(‘dahu‘,24,‘male‘)
dict = dict.fromkeys(seq)
print "New Dictionary : %s" % str(dict)#这样输出形式也行
print "d is %s" % str(d)
dc = dict.fromkeys(seq, 1)#算是创建一个新的字典,设置每个初始值
# d = dict.fromkeys(seq, value)#不可以这样,交叉设置不行
print "New Dictionary d is: %s" % str(dc)
print(d.has_key(‘jh‘))#判断是否有键值
print(d.get(‘jh‘))
print(d.get(‘ycs‘,‘haha‘))#返回指定键的值,如果值不在字典中,返回你设定的值。
print "<><>",d
x=d.items()#返回一对键和值,一对作为一个tuple
print x,type(x)#返回x为list,x[0]为tuple,所以上面的例子中x用作循环了
xplus=d.iteritems()
print xplus,type(xplus)
xp=list(xplus)#其实跟.items()方法区别不大
print xp,type(xp[0])#字典.iteritems()方法在需要迭代结果的时候使用最适合,而且它的工作效率非常的高。
k=d.keys()
print k,type(k)#类型为list
kplus=d.iterkeys()
print kplus,type(kplus)
kp=list(kplus)
print kp,type(kp)#跟上面iteritems比较类似
# iterkeys返回一个迭代器,而keys返回一个list,表面上看没啥区别,前者不能直接print,而后者可以,在数据量比较大的时候,for循环里用迭代器的效率要比list大很多。
v=d.values()#返回value列表
print v,type(v)
vplus=d.itervalues()
print vplus,type(vplus)
vp=list(vplus)
print vp,type(vp)#同上类比
pp=d.pop(‘jh‘)
print ">>>>\npp is",pp
pa=d.popitem()
print "pa is ",pa,type(pa)
print d
del d[‘jh‘]
#clear()方法是用来清除字典中的所有数据
#pop()方法的作用是:删除指定给定键所对应的值,返回这个值并从字典中把它移除
#列表中pop()方法,要么删除最后一位,要么指定位置删除,这个不一样
#popitem随机返回并删除字典中的一对键和值,是tuple
#也可以直接del某键,值也会一起删掉。
d={‘jh‘:‘jianhu‘,‘yc‘:‘yancheng‘,‘js‘:‘jiangsu‘,1:55}
df=d.setdefault(‘sz‘,‘suzhou‘)#会实际添加进去,两个用法比较接近
df=d.setdefault(‘jh‘,‘beijing‘)
gf=d.get("bj",‘beijing‘);print gf#不会真的添加进去
print d
beif={"gz":"guangzhou"};print beif
beif.update(d);print beif#把里面的键、值对更新到第一个字典里
vi=d.viewvalues()#viewitems,viewkeys和viewvalues的用法,类型比较奇怪。
print vi,type(vi)
print(len(vi))
using_file
#coing=utf-8
#coding=gbk
poem=‘‘‘\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
‘‘‘
f=file(‘poem.txt‘,‘w‘)
f.write(poem)
f.close
f=file(‘poem.txt‘,‘w+‘)
# while True:
# line= f.readline()
# if len(line)== 0:
# break
# print line,len(line)
# print(f.readline())
# print(f.readlines())
f.seek(20,0)
print‘>>>‘,f.readline()
print f.tell()
#返回当前在文件中的位置,这个可以跟readline结合起来玩
# f.truncate(3)#存在则截断该字节数,不存在则从当前位置截断,之后所有字符都被删除
f.close()
using_list
#coding=utf-8
shoplist=[‘apple‘,‘mango‘,‘carrot‘,‘banana‘]
print ">>>>>>\nI have",len(shoplist),‘items to purchase.‘
print "These items are",
for item in shoplist:
print item, #这边加,就表示连起来输出了
print ‘\nI also have to buy rice.‘
shoplist.append(‘rice‘)
print "My shopping list is now",shoplist
print "I will sort my list now"
shoplist.sort()
print "Sorted shopping list is",shoplist
print"The first item I will buy is",shoplist[0]
olditem=shoplist[0]
del shoplist[0]
print "I bought the",olditem
print "My shopping list is now",shoplist
using_name
#coding =utf-8
if __name__ ==‘__main__‘:
print "This program is being run by itself."
else:
print ‘I am beng imported from another module.‘
# $ python using_name.py
# This program is being run by itself
# $ python
# >>> import using_name
# I am being imported from another module
# >>>
Using_slice
#coding=utf-8
li=[1,2,3,4,5,6,7]
print li[1:];print li[1:len(li)]#最后这个超过len(li)也行的
print li[:] ;print li[0:len(li):1]#其实索引、终止索引、步长
# len正好是统计了整个list的数量,正常计数呢又从0开始,少一位,很恰巧。
print li[::]
print li[::-1]#逆序排布
print">>>>>"
#实现让字符串倒叙打印
s=‘abcdefg‘
for i in range(len(s)):
print s[-i-1]#呵呵,自己写的
i=-1
print">>>>>"#每次都把最后一个字符砍掉
for i in [None]+range(-1,-len(s),-1):#倒序负数实现
print s[:i]
print(len(s))
print(range(-1,-7,-1))
#---倒序正数实现
for i in range(len(s),0,-1):
print s[:i]
using_str
#coding=utf-8
#coding=gbk
s="abcdef"
print s,type(s)
print "xx"+s,"ac" in s
b="xx"+s
print s[-1]# 有点像list里面的操作了
print s[0:len(s)]
#----字母处理
print "\n>>>>"
print s.upper()#全部大写
s=s.upper()
print s.lower()#全部小写
print s.swapcase()#大小写互换
print s.title()#所有单词首字母大写,其余小写的
print s.capitalize()#首字母大写,其余小写
print "\n>>>>"
#----格式化相关
print ‘%s ljust=%s‘ % (s,s.zfill(10))
# 获取固定长度,右对齐,左边不够用空格补齐:str.ljust(width)
# 获取固定长度,左对齐,右边不够用空格补齐:str.rjust(width)
# 获取固定长度,中间对齐,两边不够用空格补齐:str.center(width)
# 获取固定长度,右对齐,左边不足用0补齐: str.zfill(width)
#-----字符串搜索相关
s="afbcfbdesf"
print s.find(‘f‘)#搜索指定字符串,没有返回-1
print s.find(‘f‘,2)#指定起始位置搜索
print s.find(‘f‘,2,7)#指定起始及结束位置搜索
print s.rfind(‘f‘,1,8)#从右边开始,用法一样的
print s.count(‘f‘)#搜索到多少个指定字符串
#index用法
print "\n>>>>"
print s.index(‘fb‘,0,8)#用法比较类似,查不到会返回异常
#-----字符串替换相关
print(s.replace(‘fb‘,‘diao‘))#全给替换了
print(s.replace(‘fb‘,‘diao‘,1))#替换指定次数的
#----字符串去空格及去指定字符
s=‘you Hello,where are you‘
print s
print(s.strip())#去两边空格
print(s.lstrip())#去左边空格
print(s.rstrip())#去右边空格
print(s.strip(‘you?‘))#去两边字符串,相应的也有lstrip,rstrip
#-------split用法
s="afbcfbdesfa"
print">>><<<\n"
print(s.split(‘f‘))#按指定字符分割字符串为数组
sa=‘ab c\n\nde fg\rkl\r\n‘
print(sa.splitlines(True))#默认为 False,不包含换行符,如果为 True,则保留换行符。
#-------字符串判断相关
print(s.startswith(‘afbc‘))#是否以start开头
print(s.endswith(‘af‘))#是否以end结尾
print(s.isalnum())#是否全为字母或数字
print(s.isalpha())#是否全字母
print(s.isdigit())#是否全数字
print(s.islower())#是否全小写
print(s.isupper())#是否全大写
#-------expandtabs相关
str = "this is\tstring example....wow!!!"
print ">>>\nOriginal string: " + str
print "Defualt exapanded tab: " + str.expandtabs()
print "Double exapanded tab: " + str.expandtabs(12)
#------join相关
b=‘**‘
print b
print(b.join(s))#b加入到s里面,s在两端
#------分隔相关
s=‘Imissmissyou‘
print(s.partition(‘miss‘))#返回一个3元的元组,第一个左边的,第二个为分隔符本身,第三个是右边的
print(s.rpartition(‘miss‘))#右边开始找
#--------- translate()的用法
from string import maketrans
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!"
print str.translate(trantab)
#>>>th3s 3s str3ng 2x1mpl2....w4w!!!,握草,完全跟对应的替换了有木有!
print str.translate(trantab,‘xm‘)#字符串中要过滤的字符列表。
xas=‘abzAZ‘
print(max(xas))#小写的大,z最大,A最小
using_tuple
#coding=utf-8
zoo=(‘wolf‘,‘elephant‘,‘penguin‘)
print ">>>>>\nNumber of animals in the zoo is ",len(zoo)
print "zoo is",zoo
new_zoo =(‘monkey‘,‘dolphin‘,zoo)
print "new zoo is",new_zoo
print "Number of animals in the new zoo is",len(new_zoo)
print "All animals in new zoo are",new_zoo
print "Animals brought from old zoo are",new_zoo[2]
print "Last animal brought from old zoo is",new_zoo[2][2]
菜鸟教程例子
sl1
#coding=utf-8
# 题目:有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
# 程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。
count =0
for i in range(1,5,1):
for j in range(1,5):
for k in range(1,5):
if (i !=j) and (i !=k) and (j !=k):
print i*100+j*10+k
count +=1
print ">>> total is ", count
sl2
#!/usr/bin/python
# -*- coding: UTF-8 -*-
#题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?
# 程序分析:请利用数轴来分界,定位。注意定义时需把奖金定义成长整型。
i = int(raw_input(‘净利润:‘))
arr = [1000000,600000,400000,200000,100000,0]
rat = [0.01,0.015,0.03,0.05,0.075,0.1]
r = 0
for idx in range(0,6):
if i>arr[idx]:
r+=(i-arr[idx])*rat[idx]
print (i-arr[idx])*rat[idx]
i=arr[idx]
print r
sl3
#coding =utf-8
# 题目:一个整数,它加上100和加上268后都是一个完全平方数,请问该数是多少?
#程序分析:在10000以内判断,将该数加上100后再开方,加上268后再开方,如果开方后的结果满足如下条件,即是结果。请看具体分析:
import math
i=0
# while True:
# if type(math.sqrt(i+100))==‘int‘ and type(math.sqrt(i+268))==‘int‘:
# print i
# break
# i +=1
count=0
while True:
x = int(math.sqrt(i + 100))
y = int(math.sqrt(i + 268))
if(x * x == i + 100) and (y * y == i + 268):
print i
count +=1
i +=1
if count ==3:
break
sl4
#coding=utf-8
import time
#输入某年某月某日,判断这一天是这一年的第几天?
year=int(raw_input(‘请输入年:‘))
month=int(raw_input(‘请输入月:‘))
day=int(raw_input(‘请输入日:‘))#肯定要考虑闰年
if year%400==0:
run=1
elif year%4==0 and year%100!=0:
run=1
else:
run=0
#首先先判断是不是闰年
a=[31,28+run,31,30,31,30,31,31,30,31,30,31]
days=0
for i in range(len(a)):
if i+1<month:
days +=a[i]
days=days+day
print days
sl5
#coding=utf-8
# 输入三个整数x,y,z,请把这三个数由小到大输出。
l=[]
for i in range(3):
x=input("integer is :")
l.append(x)
l.sort()
print l
#多么完美的输出!beautiful!
Sl6
#coding=utf-8
#题目:斐波那契数列。
# 程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34
f=[]
f.append(0)
f.append(1)
for i in range(2,10):
# f[i]=f[i-2]+f[i-1]
f.append(f[i-2]+f[i-1])
print f[:]
sl7
有两个序列a,b,大小都为n,序列元素的值任意整形数,无序;
要求:通过交换a,b中的元素,使[序列a元素的和]与[序列b元素的和]之间的差最小。
#!/usr/bin/env python
a = [1000, 999, 998, 997, 996, 995]
b = [994, 993, 992, 3, 2, 1]
#a = [3, 8, 11]
#b = [1, 2, 7]
x = y = 0
min = abs((sum(a)) - (sum(b)))
tag = 1
#num = 0
while tag:
old = min
while x < len(a):
while y < len(b):
a[x], b[y] = b[y], a[x]
# num = num + 1
print a
print b
tmp = abs((sum(a)) - (sum(b)))
if min > tmp:
min = tmp
else:
a[x], b[y] = b[y], a[x]
y = y + 1
x = x + 1
y = 0
if min == old:
tag = 0
else:
x = y = 0
print min
#print num
sl11
#coding=utf-8
#题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
# def born(pair,month=1):
# x=[1,1]
# if month >=3:
# y=pair*2
#-----打算用递归做,failed
# count=0
# def tuzi(month):
# if month==1 or month==2:
# return 1
# count +=1
# if month >=3:
# for i in range(3,month+1):
# return 1+tuzi(month-2)
# count +=1
# print(tuzi(8))
#-----answer
f1 = 1
f2 = 1
for i in range(1,21):
print ‘%12ld %12ld‘ % (f1,f2),
if (i % 3) == 0:
print ‘‘
f1 = f1 + f2
f2 = f1 + f2
sl12
# coding=utf-8
# 题目:判断101-200之间有多少个素数,并输出所有素数。
import math
leap=1
for i in range(2,20001):
for x in range(2,int(math.sqrt(i)+1)):
if i%x ==0:
leap=0#是偶数就确定为0
break
if leap==1:
print i,
leap =1
sl13
# coding=utf-8
#题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。。
for i in range(100,1000):
x=i//100
y=i//10-10*x#这边采用取整的算法
z=i-100*x-10*y
if x**3+y**3+z**3==i:
print i,
sl14
# coding=utf-8
#题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
def reduceNum(n):
print ‘{} = ‘.format(n),
if not isinstance(n, int) or n <= 0 :
print ‘请输入一个正确的数字 !‘
exit(0)
elif n in [1] :
print ‘{}‘.format(n)
while n not in [1] : # 循环保证递归,除到最后n即为1,退出循环
for index in xrange(2, n + 1) :
if n % index == 0:
n /= index # n 等于 n/index
if n == 1:
print index
else : # index 一定是素数
print ‘{} *‘.format(index),
break #当找到一个因子后,跳出for循环,又从2开始找,所以永远是素数
reduceNum(input(‘Input a number:‘))
sl17
# coding=utf-8
#题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
s=raw_input(‘Inut something:‘)
char=0
space=0
digit=0
other=0
for i in s:
if i.isalpha():
char+=1
elif i.isspace():
space+=1
elif i.isdigit():
digit+=1
else:
other+=1
print ‘char=%d,space=%d,digit=%d,other=%d‘%(char,space,digit,other)
sl18
# coding=utf-8
#题目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加有键盘控制。
a=input(‘input a number:\n‘)
b=input(‘input counts:\n‘)
x=0#表示单个数字
y=0
for i in range(1,b+1): #外循环计算各个数相加
for j in range(i,0,-1): #内循环生成每个数
if j==1:
x+=a
break
else :
x+=a*10**(j-1)
j-=1
y+=x
x=0 #这个数相加后清空,下个数重新生成
print ‘final is‘,y
sl19
# coding=utf-8
#题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。
s=0
for x in range(2,13):#这个算的是各个质因子之和
n=x
while n not in [1]:
for index in xrange(2,n+1):
if n % index == 0:
# print ‘index is‘,index
n /= index # n 等于 n/index
if n == 1:
s+=index
else : # index 一定是素数
s+=index
print ‘bofore break n is%d,s is%d,index is%d‘%(n,s,index)
break
s=s+1
print ‘x is %d,s is %d‘%(x,s)
if s==x:
print ‘equal‘,s
s=0
# coding=utf-8
# coding =gbk
#题目:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数。
s=0
for x in range(2,1000):
a=[]
for index in xrange(1,x):
if x % index == 0:
a.append(index)
# print"x is %d\n因子:%s"%(x,str(a))
if x==sum(a):#数组里求和
print ">>>>>>x is %d\n因子:%s"%(x,str(a))
sl20
# coding=utf-8
#题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
# def ball_fantan(h,count):
# fantan =float(0)
# fantan=h/(2**count)
# return fantan
# s=float(0)
# 第k次反弹和第k+1次落地距离是一样的
# for i in range(1,10):
# s+=ball_fantan(100,i)
# s=2*s+100
# print"共经过%d米,第10次反弹%d米"%(s,ball_fantan(100,10))
Sn = 100.0
Hn = Sn / 2
for n in range(2,11):
Sn += 2 * Hn
Hn /= 2
print ‘Total of road is %f‘ % Sn
print ‘The tenth is %f meter‘ % Hn
sl21
题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
程序分析:采取逆向思维的方法,从后往前推断。
程序源代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
x2 = 1
for day in range(9,0,-1):
x1 = (x2 + 1) * 2
x2 = x1
print x1
以上实例输出结果为:
1534
Sl22
题目:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
程序源代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
for i in range(ord(‘x‘),ord(‘z‘) + 1):
for j in range(ord(‘x‘),ord(‘z‘) + 1):
if i != j:
for k in range(ord(‘x‘),ord(‘z‘) + 1):
if (i != k) and (j != k):
if (i != ord(‘x‘)) and (k != ord(‘x‘)) and (k != ord(‘z‘)):
print ‘order is a -- %s\t b -- %s\tc--%s‘ % (chr(i),chr(j),chr(k))
以上实例输出结果为:
order is a -- z b -- x c--y
sl23
题目:打印出如下图案(菱形):
*
***
*****
*******
*****
***
*
程序分析:先把图形分成两部分来看待,前四行一个规律,后三行一个规律,利用双重for循环,第一层控制行,第二层控制列。
程序源代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from sys import stdout
for i in range(4):
for j in range(2 - i + 1):
stdout.write(‘ ‘)
for k in range(2 * i + 1):
stdout.write(‘*‘)
for i in range(3):
for j in range(i + 1):
stdout.write(‘ ‘)
for k in range(4 - 2 * i + 1):
stdout.write(‘*‘)
以上实例输出结果为:
*
***
*****
*******
*****
***
*
Sl24
题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
程序分析:请抓住分子与分母的变化规律。
程序源代码:
方法一:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = 2.0
b = 1.0
s = 0
for n in range(1,21):
s += a / b
t = a
a = a + b
b = t
print s
方法二:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = 2.0
b = 1.0
s = 0.0
for n in range(1,21):
s += a / b
b,a = a , a + b
print s
s = 0.0
for n in range(1,21):
s += a / b
b,a = a , a + b
print s
方法三:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = 2.0
b = 1.0
l = []
for n in range(1,21):
b,a = a,a + b
l.append(a / b)
print reduce(lambda x,y: x + y,l)
以上实例输出结果为:
32.6602607986
Sl25
题目:求1+2!+3!+...+20!的和。
程序分析:此程序只是把累加变成了累乘。
程序源代码:
方法一:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
n = 0
s = 0
t = 1
for n in range(1,21):
t *= n
s += t
print ‘1! + 2! + 3! + ... + 20! = %d‘ % s
方法二:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
s = 0
l = range(1,21)
def op(x):
r = 1
for i in range(1,x + 1):
r *= i
return r
s = sum(map(op,l))
print ‘1! + 2! + 3! + ... + 20! = %d‘ % s
以上实例输出结果为:
1! + 2! + 3! + ... + 20! = 2561327494111820313
Sl26
题目:利用递归方法求5!。
程序分析:递归公式:fn=fn_1*4!
程序源代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def fact(j):
sum = 0
if j == 0:
sum = 1
else:
sum = j * fact(j - 1)
return sum
for i in range(5):
print ‘%d! = %d‘ % (i,fact(i))
以上实例输出结果为:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
Sl27
题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。
程序分析:无。
程序源代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def output(s,l):
if l==0:
return
print (s[l-1])
output(s,l-1)
s = raw_input(‘Input a string:‘)
l = len(s)
output(s,l)
以上实例输出结果为:
Input a string:abcde
e
d
c
b
a
sl28
题目:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?
程序分析:利用递归的方法,递归分为回推和递推两个阶段。要想知道第五个人岁数,需知道第四人的岁数,依次类推,推到第一人(10岁),再往回推。
程序源代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def age(n):
if n == 1: c = 10
else: c = age(n - 1) + 2
return c
print age(5)
以上实例输出结果为:
18
Sl29
题目:给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
程序分析:学会分解出每一位数。
程序源代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
x = int(raw_input("请输入一个数:\n"))
a = x / 10000
b = x % 10000 / 1000
c = x % 1000 / 100
d = x % 100 / 10
e = x % 10
if a != 0:
print "5 位数:",e,d,c,b,a
elif b != 0:
print "4 位数:",e,d,c,b,
elif c != 0:
print "3 位数:",e,d,c
elif d != 0:
print "2 位数:",e,d
else:
print "1 位数:",e
以上实例输出结果为:
请输入一个数:
23459
5 位数: 9 5 4 3 2
请输入一个数:
3472
4 位数: 2 7 4 3
Sl30
题目:一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同。
程序分析:无。
程序源代码:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
a = int(raw_input("请输入一个数字:\n"))
x = str(a)
flag = True
for i in range(len(x)/2):
if x[i] != x[-i - 1]:
flag = False
break
if flag:
print "%d 是一个回文数!" % a
else:
print "%d 不是一个回文数!" % a
以上实例输出结果为:
请输入一个数字:
12321
12321 是一个回文数!
sqdEvens = [x ** 2 for x in range(8) if not x % 2]
多么简洁的代码!获取偶数的平方!
Mysql教程
开启服务
C:\mysql-5.0.45-win32\bin>mysqld –console
关闭服务:
C:\mysql-5.0.45-win32\bin>mysqladmin -uroot shutdown
连接到 MySQL 服务器:
[[email protected] ~]$ mysql -uroot –p
1.创建数据库
CREATE DATABASE dbname
查看数据库
mysql> show databases;
选择数据库
USE dbname
查看 test1 数据库中创建的所有数据表:
mysql> show tables;
2.删除数据库
删除数据库的语法很简单,如下所示:
drop database dbname;
数据库的名字不可以改
3.创建表
在数据库中创建一张表的基本语法如下:
CREATE TABLE tablename (column_name_1 column_type_1 constraints,
column_name_2 column_type_2 constraints , ……column_name_n column_type_n
constraints)
mysql> create table emp(ename varchar(10),hiredate date,sal decimal(10,2),deptno int(2));
查看一下表的定义,可以使用如下命令:
DESC tablename
为了查看更全面的表定义信息,可以使用如下命令实现:
mysql> show create table emp \G;
4.删除表
表的删除命令如下:
DROP TABLE tablename
5修改表
(1) 修改表类型,语法如下:
ALTER TABLE tablename MODIFY [COLUMN] column_definition [FIRST | AFTER col_name]
mysql> alter table emp modify ename varchar(20);
(2)增加表字段,语法如下:
ALTER TABLE tablename ADD [COLUMN] column_definition [FIRST | AFTER col_name]
alter table emp add column age int(3);
(3)删除表字段,语法如下:
ALTER TABLE tablename DROP [COLUMN] col_name
mysql> alter table emp drop column age;
(4)字段改名,语法如下:
ALTER TABLE tablename CHANGE [COLUMN]
old_col_name column_definition
[FIRST|AFTER col_name]
mysql> alter table emp change age age1 int(4) ;
(5)修改字段排列顺序
mysql> alter table emp add birth date after ename;
(6)表改名,语法如下:
ALTER TABLE tablename RENAME [TO] new_tablename
mysql> alter table emp rename emp1;
DML 语句
DML 操作是指对数据库中表记录的操作,主要包括表记录的插入(insert)、更新(update)、删除(delete)和查询(select),是开发人员日常使用最频繁的操作。下面将依次对它们进行介绍。
插入记录
INSERT INTO tablename (field1,field2,……fieldn) VALUES(value1,value2,……valuesn);
mysql> insert into emp (ename,hiredate,sal,deptno) values(‘zzx1‘,‘2000-01-01‘,‘2000‘,1);
mysql> insert into emp values(‘lisa‘,‘2003-02-01‘,‘3000‘,2);
只对表中的 ename 和 sal 字段显式插入值:
mysql> insert into emp (ename,sal)
values(‘dony‘,1000);
insert
语句还有一个很好的特性,可以一次性插入多条记录,语法如下:
INSERT
INTO tablename (field1, field2,……fieldn)
VALUES
(record1_value1, record1_value2,……record1_valuesn),
(record2_value1, record2_value2,……record2_valuesn),
……
(recordn_value1, recordn_value2,……recordn_valuesn)
;
mysql> insert into dept values(5,‘dept5‘),(6,‘dept6‘);
更新记录
通过 update 命令进行更改,语法如下:
UPDATE
tablename SET field1=value1,field2.=value2,……fieldn=valuen
[WHERE CONDITION]
将表 emp 中 ename 为“lisa”的薪水(sal)从 3000 更改为 4000:
mysql> update emp set sal=4000 where ename=‘lisa‘;
update
命令可以同时更新多个表中数据,语法如下:
UPDATE
t1,t2…tn set t1.field1=expr1,tn.fieldn=exprn [WHERE CONDITION]
mysql> update emp a,dept b set a.sal=a.sal*b.deptno,b.deptname=a.ename where
a.deptno=b.deptno;
两个表的数据同时进行了更新。
注意:多表更新的语法更多地用在了根据一个表的字段,来动态的更新另外一个表的字段
删除记录
如果记录不再需要,可以用 delete 命令进行删除,语法如下:
DELETE
FROM tablename [WHERE CONDITION]
在 emp 中将 ename 为‘dony’的记录全部删除,命令如下:
mysql> delete from emp where ename=‘dony‘;
mysql> delete a,b from emp a,dept b where a.deptno=b.deptno and a.deptno=3;
注意:不管是单表还是多表,不加 where 条件将会把表的所有记录删除,所以操作时一定要小心。
查询记录
SELECT * FROM tablename [WHERE CONDITION]
“*”表示要将所有的记录都选出来,也可以用逗号分割的所有字段来代替,例如,以
下两个查询是等价的:
mysql> select ename,hiredate,sal,deptno from emp;
(1) 查询不重复的记录。
有时需要将表中的记录去掉重复后显示出来,可以用 distinct 关键字来实现:
mysql>
select ename,hiredate,sal,deptno from emp;
(2)条件查询
mysql> select * from emp where deptno=1;
上面的例子中,where 后面的条件是一个字段的‘=’比较,除了‘=’外,还可以使用>、<、>=、<=、!=等比较运算符;多个条件之间还可以使用 or、and 等逻辑运算符进行多条件联合查询
(3)排序和限制
用关键字 ORDER BY 来实现,语法如下:
SELECT
* FROM tablename [WHERE CONDITION] [ORDER BY field1 [DESC|ASC] , field2
[DESC|ASC],……fieldn [DESC|ASC]]
DESC 表示按照字段进行降序排列,ASC 则表示升序排列,如果不写此关键字默认是升序排列。
对于排序后的记录,如果希望只显示一部分,而不是全部,这时,就可以使用 LIMIT 关键字来实现,LIMIT 的语法如下:
SELECT
……[LIMIT offset_start,row_count]
显示 emp 表中按照 sal 排序后的前 3 条记录:
mysql> select * from emp order by sal limit 3;
(4)聚合
聚合操作的语法如下:
SELECT
[field1,field2,……fieldn] fun_name
FROM tablename
[WHERE where_contition]
[GROUP BY field1,field2,……fieldn
[WITH ROLLUP]]
[HAVING- where_contition]
统计人数大于
1
人的部门:
mysql> select deptno,count(1) from emp group by
deptno having count(1)>1;
mysql> select sum(sal),max(sal),min(sal) from emp;
约束
主键约束
联合主键
已经存在数据,仍添加主键
删除主键
外键约束
A表和B表有同一列数据,A表设置成主键约束,B表才可以设置成外键约束
如果已经存在数据
Fk_只是约束键的名称
删除外键
非空约束
检查约束
数据已经存在
唯一约束
Unique
以上是关于python部分内容存档的主要内容,如果未能解决你的问题,请参考以下文章