Day08 学习笔记

输入与类型

  • 使用 input() 接收键盘输入,并保留原有数据类型;打印其值与类型便于观察:
1
2
3
4
# input.py
c = input("请输入:")
print c
print type(c)

线程基础(thread 模块)

  • 通过 thread.start_new_thread(func, args) 启动轻量线程;主线程可 sleep 等待子线程执行完毕:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import thread
import time

def loop1():
print "loop1 up:", time.ctime()
time.sleep(6)
print "loop1 down:", time.ctime()

def loop2():
print "loop2 up:", time.ctime()
time.sleep(3)
print "loop2 down:", time.ctime()

print "main:", time.ctime()
thread.start_new_thread(loop1, ())
thread.start_new_thread(loop2, ())
time.sleep(10)
print "all down:", time.ctime()

线程继承(threading.Thread)

  • 继承 threading.Thread,覆盖 run(),使用 start() 启动、join() 等待:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import threading
import time

class MyThread(threading.Thread):
def __init__(self, threadID, name, delay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.delay = delay

def run(self):
print "starting", self.name
print_time(self.name, 5, self.delay)
print "exiting", self.name

def print_time(threadName, count, delay):
while count:
time.sleep(delay)
print "%s : %s" % (threadName, time.ctime())
count -= 1

t1 = MyThread(1, "Thread-1", 1)
t2 = MyThread(2, "Thread-2", 2)
t1.start()
t2.start()
# t1.join() # 可选等待 t1
t2.join() # 等待 t2 结束
print "Exiting Main!!!"

小项目:英汉词典(交互菜单)

  • 支持添加与查询单词,使用字典作为存储结构:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class EnglishDictionary:
def aadd_dic(self, dic):
try:
while True:
word = raw_input("\033[0;31;42mEnter键返回主界面,\033[0m请输入英文单词:")
if len(word) == 0:
break
meaning = raw_input("请输入中文翻译:")
dic[word] = meaning
print "该单词已添加到字典库!!!"
except Exception, e:
print e.__str__()

def search_dic(self, dic):
try:
while True:
word = raw_input("\033[0;31;42mEnter键返回主界面,\033[0m请输入要查询的英文单词:")
if len(word) == 0:
break
if word in dic:
print "%s 的中文翻译是:%s" % (word, dic[word])
else:
print "字典库中未找到这个单词!!!"
except Exception, e:
print e.__str__()

def run():
try:
worddic = dict()
xiaohong = EnglishDictionary()
while True:
print "请选择功能:\n1:添加 \n2:查询 \n3:退出"
c = input("请输入要执行的代号:")
if c == 1:
xiaohong.aadd_dic(worddic)
elif c == 2:
xiaohong.search_dic(worddic)
elif c == 3:
break
else:
print "输入错误!!!"
except Exception, e:
print e.__str__()

if __name__ == "__main__":
run()

Day08 学习笔记
https://blog.pangcy.cn/2018/10/22/后端编程相关/python/python2基础/Day08 学习笔记/
作者
子洋
发布于
2018年10月22日
许可协议