0%

python-第八天

python3基础学习

网络编程

服务端与客户端间通过TCP/IP协议通信

服务端

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
#!/usr/bin/env python
# coding=utf-8
import socket
import threading
import time
def tcplink(sock, addr):
print('Accept new connetction from %s:%s...' %addr)
sock.send(b'Welcome')
while True:
data = sock.recv(1024)
time.sleep(1)
if not data or data.decode('utf-8') == 'exit':
break
sock.send(('Hello, {}'.format(data).encode('utf-8')))
sock.close()
print('Connection from %s:%s closed.' %addr)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1',9999))
s.listen(5)
print('Waiting for connection...')

while True:
sock, addr = s.accept()
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()

客户端

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python
# coding=utf-8
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
print(s.recv(1024).decode('utf-8'))
for data in [b'Michael', b'Tracy', b'Sarah']:
s.send(data)
print(s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()

数据库操作

练习:请编写函数,在 Sqlite 中根据分数段查找指定的名字:

这道题刚好上学期java期末作业做过

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python
# coding=utf-8
# -*- coding: utf-8 -*-

import os, sqlite3

db_file = os.path.join(os.path.dirname(__file__), 'test.db')

if os.path.isfile(db_file):
os.remove(db_file)

# 初始数据:

conn = sqlite3.connect(db_file)

cursor = conn.cursor()

cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)')

cursor.execute(r"insert into user values ('A-001', 'Adam', 95)")

cursor.execute(r"insert into user values ('A-002', 'Bart', 62)")

cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)")

cursor.close()

conn.commit()

conn.close()

#第一种我想得到的写法
def get_score_in(low, high):
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
cursor.execute(r"select * from user order by score")
values = cursor.fetchall()
List = []
for result in values:
if result[2] >= low and result[2]<=high:
List.append(result[1])
cursor.close()
conn.close()
return List
' 返回指定分数区间的名字,按分数从低到高排序 '

#第二种写法,感觉更好,直接用数据库排好序了,不知道sql语法的可以跟我上面那个一样
def get_score_in(low, high):
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
cursor.execute(r"select * from user where score between ? and ? order by score",(low,high))
values = cursor.fetchall()
name = [x[1] for x in values]
cursor.close()
conn.close()
return name
' 返回指定分数区间的名字,按分数从低到高排序 '

# 测试:

assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95)

assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80)

assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'],get_score_in(60, 100)

print('Pass')

本文作者:NoOne
本文地址https://noonegroup.xyz/posts/4a143a03/
版权声明:转载请注明出处!