Python Samples

Essential Python code examples and Hello World demonstrations

Key Facts

Category
Programming Languages
Items
3
Format Families
json, csv

Sample Overview

Essential Python code examples and Hello World demonstrations This sample set belongs to Programming Languages and can be used to test related workflows inside Elysia Tools.

💻 Python Hello World python

🟢 simple

Basic Python Hello World program and fundamental syntax examples

⏱️ 10 min 🏷️ python, programming, beginner
Prerequisites: Basic programming concepts
# Python Hello World Examples

# 1. Basic Hello World
print("Hello, World!")

# 2. Hello World with variable
message = "Hello, World!"
print(message)

# 3. Hello World with function
def say_hello():
    return "Hello, World!"

print(say_hello())

# 4. Hello World with function parameters
def greet(name):
    return f"Hello, {name}!"

print(greet("World"))
print(greet("Python"))

# 5. Hello World with class
class Greeter:
    def __init__(self, message="Hello, World!"):
        self.message = message
    
    def greet(self):
        return self.message

greeter = Greeter()
print(greeter.greet())

# 6. Hello World with user input
name = input("Enter your name: ")
print(f"Hello, {name}!")

# 7. Hello World multiple times
for i in range(5):
    print(f"Hello, World! {i + 1}")

# 8. Hello World with list
hellos = ["Hello", "Bonjour", "Hola", "Ciao", "こんにちは"]
for greeting in hellos:
    print(f"{greeting}, World!")

# 9. Hello World with dictionary
greetings = {
    "en": "Hello",
    "es": "Hola", 
    "fr": "Bonjour",
    "de": "Hallo",
    "ja": "こんにちは"
}

for lang, greeting in greetings.items():
    print(f"{greeting}, World! ({lang})")

# 10. Hello World with file I/O
with open("hello.txt", "w") as f:
    f.write("Hello, World!")

with open("hello.txt", "r") as f:
    content = f.read()
    print(f"From file: {content}")

# Basic data types examples
integer = 42
float_num = 3.14
string = "Python"
is_boolean = True
list_data = [1, 2, 3, 4, 5]
tuple_data = (1, 2, 3)
dictionary = {"name": "Python", "version": 3.9}

print(f"Integer: {integer}, Type: {type(integer)}")
print(f"Float: {float_num}, Type: {type(float_num)}")
print(f"String: {string}, Type: {type(string)}")
print(f"Boolean: {is_boolean}, Type: {type(is_boolean)}")
print(f"List: {list_data}, Type: {type(list_data)}")
print(f"Tuple: {tuple_data}, Type: {type(tuple_data)}")
print(f"Dictionary: {dictionary}, Type: {type(dictionary)}")

# Control flow examples
age = 18
if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

# Loop examples
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

# While loop example
count = 0
while count < 3:
    print(f"Count: {count}")
    count += 1

# List comprehensions
squares = [x**2 for x in range(10)]
print(f"Squares: {squares}")

# Exception handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("This always runs")

💻 Python Data Structures python

🟡 intermediate ⭐⭐⭐

Comprehensive examples of Python data structures and their operations

⏱️ 20 min 🏷️ python, data structures, programming
Prerequisites: Basic Python syntax
# Python Data Structures Examples

# 1. Lists (Mutable sequences)
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = list(range(1, 6))  # [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# List operations
fruits.append("orange")           # Add to end
fruits.insert(1, "grape")        # Insert at index
fruits.remove("banana")          # Remove first occurrence
popped = fruits.pop()            # Remove and return last item
fruits[0] = "kiwi"               # Update item

# List slicing
print(fruits[1:3])      # Items from index 1 to 2
print(fruits[:2])       # Items from start to index 1
print(fruits[2:])       # Items from index 2 to end

# List comprehensions
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]

# 2. Tuples (Immutable sequences)
# Creating tuples
coordinates = (10, 20)
single_item = (42,)      # Note the comma
empty_tuple = ()

# Tuple operations
x, y = coordinates      # Unpacking
print(f"X: {x}, Y: {y}")

