Programming and Networking Basics Guide
Programming and Networking Basics Guide
A variable is a named container that stores a value in the computer's memory. Think of it
as a labeled box where you can keep data[1]. Each variable has three properties:
Name: The identifier used to reference the variable (e.g., age, temperature)
Value: The actual data stored (e.g., 25, 98.6)
Type: The kind of data it holds (determines memory allocation and operations
allowed)
The computer allocates a specific memory location and size based on the variable's data
type.
What are the main primitive data types, and what are their memory requirements?
Data Size
Range/Purpose Example
Type (Typical)
int 4 bytes -2,147,483,648 to 2,147,483,647 age = 25
Decimal numbers (6-7 significant price =
float 4 bytes
digits) 19.99
Double precision decimals (15-17 pi =
double 8 bytes
significant digits) 3.14159
grade =
char 1 byte Single character (ASCII)
'A'
isActive =
bool 1 byte True or False
true
name =
string Variable Sequence of characters
"Alice"
How does type casting work, and why is it important?
Type casting converts a variable from one data type to another. There are two types:
Structur
Syntax Example Purpose
e
if (condition) { /*
if Execute block if condition is true
code */ }
if (condition) { } else {
if-else Two-way branching
}
if-else if-
Multiple conditions Multi-way branching
else
switch(variable) { Efficient multi-way branching for
switch
case value: } discrete values
What are loops, and what are the differences between loop types?
Loops repeat a block of code a specified number of times or until a condition is met.
Loop
Use Case Example
Type
Known number of for i in range(5): (iterate 5
for
iterations times)
Unknown iterations; while user_input != 'quit':
while
condition-based (repeat until user quits)
do- Execute at least once, Not common in Python; used in
while then check C/Java
Print numbers 1 to 5
for i in range(1, 6):
print(i)
Output: 1 2 3 4 5
Example: while loop
count = 0
while count < 3:
print(f"Count: {count}")
count += 1
Output: Count: 0, Count: 1, Count: 2
What are loop control statements?
Output: 0 1 2 3 4
Quick Reference Summary
Conditionals (if-else, switch) make decisions based on conditions
Loops (for, while) repeat code blocks
Loop control (break, continue) alters loop execution
A function is a reusable block of code that performs a specific task. Functions promote code
reusability, maintainability, and organization.
Basic Function Definition:
def greet(name):
"""Docstring: Function to greet a person"""
return f"Hello, {name}!"
result = greet("Alice")
print(result) # Output: Hello, Alice!
Function Components:
Parameters: Variables passed to the function
Return value: Data the function returns to the caller
Call: Executing the function with actual values (arguments)
What is scope, and what are the main types?
Example:
x = 10 # Global scope
def my_function():
y = 5 # Local scope
print(x) # Can access global x
print(y) # Can access local y
Structure:
def recursive_function(problem):
if base_case_met:
return solution # Base case: stop recursion
else:
return recursive_function(smaller_problem) # Recursive case
Example: Factorial
def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120 (5 * 4 * 3 * 2 * 1)
How does recursion trace execution?
factorial(5)
→ 5 * factorial(4)
→ 5 * 4 * factorial(3)
→ 5 * 4 * 3 * factorial(2)
→ 5 * 4 * 3 * 2 * factorial(1)
→ 5 * 4 * 3 * 2 * 1 (base case)
Recursion vs Iteration:
Recursion: Elegant for naturally recursive problems (trees, factorials), but slower
and uses more memory (call stack)
Iteration: Faster and uses less memory for most cases
def display_info(self):
return f"{[Link]} {[Link]}"
What is Encapsulation?
Encapsulation bundles data (attributes) and methods (functions) together, hiding internal
complexity from the outside.
class BankAccount:
def init(self, balance):
self.__balance = balance # Private attribute (hidden)
Parent class
class Animal:
def init(self, name):
[Link] = name
def make_sound(self):
return "Generic sound"
Polymorphism allows objects of different classes to be treated through the same interface.
The same method name performs different actions based on the object type.
class Cat(Animal):
def make_sound(self):
return f"{[Link]} meows: Meow!"
Polymorphism: same method, different
behavior
animals = [Dog("Max"), Cat("Whiskers")]
Output:
Max barks: Woof!
Whiskers meows: Meow!
What is Abstraction?
Abstraction hides complexity by showing only essential features and hiding
implementation details.
bike = Motorcycle()
print(bike.start_engine()) # Output: Motorcycle engine started
An array is a fixed-size collection of elements of the same data type, stored in contiguous
memory locations.
A list is a dynamic collection that can grow or shrink and may contain mixed data types.
Feature Array List
Size Fixed Dynamic
Data Types Same type Mixed types allowed
Memory Contiguous Can be scattered
Access Time O(1) O(1)
Language C, Java (built-in) Python, JavaScript
Access (indexing)
print(my_list[0]) # Output: 10 (first element)
print(my_list[-1]) # Output: 50 (last element)
Slicing
print(my_list[1:4]) # Output: [20, 30, 40]
Insert
my_list.insert(2, 25) # Insert 25 at index 2
print(my_list) # Output: [10, 20, 25, 30, 40, 50]
Delete
my_list.remove(25) # Remove by value
del my_list[0] # Delete by index
print(my_list) # Output: [20, 30, 40, 50]
A dictionary is an unordered collection of key-value pairs. Each key must be unique and is
used to access its corresponding value. Dictionaries are efficient for lookups.
Characteristics:
Unordered (in older Python versions; ordered since Python 3.7)
Mutable (can be modified)
Keys must be unique and immutable (strings, numbers, tuples)
Values can be any data type
Example:
student = {
"name": "Alice",
"age": 20,
"gpa": 3.8,
"courses": ["Python", "Data Science", "Web Dev"]
}
Access value
print(student["name"]) # Output: Alice
Update value
student["age"] = 21
Delete key-value pair
del student["courses"]
Operatio
Array List Dictionary
n
Create int arr[5] (C) my_list = [] my_dict = {}
arr[0] (by
Access list[0] dict["key"]
index)
append(), dict[key] =
Insert Fixed size
insert() value
Search O(n) O(n) O(1) average
Memory Fixed Dynamic Dynamic
Lay
Name Function Examples
er
Transp End-to-end communication, TCP (reliable), UDP
4
ort reliability (fast)
Lay
Name Function Examples
er
Netwo IP addresses,
3 Logical addressing, routing
rk routing protocols
Data Physical addressing, frame MAC addresses,
2
Link delivery Ethernet, Wi-Fi
Physic Transmission of raw bits Cables, fiber optics,
1
al over physical media radio waves
This layer ensures data is in a format that the application layer understands. It handles
translation, encryption, and compression.
Functions:
Encryption/Decryption: Convert plaintext to ciphertext and vice versa
Compression: Reduce file size (e.g., JPEG, PNG)
Translation: Convert between different character sets (ASCII, Unicode)
Example: When you download an image, the presentation layer decompresses it into a
viewable format.
Layer 5 - Session Layer (Connection Management)
This layer establishes, maintains, and terminates connections between devices. It manages
conversations between applications.
Functions:
Session Establishment: Create connection between applications
Session Maintenance: Keep connection alive, handle timeouts
Session Termination: Gracefully close connections
Example: When you log into a website, the session layer maintains your login state.
Proto Spee
Reliability Use Case
col d
Reliable (guarantees Slow Email, web browsing,
TCP
delivery, ordered) er file transfer
Unreliable (fast, no Faste Video streaming, online
UDP
guarantee) r gaming, VoIP
TCP Example:
Client → Server: "I want to send data" (connection established)
Data transfer with acknowledgments (guaranteed delivery)
Graceful close
UDP Example:
Client → Server: Send packet (fire and forget)
No acknowledgment; lost packets ignored
Layer 3 - Network Layer (Logical Addressing & Routing)
This layer handles logical addressing (IP addresses) and determines the best path for data
to travel across networks.
Key Functions:
IP Addressing: Assign unique addresses (IPv4, IPv6)
Routing: Forward packets to correct destination
Logical Segmentation: Divide networks using subnets
Key Protocols:
Functions:
MAC Addressing: Identify devices on local network (e.g., 00:1A:2B:3C:4D:5E)
Frame Assembly: Wrap data into frames
Switching: Forward frames between devices on same network
Key Technologies:
Physical Media:
Copper cables: Twisted pair (Cat5, Cat6), coaxial
Fiber optic cables: High-speed, long-distance
Wireless: Radio waves, infrared
Functions:
TCP/IP
OSI Layers Purpose
Layer
5-7 (Session, Presentation, HTTP, FTP, DNS,
Application
Application) SMTP, SSH
Transport 4 (Transport) TCP, UDP
IP (IPv4, IPv6), ICMP,
Internet 3 (Network)
IGMP
Network
1-2 (Physical, Data Link) Ethernet, Wi-Fi, PPP
Access
The TCP Three-Way Handshake is a process that establishes a TCP connection between a
client and server. It synchronizes both parties and ensures reliable communication can
begin[4].
The Three Steps:
Step 1: SYN (Synchronize)
Client initiates: Sends a TCP packet with the SYN flag set
Includes: Client's Initial Sequence Number (ISN) - a random starting number
Purpose: "I want to start a connection, and here's my starting sequence number"
Step 2: SYN-ACK (Synchronize-Acknowledge)
Server responds: Sends a TCP packet with SYN and ACK flags set
Includes: Server's ISN and acknowledgment of client's ISN (Client ISN + 1)
Purpose: "I acknowledge your sequence number, and here's mine"
Visual Representation:
Client Server
||
|--- SYN (seq=100) ------------>|
| [SYN received]
|<-- SYN-ACK (seq=300, ack=101)-|
| [SYN-ACK received] |
|--- ACK (seq=101, ack=301) --->|
| [ESTABLISHED]
|========== Data Transfer ======|
| (both ESTABLISHED) |
Why is the Three-Way Handshake important?
Example: Your home router typically uses [Link]/24, assigning addresses like
[Link], [Link], etc.
How does NAT (Network Address Translation) work?
NAT allows private IP addresses to communicate with the public internet by translating
them to a public IP address.
Process:
Internal Device ([Link])
↓
NAT Router translates to public IP (e.g., [Link])
↓
Request sent to internet
↓
Response returns to public IP
↓
NAT Router translates back to private IP ([Link])
↓
Device receives response
Benefit: Allows multiple private devices to share one public IP address, improving security
and conserving public IP addresses.
What is subnetting, and how does it work?
Subnetting divides a large network into smaller, manageable subnetworks (subnets). It
improves network efficiency, security, and organization.
Components:
Network Address: Identifies the subnet (all host bits = 0)
Subnet Mask: Determines which bits are network and which are host
Broadcast Address: Identifies all devices in subnet (all host bits = 1)
Usable Host Addresses: Range between network and broadcast
Subnet Mask Examples:
Notati
Mask Meaning
on
255.255.255. First 24 bits = network; last 8 bits = hosts
/24
0 (256 addresses)
255.255.255. First 25 bits = network; last 7 bits = hosts
/25
128 (128 addresses)
255.255.254. First 23 bits = network; last 9 bits = hosts
/23
0 (512 addresses)
Subnetting Example:
Network: [Link]/24
Breaking it into two /25 subnets:
Subnet 1:
Network: [Link]
Broadcast: [Link]
Usable hosts: [Link] to [Link] (126 addresses)
Subnet 2:
Network: [Link]
Broadcast: [Link]
Usable hosts: [Link] to [Link] (126 addresses)
Advantages of Subnetting:
Network Organization: Separate departments or functions
Improved Security: Isolate sensitive networks
Reduced Broadcast Traffic: Broadcasts limited to subnet
Better Performance: Smaller collision domains
IP Address Conservation: Efficient use of address space
Process:
User types: [Link] in browser
↓
DNS Resolver (usually ISP) queries root nameserver
↓
Root nameserver responds with TLD (Top-Level Domain) server address
↓
TLD server responds with authoritative nameserver address
↓
Authoritative nameserver responds with IP address (e.g., [Link])
↓
Browser connects to IP address; website loads
DNS Record Types:
Type Purpose Example
Maps domain to IPv4
A [Link] → [Link]
address
AAA Maps domain to IPv6 [Link] →
A address 2606:2800:220:1:248:1893:25c8:1946
CNA Alias (canonical
[Link] → [Link]
ME name)
Mail exchange
MX Points to mail server
(email server)
NS Nameserver Points to authoritative nameserver
TXT Text records Verification, SPF, DKIM
Process:
1. DISCOVER: Client broadcasts "I need an IP address"
2. OFFER: DHCP server responds with available IP
3. REQUEST: Client requests the offered IP
4. ACK: Server confirms the assignment
Result: Device receives IP, gateway, DNS servers, and lease time
Benefits:
Simplifies network management
Prevents duplicate IP assignments
Automatic configuration of DNS servers and gateways
IP addresses recycled when devices leave network
Lease Time: IP is temporarily assigned (e.g., 24 hours). Device must renew before
expiration.
Characteristics:
Unencrypted (credentials visible)
Uses two connections: Control (port 21) and Data (port 20)
Authentication required (username/password)
Status: Legacy; replaced by SFTP for security
Example FTP Session:
Characteristics:
Encrypted communication (secure alternative to Telnet)
Uses public-key cryptography for authentication
Runs on port 22
Supports SFTP (Secure FTP) for encrypted file transfer
SSH Example:
ssh user@[Link]
Proto Encrypti
Port Use Case Status
col on
Domain name
DNS 53 No Active
resolution
67/6 IP address
DHCP No Active
8 assignment
Deprecated (use
HTTP 80 No Web browsing
HTTPS)
HTTP Yes Secure web
443 Standard
S (SSL/TLS) browsing
20/2 Legacy (use
FTP No File transfer
1 SFTP)
Secure remote
SSH 22 Yes Standard
access
25/5
SMTP Optional Email sending Active
87
POP3 110 Optional Email retrieval Active
Email retrieval
IMAP 143 Optional Active
(advanced)
Quick Reference Summary
DNS: Translates domain names to IP addresses
DHCP : Automatically assigns IP addresses and network configuration
HTTP/HTTPS: Web protocols; HTTPS is encrypted and secure
FTP : File transfer (legacy; use SFTP)
SSH: Secure remote access and encrypted file transfer
A Router connects multiple networks and forwards data packets between them using IP
addresses (Layer 3).
Functions:
Forwarding: Routes packets to correct destination network
IP Routing: Uses routing tables to determine best path
NAT: Translates private IPs to public IPs
DHCP Server: Assigns IP addresses to local devices
Firewall: Basic packet filtering (many routers include this)
Router Types:
Switch Functions:
Learning: Builds MAC address table (learns which MAC on which port)
Forwarding: Sends frames to correct port based on destination MAC
Flooding: Sends broadcast/unknown frames to all ports except incoming
Example Switch Operation:
Device A (MAC: AA:AA:AA:AA:AA:AA) on port 1
↓
Device A sends frame to Device B (MAC: BB:BB:BB:BB:BB:BB)
↓
Switch checks MAC table: BB:BB:BB:BB:BB:BB is on port 3
↓
Switch forwards frame only to port 3
↓
Device B receives frame; other devices don't see it (improves efficiency)
Internet
↓
[FIREWALL] ← Perimeter defense
↓
Router
↓
Internal Network
Hardware vs Software Firewall:
Aspect Hardware Software
Location Network perimeter Individual device
Protection Entire network Single device
Performance Impact Minimal May slow device
Management Centralized Per-device
Cost Higher Usually free
Use Case Enterprise Personal computers
References
[1] Duke University. (2025). Data: Types, Values, Variables, and Names. Retrieved from http
s://[Link]/jupyternotebooks/
[2] Corero. (2025). What is the OSI Model? The 7 Layers Explained. Retrieved from [Link]
[Link]/what-is-the-osi-model/
[3] Codecademy. (2025). TCP 3-Way Handshake: How Does it Work? Retrieved from [Link]
[Link]/resources/blog/what-is-tcp
[4] CloudMyLab. (2025). Understanding the TCP/IP 3-Way Handshake. Retrieved from http
s://[Link]/tcp-ip-3-way-handshake