Fundamentals 22 min read

Comprehensive Python Basics: Syntax, Data Structures, File I/O, Functions, OOP, Exceptions, Math, Regex, File System, and Network Requests

This tutorial presents a comprehensive collection of Python programming fundamentals, covering basic syntax, data structures, file operations, functions, object‑oriented concepts, exception handling, mathematical computations, regular expressions, file system manipulation, and network requests, each illustrated with clear code examples.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Comprehensive Python Basics: Syntax, Data Structures, File I/O, Functions, OOP, Exceptions, Math, Regex, File System, and Network Requests

Basic Syntax

Printing, variable assignment, arithmetic, conditionals, loops, and simple data processing examples.

print("Hello, World!")
message = "Hello, Python!"
print(message)
a = 5
b = 3
sum = a + b
print(sum)
num = 10
if num > 0:
    print("Positive")
else:
    print("Not Positive")
for i in range(1, 11):
    print(i)
i = 1
while i <= 10:
    print(i)
    i += 1
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)
def is_palindrome(s):
    return s == s[::-1]
s = "madam"
print(is_palindrome(s))
s = "hello, world!"
print(s.upper())
s = "hello, world!"
if "world" in s:
    print("Substring found")
else:
    print("Substring not found")

Data Structures

Lists, dictionaries, loops, sorting, and set operations.

my_list = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
print(my_list)
my_dict = {}
my_dict['name'] = 'Alice'
my_dict['age'] = 30
print(my_dict)
my_list = [1, 2, 3, 4, 5]
for item in my_list:
    print(item)
my_dict = {'name': 'Alice', 'age': 30}
for key, value in my_dict.items():
    print(f"{key}: {value}")
my_list = [3, 1, 4, 1, 5, 9]
my_list.sort()
print(my_list)
my_list = [3, 1, 4, 1, 5, 9]
print(max(my_list))
print(min(my_list))
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)
my_set = set()
my_set.add(1)
my_set.add(2)
my_set.add(3)
print(my_set)
my_tuple = (1, 2, 3)
print(my_tuple[0])
print(my_tuple[1])
print(my_tuple[2])

File Operations

Reading, writing, appending, line‑by‑line processing, copying, counting words, and replacing text.

with open('file.txt', 'r') as file:
    content = file.read()
    print(content)
with open('file.txt', 'w') as file:
    file.write('Hello, World!')
with open('file.txt', 'a') as file:
    file.write('
Appending new line.')
with open('file.txt', 'r') as file:
    for line in file:
        print(line.strip())
with open('source.txt', 'r') as source_file:
    with open('destination.txt', 'w') as dest_file:
        dest_file.write(source_file.read())
with open('file.txt', 'r') as file:
    content = file.read()
    words = content.split()
    print(len(words))
with open('file.txt', 'r') as file:
    content = file.read()
new_content = content.replace('old_word', 'new_word')
with open('file.txt', 'w') as file:
    file.write(new_content)
import csv
with open('data.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)
import csv
with open('data.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['Alice', 30])
    writer.writerow(['Bob', 25])
import json
with open('data.json', 'r') as f:
    data = json.load(f)
    print(data)

Functions and Modules

Defining functions, default arguments, *args, **kwargs, and importing modules.

def greet(name):
    print(f"Hello, {name}!")
greet("Alice")
def add(a, b):
    return a + b
result = add(3, 5)
print(result)
def greet(name="World"):
    print(f"Hello, {name}!")
greet()
greet("Alice")
def sum_all(*args):
    return sum(args)
result = sum_all(1, 2, 3, 4, 5)
print(result)
def display_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")
display_info(name="Alice", age=30)
import math
result = math.sqrt(16)
print(result)
# mymodule.py

def hello():
    print("Hello from mymodule!")

import mymodule
mymodule.hello()
from math import sqrt
result = sqrt(16)
print(result)
import sys
for arg in sys.argv:
    print(arg)
import os
current_dir = os.getcwd()
print(current_dir)

Object‑Oriented Programming

Classes, inheritance, class/instance/static methods, properties, and special methods.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")
person = Person("Alice", 30)
person.greet()
class Animal:
    def speak(self):
        pass
class Dog(Animal):
    def speak(self):
        print("Woof!")
class Cat(Animal):
    def speak(self):
        print("Meow!")
dog = Dog()
cat = Cat()
dog.speak()
cat.speak()
class Circle:
    pi = 3.14159
    def __init__(self, radius):
        self.radius = radius
    def area(self):
        return Circle.pi * (self.radius ** 2)
circle = Circle(5)
print(circle.area())
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height
    def area(self):
        return self.width * self.height
rectangle = Rectangle(5, 10)
print(rectangle.area())
class MathUtils:
    @staticmethod
    def add(a, b):
        return a + b
result = MathUtils.add(3, 5)
print(result)
class Person:
    count = 0
    def __init__(self, name):
        self.name = name
        Person.count += 1
    @classmethod
    def get_count(cls):
        return cls.count
person1 = Person("Alice")
person2 = Person("Bob")
print(Person.get_count())
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance
    def deposit(self, amount):
        self.__balance += amount
    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
        else:
            print("Insufficient funds")
    def get_balance(self):
        return self.__balance
account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance())
class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius
    @property
    def fahrenheit(self):
        return (self.celsius * 9/5) + 32
temp = Temperature(25)
print(temp.fahrenheit)
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius
    @property
    def celsius(self):
        return self._celsius
    @celsius.setter
    def celsius(self, value):
        self._celsius = value
    @property
    def fahrenheit(self):
        return (self._celsius * 9/5) + 32
temp = Temperature(25)
print(temp.fahrenheit)
temp.celsius = 30
print(temp.fahrenheit)
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __str__(self):
        return f"Point({self.x}, {self.y})"
    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"
point = Point(3, 4)
print(point)
print(repr(point))

Exception Handling

Try/except blocks, multiple exceptions, finally, and raising errors.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
try:
    result = 10 / 0
except (ZeroDivisionError, TypeError):
    print("An error occurred")
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("This will always execute")
def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b
try:
    result = divide(10, 0)
except ValueError as e:
    print(e)

Mathematical and Scientific Computing

Square roots, powers, circle area, factorial, and combinations.

import math
result = math.sqrt(16)
print(result)
result = pow(2, 3)
print(result)
import math
def circle_area(radius):
    return math.pi * (radius ** 2)
area = circle_area(5)
print(area)
import math
result = math.factorial(5)
print(result)
import math
result = math.comb(5, 2)
print(result)

String Operations

Concatenation, formatting, splitting, joining, replacing, searching, case conversion, trimming, slicing, and length.

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)
name = "Alice"
age = 30
message = f"Name: {name}, Age: {age}"
print(message)
text = "apple,banana,orange"
fruits = text.split(',')
print(fruits)
fruits = ['apple', 'banana', 'orange']
text = ','.join(fruits)
print(text)
text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text)
text = "Hello, World!"
index = text.find("World")
print(index)
text = "Hello, World!"
upper_text = text.upper()
lower_text = text.lower()
print(upper_text)
print(lower_text)
text = "   Hello, World!   "
trimmed_text = text.strip()
print(trimmed_text)
text = "Hello, World!"
substring = text[7:12]
print(substring)
text = "Hello, World!"
length = len(text)
print(length)

