Python Fundamentals: Basic, Intermediate, and Advanced Code Examples
This article presents a comprehensive collection of Python code snippets ranging from basic constructs like list comprehensions and file handling to intermediate topics such as threading and HTTP requests, and advanced examples including classes, generators, and concurrent programming techniques.
Basic Cases demonstrate fundamental Python techniques: a list comprehension to generate the FizzBuzz sequence, reading CSV files with the csv module, extracting words using regular expressions, counting character occurrences, deduplicating lists with set, string formatting with format(), a caching decorator to memoize function results, complete exception handling with try‑except‑else‑finally, assertions for input validation, and path manipulation using os.path.
fizz_buzz_list = [ "FizzBuzz" if i % 15 == 0 else "Fizz" if i % 3 == 0 else "Buzz" if i % 5 == 0 else i for i in range(1, 101) ]
print(fizz_buzz_list)
import csv
with open('data.csv', mode='r') as file:
csvFile = csv.reader(file)
for row in csvFile:
print(row)
import re
pattern = r'\b[A-Za-z][A-Za-z0-9_]*\b'
text = "Hello, this is a test string with username: JohnDoe"
matches = re.findall(pattern, text)
print(matches)
text = "Hello, World!"
char = "l"
count = text.count(char)
print(f"The character '{char}' appears {count} times.")
duplicates = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(duplicates))
print(unique_list)
name = "John"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
def cache(func):
cache_dict = {}
def wrapper(num):
if num in cache_dict:
return cache_dict[num]
else:
val = func(num)
cache_dict[num] = val
return val
return wrapper
@cache
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result is:", result)
finally:
print("Execution complete.")
def divide(a, b):
assert b != 0, "Division by zero is not allowed"
return a / b
print(divide(10, 2))
# divide(10, 0) would raise AssertionError
import os
path = "/path/to/some/file.txt"
dirname = os.path.dirname(path)
basename = os.path.basename(path)
print("Directory:", dirname)
print("Basename:", basename)Intermediate Cases cover useful utilities: accessing and setting environment variables via os.environ, generating combinations with itertools.combinations, performing date arithmetic with datetime, sorting and reversing lists, handling JSON data, using defaultdict for automatic default values, aggregating with functools.reduce, creating threads with threading, spawning processes with multiprocessing, and making HTTP GET requests using the requests library.
import os
print("PATH:", os.environ["PATH"])
os.environ["NEW_VAR"] = "NewValue"
print("NEW_VAR:", os.environ["NEW_VAR"])
import itertools
for combination in itertools.combinations([1, 2, 3], 2):
print(combination)
from datetime import datetime, timedelta
now = datetime.utcnow()
one_day = timedelta(days=1)
yesterday = now - one_day
print("Yesterday's date:", yesterday)
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print("Sorted:", numbers)
numbers.reverse()
print("Reversed:", numbers)
import json
data = {"name": "John", "age": 30}
json_data = json.dumps(data)
print(json_data)
parsed_data = json.loads(json_data)
print(parsed_data)
from collections import defaultdict
dd = defaultdict(int)
dd["apple"] = 1
dd["banana"] = 2
print(dd["apple"]) # 1
print(dd["orange"]) # 0 (default)
from functools import reduce
from operator import add
numbers = [1, 2, 3, 4]
total = reduce(add, numbers)
print(total) # 10
import threading
def print_numbers():
for i in range(10):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
from multiprocessing import Process, cpu_count
def print_hello():
print("Hello from child process")
if __name__ == '__main__':
processes = []
for _ in range(cpu_count()):
p = Process(target=print_hello)
p.start()
processes.append(p)
for p in processes:
p.join()
import requests
response = requests.get("https://www.example.com")
print(response.status_code)
print(response.text)Advanced Cases illustrate more complex constructs: converting space‑separated strings to integer lists with map, using conditional statements, iterating over lists, while loops, enumerating with index, list slicing, f‑string formatting, handling exceptions, defining classes with methods, performing set union, creating and manipulating dictionaries, writing generator functions, parallel iteration with zip, and reading/writing files using context managers.
string_numbers = "1 2 3 4 5"
numbers = list(map(int, string_numbers.split()))
print(numbers)
x = 7
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
count = 0
while count < 5:
print(count)
count += 1
for index, value in enumerate(["apple", "banana", "cherry"]):
print(index, value)
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
print(fruits[1:4])
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
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("John", 30)
person.greet()
fruits_set = {"apple", "banana", "cherry"}
veggies_set = {"carrot", "broccoli", "banana"}
print(fruits_set | veggies_set)
person_dict = {"name": "John", "age": 30, "city": "New York"}
print(person_dict)
print(person_dict["name"])
del person_dict["age"]
print(person_dict)
def countdown(n):
while n > 0:
yield n
n -= 1
for i in countdown(5):
print(i)
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(name, age)
with open('output.txt', 'w') as file:
file.write("Hello, World!")
with open('output.txt', 'r') as file:
content = file.read()
print(content)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