# Named tuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(10, 20)
print(f"Point: ({p1.x}, {p1.y})")

# 3. Dictionaries (Key-value pairs)
# Creating dictionaries
student = {
    "name": "Alice",
    "age": 20,
    "grades": [85, 90, 78]
}

# Dictionary operations
student["major"] = "Computer Science"    # Add key-value pair
age = student.get("age", 0)              # Get with default
del student["grades"]                    # Delete key-value pair

# Dictionary methods
keys = student.keys()
values = student.values()
items = student.items()

# Dictionary comprehensions
squares_dict = {x: x**2 for x in range(6)}
print(f"Squares dictionary: {squares_dict}")

# 4. Sets (Unique elements)
# Creating sets
unique_numbers = {1, 2, 3, 2, 1}  # {1, 2, 3}
from_set = set([1, 2, 3, 2, 1])

# Set operations
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

print(f"Union: {set_a | set_b}")           # {1, 2, 3, 4, 5, 6}
print(f"Intersection: {set_a & set_b}")    # {3, 4}
print(f"Difference: {set_a - set_b}")      # {1, 2}
print(f"Symmetric difference: {set_a ^ set_b}")  # {1, 2, 5, 6}

# 5. Strings (Immutable sequences)
text = "Hello, Python!"
print(f"Length: {len(text)}")
print(f"Upper: {text.upper()}")
print(f"Lower: {text.lower()}")
print(f"Replace: {text.replace('Python', 'World')}")

# String methods
words = text.split(", ")
print(f"Words: {words}")
joined = "-".join(words)
print(f"Joined: {joined}")

# 6. Stack and Queue using lists
# Stack (LIFO)
stack = []
stack.append(1)    # push
stack.append(2)
stack.append(3)
top_item = stack.pop()  # pop

# Queue (FIFO) - using collections.deque
from collections import deque
queue = deque()
queue.append(1)    # enqueue
queue.append(2)
queue.append(3)
front_item = queue.popleft()  # dequeue

# 7. Nested data structures
# List of dictionaries
students = [
    {"name": "Alice", "age": 20, "grades": [85, 90, 78]},
    {"name": "Bob", "age": 22, "grades": [92, 88, 95]},
    {"name": "Charlie", "age": 21, "grades": [78, 85, 82]}
]

# Accessing nested data
for student in students:
    avg_grade = sum(student["grades"]) / len(student["grades"])
    print(f"{student['name']}: Average grade = {avg_grade:.1f}")

# 8. Advanced list operations
# Sorting
numbers = [64, 34, 25, 12, 22, 11, 90]
numbers.sort()                    # In-place sort
sorted_numbers = sorted(numbers, reverse=True)  # New sorted list

# Sorting with custom key
students.sort(key=lambda x: x["age"])

# 9. Dictionary with complex keys
complex_dict = {
    (1, 2): "Point at (1,2)",
    "nested": {"inner": "value"},
    frozenset([1, 2, 3]): "Immutable set as key"
}

# 10. Performance comparison
import time

# List vs Set for membership testing
large_list = list(range(100000))
large_set = set(large_list)

# Test list membership
start = time.time()
result = 99999 in large_list
list_time = time.time() - start

# Test set membership
start = time.time()
result = 99999 in large_set
set_time = time.time() - start

print(f"List membership time: {list_time:.6f}s")
print(f"Set membership time: {set_time:.6f}s")

💻 Python File Handling python

🟡 intermediate ⭐⭐⭐

File I/O operations and file system manipulation in Python

⏱️ 25 min 🏷️ python, file operations, i/o
Prerequisites: Basic Python syntax
# Python File Handling Examples

import os
import json
import csv
from pathlib import Path

# 1. Basic file operations
# Write to file
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a file handling example.\n")
    file.write("Python makes file operations easy.\n")

# Read from file
with open("example.txt", "r") as file:
    content = file.read()
    print("File content:")
    print(content)