Regular Expressions

Email, phone, date matching, substitution, and pattern checking.

import re
text = "Contact us at [email protected] or [email protected]"
emails = re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)
print(emails)
import re
text = "Call us at 123-456-7890 or 987-654-3210"
phone_numbers = re.findall(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', text)
print(phone_numbers)
import re
text = "Meeting on 2023-10-05 and 2023-10-10"
dates = re.findall(r'\b\d{4}-\d{2}-\d{2}\b', text)
print(dates)
import re
text = "The quick brown fox jumps over the lazy dog"
new_text = re.sub(r'fox', 'cat', text)
print(new_text)
import re
text = "123-456-7890"
pattern = r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'
if re.match(pattern, text):
    print("Match found")
else:
    print("No match")

File and Directory Operations

Creating, deleting, listing, copying, moving, renaming, checking existence, size, modification time, recursive traversal, searching, compression, and extraction.

import os
os.makedirs('new_directory', exist_ok=True)
import shutil
shutil.rmtree('directory_to_delete')
import os
for item in os.listdir('path/to/directory'):
    print(item)
import shutil
shutil.copy('source_file.txt', 'destination_file.txt')
import shutil
shutil.move('source_file.txt', 'destination_directory/')
import os
os.rename('old_name.txt', 'new_name.txt')
import os
if os.path.exists('file.txt'):
    print('File exists.')
import os
file_size = os.path.getsize('file.txt')
print(f'File size: {file_size} bytes')
import os
mod_time = os.path.getmtime('file.txt')
print(f'Modified time: {mod_time}')
import os
for root, dirs, files in os.walk('path/to/directory'):
    for name in files:
        print(os.path.join(root, name))
import os
for root, dirs, files in os.walk('path/to/directory'):
    if 'target_file.txt' in files:
        print(os.path.join(root, 'target_file.txt'))
import zipfile
with zipfile.ZipFile('archive.zip', 'w') as zipf:
    zipf.write('file.txt')
import zipfile
with zipfile.ZipFile('archive.zip', 'r') as zipf:
    zipf.extractall('extracted_directory')
import csv
with open('data.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)
import csv
with open('data.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['Alice', 30])
    writer.writerow(['Bob', 25])

Network Requests

GET, POST, custom headers, file download/upload, JSON and XML handling, timeout, error handling, and sessions.

import requests
response = requests.get('https://api.example.com/data')
print(response.text)
import requests
payload = {'key': 'value'}
response = requests.post('https://api.example.com/submit', data=payload)
print(response.text)
import requests
headers = {'Content-Type': 'application/json'}
response = requests.get('https://api.example.com/data', headers=headers)
print(response.text)
import requests
url = 'https://example.com/file.zip'
response = requests.get(url)
with open('downloaded_file.zip', 'wb') as f:
    f.write(response.content)
import requests
files = {'file': open('file.txt', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)
print(response.text)
import requests
response = requests.get('https://api.example.com/data')
data = response.json()
print(data)
import requests
import xml.etree.ElementTree as ET
response = requests.get('https://api.example.com/data.xml')
root = ET.fromstring(response.text)
for child in root:
    print(child.tag, child.attrib)
import requests
response = requests.get('https://api.example.com/data', timeout=5)
print(response.text)
import requests
try:
    response = requests.get('https://api.example.com/data')
    response.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print("Http Error:", errh)
except requests.exceptions.ConnectionError as errc:
    print("Error Connecting:", errc)
except requests.exceptions.Timeout as errt:
    print("Timeout Error:", errt)
except requests.exceptions.RequestException as err:
    print("OOps: Something Else", err)
import requests
session = requests.Session()
session.auth = ('username', 'password')
response = session.get('https://api.example.com/data')
print(response.text)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingcode-examples
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.