笨辦法學python. 1php
Ec6字符串和文本... 1html
ec7. 1java
ec8. 1node
Ec9. 1python
Ec10 轉義字符... 1mysql
Ec11提問... 1git
raw_input和input的區別... 1算法
Ec12提示別人... 1sql
ec13 參數,解包,變量... 1shell
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
Ashdgasbjdb
Asdhgajsd
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)
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)
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."
))
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
''')#這樣寫就會換行,應該是'''起做用
#--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位十六進制所表明的任意字符
二位十六進制
注意:區分,斜槓:"/" 與 反斜槓:"\" ,此處不可互換
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)
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全都是字符型,無所謂。
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)
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
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不會接引號
#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()
#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()
#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()
#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()
#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)
#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)#果真不是按照行號來的
#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?"
#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的幾個值均可以用做結格式數據裏面裏面
#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就行,
# 注意函數之間寫文檔註釋,這個也很屌。
#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!"
#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
#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()
#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])#下限是不包含的
#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
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
#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')
#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()
#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
#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()
#coding=utf-8
def convert_number(s):
try:
return int(s)
except ValueError:
return None
s=raw_input("PLZ>>")
print(convert_number(s))
#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))
#coding=utf-8
import glob
print(glob.glob("H:\python_program\shiyanlou\*"))
#該命令找出文件夾下全部文件。
#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())#查詢當前工做路徑
#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命令。
#運用此命令須要先肯定文件的位置,一開始肯定工做區也是可行的!
#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
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)
#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()
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編碼之間的切換。
#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
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()
#coding=utf-8
from PIL import Image
import argparse
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")#字符全放在表裏面,注意他們的使用方式
# print ascii_char
# print len(ascii_char)
# a=list("!@#$%")#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)
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)
#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("$@B%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)
#-*- 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)
# 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
#-*- 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()
#-*- 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的一些用法
#-*- 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
#矩陣轉換的一些用法
# 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__
#-*- 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)
#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 >>>
'''
#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
#coding=utf-8
# for i in xrange(500):
# print #這個方法有點二
import sys
import os
os.system('cls')
#這纔是對的
#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) #讀取文件內容
#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)
#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()
#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.'
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import Tkinter
top = Tkinter.Tk()
# 進入消息循環
top.mainloop()
#!/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() # 進入消息循環
#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
#調用子類方法時,如今子類中進行調用,若是子類沒有,而後再在父類中調用
#coding=utf-8
def make_repeater(n):
return lambda s:s*n#lambda語句用來建立函數對象,返回表達式的值
twice = make_repeater(2)
print twice('word')
print twice(5)
#coding=utf-8
listone=[2,3,4]
listtwo=[2*i for i in listone if i >2]
print listtwo
#coding=utf-8
class Person:
def sayHi(self):
print "Hello,wtf?"
p=Person()
p.sayHi()
#coding=utf-8
def sayhi():
print "Hi, this is my module speaking!"
version = '0.1'
# import my_module
# my_module.sayhi()
# print 'version',my_module.version
from my_module import *
sayhi()
print 'version',version
#這邊注意,import的*用法,前面須要加對應庫,有* 的則不須要
#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
#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))
#coding=utf-8
import sys
print"I",
print"love",
print'you!'
sys.stdout.write("I")
sys.stdout.write("love")
sys.stdout.write('you!')
#!/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"
#!/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"
#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."
#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
#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))
#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()
#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
#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
# >>>
#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]
#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最小
#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]
#coding=utf-8
# 題目:有一、二、三、4個數字,能組成多少個互不相同且無重複數字的三位數?都是多少?
# 程序分析:可填在百位、十位、個位的數字都是一、二、三、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
#!/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
#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
#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
#coding=utf-8
# 輸入三個整數x,y,z,請把這三個數由小到大輸出。
l=[]
for i in range(3):
x=input("integer is :")
l.append(x)
l.sort()
print l
#多麼完美的輸出!beautiful!
#coding=utf-8
#題目:斐波那契數列。
# 程序分析:斐波那契數列(Fibonacci sequence),又稱黃金分割數列,指的是這樣一個數列:0、一、一、二、三、五、八、1三、2一、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[:]
有兩個序列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
#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
# 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
# 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,
# 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:'))
# 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)
# 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
# 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))
# 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
題目:猴子吃桃問題:猴子第一天摘下若干個桃子,立即吃了一半,還不癮,又多吃了一個次日早上又將剩下的桃子吃掉一半,又多吃了一個。之後天天早上都吃了前一天剩下的一半零一個。到第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
題目:兩個乒乓球隊進行比賽,各出三人。甲隊爲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
題目:打印出以下圖案(菱形):
*
***
*****
*******
*****
***
*
程序分析:先把圖形分紅兩部分來看待,前四行一個規律,後三行一個規律,利用雙重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('*')
以上實例輸出結果爲:
*
***
*****
*******
*****
***
*
題目:有一分數序列: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
題目:求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
題目:利用遞歸方法求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
題目:利用遞歸函數調用方式,將所輸入的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
題目:有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
題目:給一個很少於5位的正整數,要求:1、求它是幾位數,2、逆序打印出各位數字。
程序分析:學會分解出每一位數。
程序源代碼:
#!/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
題目:一個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]
多麼簡潔的代碼!獲取偶數的平方!
開啓服務
C:\mysql-5.0.45-win32\bin>mysqld –console
關閉服務:
C:\mysql-5.0.45-win32\bin>mysqladmin -uroot shutdown
鏈接到 MySQL 服務器:
[mysql@db3 ~]$ mysql -uroot –p
CREATE DATABASE dbname
查看數據庫
mysql> show databases;
選擇數據庫
USE dbname
查看 test1 數據庫中建立的全部數據表:
mysql> show tables;
刪除數據庫的語法很簡單,以下所示:
drop database dbname;
數據庫的名字不能夠改
在數據庫中建立一張表的基本語法以下:
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;
表的刪除命令以下:
DROP TABLE tablename
ALTER TABLE tablename MODIFY [COLUMN] column_definition [FIRST | AFTER col_name]
mysql> alter table emp modify ename varchar(20);
ALTER TABLE tablename ADD [COLUMN] column_definition [FIRST | AFTER col_name]
alter table emp add column age int(3);
ALTER TABLE tablename DROP [COLUMN] col_name
mysql> alter table emp drop column age;
ALTER TABLE tablename CHANGE [COLUMN] old_col_name column_definition
[FIRST|AFTER col_name]
mysql> alter table emp change age age1 int(4) ;
mysql> alter table emp add birth date after ename;
ALTER TABLE tablename RENAME [TO] new_tablename
mysql> alter table emp rename emp1;
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;
有時須要將表中的記錄去掉重複後顯示出來,能夠用 distinct 關鍵字來實現:
mysql> select ename,hiredate,sal,deptno from emp;
mysql> select * from emp where deptno=1;
上面的例子中,where 後面的條件是一個字段的‘=’比較,除了‘=’外,還可使用>、<、>=、<=、!=等比較運算符;多個條件之間還可使用 or、and 等邏輯運算符進行多條件聯合查詢
用關鍵字 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;
聚合操做的語法以下:
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