PYTHON — Shortest correct reusable writing patterns
Python in the selected experiments: Exp 9 uses TCP/UDP sockets; Exp 12 uses HTTP REST; Exp 13 uses XOR and RSA. They share Python syntax but not the same algorithm. Choose the correct program from the question.
Master socket skeleton — TCP: TWO files (Exp 9)
Server:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 5000))
s.listen(1)
c, addr = s.accept()
msg = c.recv(1024).decode()
print('Received:', msg)
c.sendall(b'TCP reply')
c.close()
s.close()
Client:
import socket
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect(('127.0.0.1', 5000))
c.sendall(b'Hello TCP')
print(c.recv(1024).decode())
c.close()
Run python server.py first, then python client.py. This is TCP only. For the UDP question, use the next pair rather than merely changing one word.
UDP differences (Exp 9)
socket.SOCK_DGRAMinstead ofSOCK_STREAM.- Server:
bind()thendata,addr = s.recvfrom(1024)followed bys.sendto(b'UDP reply',addr). - Client:
s.sendto(b'Hello UDP',('127.0.0.1',6000));data,addr = s.recvfrom(1024). - No
listen(),accept(), orconnect()is needed for this simple UDP exchange.
REST (Exp 12) — short independent program
import requests
r = requests.get('https://jsonplaceholder.typicode.com/posts/1', timeout=10)
print('Status Code:', r.status_code)
print('Response Data:', r.json())
Needs internet and requests; the status code is typically 200 when the service is reachable.
XOR encryption (Exp 13) — short independent program
message, key = 'NETWORK SECURITY', 7
cipher = ''.join(chr(ord(ch) ^ key) for ch in message)
plain = ''.join(chr(ord(ch) ^ key) for ch in cipher)
print('Original:', message)
print('Encrypted:', cipher)
print('Decrypted:', plain)
RSA requires cryptography and public/private keys; do not write XOR and claim it answers an RSA/asymmetric-specific question. Full runnable RSA file in Exp 13.
Practical-answer rule
Memorize common structure: import → create needed object → configure/request → send/receive/transform → print output → close/return. But always show the protocol- or algorithm-specific operations the question asks.
Two optional ready-to-run Python files
For speed, use MASTER_NETWORK.py (TCP, UDP, delay, REST) and MASTER_SECURITY.py (XOR/RSA). Run with a choice argument, e.g. python MASTER_NETWORK.py tcp-server; the companion client runs in a second terminal. In the written exam, choose just the relevant short experiment code rather than copying the whole multipurpose runner.