# Read line by line
with open("example.txt", "r") as file:
    print("\nReading line by line:")
    for line_num, line in enumerate(file, 1):
        print(f"Line {line_num}: {line.strip()}")

# 2. Different file modes
# Append mode
with open("example.txt", "a") as file:
    file.write("\nAppended text at the end.")

# Read and write mode (r+)
with open("example.txt", "r+") as file:
    content = file.read()
    file.seek(0)  # Go to beginning
    file.write("MODIFIED: " + content)

# 3. Working with binary files
# Write binary data
data = bytes(range(256))  # 0-255 bytes
with open("binary.bin", "wb") as file:
    file.write(data)

# Read binary data
with open("binary.bin", "rb") as file:
    binary_data = file.read()
    print(f"\nBinary data length: {len(binary_data)} bytes")

# 4. JSON file operations
data_to_save = {
    "name": "John Doe",
    "age": 30,
    "skills": ["Python", "JavaScript", "SQL"],
    "address": {
        "street": "123 Main St",
        "city": "New York"
    }
}

# Write JSON to file
with open("data.json", "w") as file:
    json.dump(data_to_save, file, indent=2)

# Read JSON from file
with open("data.json", "r") as file:
    loaded_data = json.load(file)
    print("\nLoaded JSON data:")
    print(json.dumps(loaded_data, indent=2))

# 5. CSV file operations
# Write CSV
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "Grade"])
    writer.writerow(["Alice", 20, "A"])
    writer.writerow(["Bob", 22, "B"])
    writer.writerow(["Charlie", 21, "A+"])

# Read CSV
with open("students.csv", "r") as file:
    reader = csv.reader(file)
    print("\nCSV content:")
    for row in reader:
        print(row)

# 6. Using pathlib for file operations
from pathlib import Path

# Create a directory structure
data_dir = Path("data")
data_dir.mkdir(exist_ok=True)

# Create and write to file using pathlib
sample_file = data_dir / "sample.txt"
sample_file.write_text("Hello from pathlib!")

# Read file using pathlib
content = sample_file.read_text()
print(f"\nPathlib content: {content}")

# File operations with pathlib
if sample_file.exists():
    print(f"File size: {sample_file.stat().st_size} bytes")
    print(f"File path: {sample_file.absolute()}")

# 7. Context manager for custom file operations
class FileManager:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None
    
    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

# Using custom context manager
with FileManager("custom.txt", "w") as file:
    file.write("Custom context manager example!")

# 8. Working with temporary files
import tempfile

# Create temporary file
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
    temp_file.write("This is temporary data")
    temp_path = temp_file.name

print(f"\nTemporary file created at: {temp_path}")

# Read temporary file
with open(temp_path, 'r') as file:
    print(f"Temp file content: {file.read()}")

# Clean up (delete=False means we need to delete manually)
os.unlink(temp_path)

# 9. File system operations
# Get current working directory
current_dir = os.getcwd()
print(f"\nCurrent directory: {current_dir}")

# List files in directory
print("Files in current directory:")
for item in os.listdir("."):
    if os.path.isfile(item):
        print(f"  File: {item}")
    elif os.path.isdir(item):
        print(f"  Directory: {item}/")

# Create directory
new_dir = "test_directory"
if not os.path.exists(new_dir):
    os.makedirs(new_dir)
    print(f"Created directory: {new_dir}")

# Remove directory
os.rmdir(new_dir)
print(f"Removed directory: {new_dir}")

# 10. Error handling in file operations
try:
    with open("nonexistent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("\nFile not found error handled gracefully")

try:
    with open("/protected/file.txt", "w") as file:
        file.write("test")
except PermissionError:
    print("Permission error handled gracefully")

# Clean up created files
files_to_remove = ["example.txt", "binary.bin", "data.json", "students.csv", "custom.txt", "sample.txt"]
for file_path in files_to_remove:
    try:
        os.remove(file_path)
    except FileNotFoundError:
        pass

# Remove data directory
try:
    import shutil
    shutil.rmtree("data")
except FileNotFoundError:
    pass

print("\nFile handling examples completed!")