Monday, 15 September 2025

10 Python One-Liners That Will Blow Your Mind

Python is famous for its readability, but sometimes the most mind-blowing thing is how much you can do in just one line of code. Here are 10 Python one-liners that will amaze you.

1. Reverse a string

print("hello world"[::-1])

2. Swap two variables without a temp variable

a, b = 5, 10; a, b = b, a

3. Check if a string is a palindrome

print(s == s[::-1])

4. Find the factorial of a number

import math; print(math.factorial(5))

5. Get unique elements from a list

print(list(set([1,2,2,3,4,4,5])))

6. Flatten a list of lists

print([x for row in [[1,2],[3,4],[5]] for x in row])

7. Generate a Fibonacci sequence (first 10 numbers)

fib = lambda n: n if n<2 else fib(n-1)+fib(n-2); print([fib(i) for i in range(10)])

8. Transpose a matrix

print(list(zip(*[[1,2,3],[4,5,6],[7,8,9]])))

9. Find the most frequent element in a list

print(max(set([1,2,2,3,3,3,4]), key=[1,2,2,3,3,3,4].count))

10. One-line list comprehension for squares

print([x**2 for x in range(10)])

Sunday, 14 September 2025

10 Apps You’re Using Wrong

Most of us rely on apps every single day—for work, communication, and entertainment. But here’s the thing: chances are, you’re not using them to their full potential. In fact, you might be using them wrong. The good news? A few small tweaks can make your favorite apps way more powerful.

Here are 10 apps you’re probably misusing—and exactly how to fix it.

1. Google Maps

The mistake: Only using it for directions.
The fix: Explore hidden features like offline maps (perfect for no-signal areas), location sharing for safety, and live traffic overlays to avoid unexpected jams.

2. WhatsApp

The mistake: Using it only for chats.
The fix: Use WhatsApp Web for faster typing, broadcast lists for updates, and disappearing messages for privacy. You can even star important messages to find them later.

3. Spotify

The mistake: Only playing playlists made by others.
The fix: Explore “Daily Mix” and “Discover Weekly” to uncover new music. Use the “Enhance” button on your playlists to automatically add songs that match your vibe.

4. Instagram

The mistake: Treating it like just a photo-sharing app.
The fix: Use Stories for engagement, Notes for quick updates, and Collections to save posts in organized folders (like recipes, travel ideas, or shopping lists).

5. Gmail

The mistake: Letting your inbox become chaos.
The fix: Use labels, filters, and “snooze” to keep things tidy. Also, schedule emails to send later—handy if you’re up late but don’t want to look unprofessional.

6. YouTube

The mistake: Only watching videos.
The fix: Use playlists to learn systematically, download videos for offline viewing, and check out “Chapters” in long videos to skip right to the section you need.

7. Dropbox / Google Drive

The mistake: Treating them like simple storage boxes.
The fix: Use version history to restore old files, offline sync for when you don’t have Wi-Fi, and shared folders for real-time collaboration.

8. Zoom

The mistake: Only joining meetings passively.
The fix: Explore features like breakout rooms for group discussions, virtual backgrounds for professionalism, and keyboard shortcuts to mute/unmute instantly.

9. Notes (Apple Notes / Google Keep)

The mistake: Just jotting down quick reminders.
The fix: Turn notes into checklists, scan documents directly inside the app, and use tags to keep everything searchable.

10. TikTok

The mistake: Just scrolling endlessly.
The fix: Use the search function like Google—many creators share quick tutorials, life hacks, and reviews. You can also create private “Collections” to save useful videos.

Final Thoughts

You don’t need to download more apps—you just need to use the ones you already have smarter. With a few small changes, your daily tools can become productivity boosters, learning hubs, and even money-savers.

So, which of these app tips are you going to try first?

10 Everyday Items You’re Using Wrong (And How to Fix It)

We all rely on everyday items to make life easier, but many of us are using them incorrectly without even realizing it. Here are 10 common things you’re probably misusing—and the simple fixes that can make a big difference.


1. Toothpaste
Most people squeeze from the middle of the tube, wasting product. Instead, roll from the bottom to use every bit and avoid messy clumps.
 

2. Aluminum Foil Box
Ever had the roll slide out when you pull? The side flaps on the box are there to lock the roll in place. Push them in and the roll won’t budge.
 

3. Bobby Pins
If you wear them with the wavy side up, you’re doing it wrong. The wavy side should face down to grip the hair properly.
 

4. Tic Tac Containers
You don’t need to shake half the box into your hand. The lid has a small groove designed to dispense a single Tic Tac at a time.
 

5. Plastic Lids on Coffee Cups
That little lid is more than a cover—it doubles as a coaster for your drink. Just flip it upside down and set your cup on it.
 

6. Key Rings
Instead of prying the ring open with your fingernail, use a staple remover. Slide the teeth in to separate the rings easily.
 

7. Microwave Heating
Placing food in the middle creates cold spots. Push your plate to the edge of the microwave turntable for even heating.
 

8. Headphone Wires
Coiling them tightly around your phone or hand weakens the wires. Use a loose figure-eight wrap to keep them tangle-free and long-lasting.
 

9. Backpack Straps
Wearing your backpack with loose straps strains your back. Tighten both straps evenly and keep the load close to your body for better support.

10. Toothbrush Storage
Leaving your toothbrush lying flat lets bacteria grow. Store it upright in an open cup so it can air dry properly.


 

Monday, 8 September 2025

10 iPhone Camera Hacks That Make Your Photos Look Professional

The iPhone camera is better than many people realize. With a few toggles, touches, and simple habits, you can capture images that look like they were shot on a mirrorless camera. Here are ten field-tested hacks you can apply today.

1) Turn On Grid & Level for Perfect Composition

Composition is half the battle. Enable the grid and level to quickly align horizons and use the rule of thirds.

How: SettingsCamera → toggle Grid and Level.
Why it works: It prevents tilted horizons and helps place your subject where the eye expects it.

Pro Tip: Place eyes on the upper-third line for portraits; keep horizons on a third, not centered.

2) Use AE/AF Lock + Exposure Slider

Tap to focus, then press-and-hold until you see “AE/AF Lock.” Slide your finger up/down to adjust exposure.

  • Lock focus on your subject to avoid focus hunting.
  • Drag down to keep bright skies from blowing out.
  • Recompose while the focus/exposure stay locked.

3) Shoot ProRAW (or RAW) When Detail Matters

RAW keeps more data for editing—amazing for landscapes, sunsets, and tricky light.

How (supported models): SettingsCameraFormats → enable Apple ProRAW (choose 12/24/48MP).
When to use: High-contrast scenes, print work, or when you plan to edit in Photos/Lightroom/Darkroom.

Note: RAW files are larger. For quick shares, shoot HEIF/JPEG; for hero shots, switch to RAW.

4) Use 48MP & 2× Lossless (Supported Models)

On newer iPhones, tap the RAW or 24/48 MP option and try the (sensor-crop) zoom for crisp detail without digital mush.

  • Great for daylight portraits and textures.
  • Gives you extra room to crop when editing.

5) Leverage Smart HDR for Balanced Highlights

Smart HDR blends multiple exposures so skies keep detail while shadows stay clean.

How: Leave Smart HDR on (defaults on modern iPhones). If you prefer more control, shoot RAW and edit highlights.

Tip: Point at the brightest area → drag exposure slightly down → shoot. You’ll get punchier clouds and richer color.

6) Master Night Mode with a Stable Base

Night mode automatically sets a multi-second exposure. Stability is everything.

How: When the moon icon appears, tap it to choose the exposure duration. Brace your phone or use a mini tripod.
Pro move: Set phone on a wall/bench → timer 3s/10s → longer Night mode → razor-sharp low-light shots.

7) Portrait Mode + Depth & Lighting Control

Portrait mode simulates lens bokeh and studio lights. After shooting, adjust the blur and lighting effect.

  • Step back a little; keep good light on the face.
  • Edit → Depth to soften or reduce background blur.
  • Try Studio Light for clean skin tones; Contour for drama.

8) Live Photos → Long Exposure Trick

Live Photos capture a short video. Convert it to a long exposure for silky waterfalls or light trails.

How: Shoot with Live on → open photo → tap Live (top-left) → choose Long Exposure.

Works best: At dusk/night with moving water, traffic, or handheld sparklers.

9) Burst Mode & Timer for Action & Groups

Capture the perfect moment without missing it.

  • Burst: Hold the shutter or drag it left (in Photo mode) to shoot a rapid series. Pick the sharpest later.
  • Timer: Use 3s/10s to reduce camera shake and get everyone in the frame.

10) Use Physical/Remote Shutters to Kill Shake

Avoid blur by not tapping the screen at all.

How: Press the phone’s volume button to shoot. EarPods/Headphones volume buttons work as a remote, too.
Apple Watch: Use the Camera Remote app to see a preview and trigger the shutter from your wrist.

Quick Editing Recipe (in Photos)

  1. Straighten & Crop: Fix horizon; apply rule of thirds.
  2. Brilliance: +10 to +30 for pop without overdoing contrast.
  3. Highlights/Shadows: Pull highlights down, lift shadows slightly.
  4. Warmth & Tint: Small tweaks to correct color cast.
  5. Sharpness: +5 to +15; avoid halos.
  6. Vignette: Subtle, to draw focus.

Export tip: For social, HEIF/JPEG at native resolution looks great. For prints, export RAW edits at full size.

One-Minute Pre-Shoot Checklist

  • Lens clean? (Shirt corner or microfiber!)
  • Grid & Level on?
  • Subject lit better than background?
  • AE/AF Lock set & exposure nudged down?
  • RAW on for hero shots? (Optional)
  • Timer or remote ready to avoid shake?

How to Make Your iPhone Battery Last Long

Stop “battery anxiety” with easy settings, smart charging habits, and a few myth-busting facts. Bookmark this guide and revisit the monthly checklist at the end.

Quick Wins (5 minutes)

1) Enable Low Power Mode

Swipe down ➝ Control Center ➝ tap the battery icon. Or go: Settings → Battery → Low Power Mode. Cuts background activity and visual effects.

2) Dim & Auto-Lock

Settings → Display & Brightness: lower brightness, set Auto-Lock to 30 seconds–1 minute, disable Always-On (on supported devices) to save hours daily.

3) Tame Location & Background Refresh

Settings → Privacy & Security → Location Services: switch rarely used apps to While Using. Then Settings → General → Background App Refresh: disable for non-essential apps.

4) Silence Non-Critical Pings

Settings → Notifications: turn off unneeded notifications & Live Activities. Every wake costs energy.

Settings to Tweak (and why they work)

SettingPathWhat to ChooseWhy It Helps
Battery Insights Settings → Battery Check Battery Usage by App Find energy-hungry apps; adjust their permissions or usage.
Mail Fetch Settings → Mail → Accounts → Fetch New Data Use Push for main account, Manual/Hourly for others Reduces constant network wake-ups.
Location Settings → Privacy & Security → Location Services Prefer While Using, disable Precise where not needed GPS & radios are battery-intensive; precision costs more.
Background App Refresh Settings → General → Background App Refresh Off for games/social/shopping you don’t need updated Stops silent network/CPU work when you’re not using the app.
Display Settings → Display & Brightness Lower brightness; disable Always-On (if available); shorter Auto-Lock Screen is the #1 daily drain; less on-time = more battery.
Haptics & System Sounds Settings → Sounds & Haptics Reduce haptics for keyboard/system Vibration motor uses more power than a simple “click”.
Widgets & Live Activities Home/Lock Screen customization Keep only essential, remove live-updating tiles Frequent refreshes wake CPU and network.
Siri & Search Settings → Siri & Search Disable “Hey Siri” if you rarely use it Always-listening voice detection costs idle power.
App Permissions Settings → [App] Block background cellular data for non-essentials Prevents stealthy syncs when on mobile data.
Pro Tip

Keep iOS and apps up-to-date. Updates often fix runaway background tasks and improve power management.

Travel & Low-Signal Tips

  • Weak signal = hungry radios. If coverage is poor and you just need offline access, turn on Airplane Mode and enable Wi-Fi as needed.
  • Use Low Data Mode in Settings → Cellular → Cellular Data Options to reduce background syncing on trips.
  • Download maps/music for offline use before you go.

Diagnose Fast Drain (Step-by-Step)

  1. Open Battery (Settings → Battery) and view the last 24 hours. Identify top draining apps.
  2. Adjust offenders:
    • Set Location to While Using, disable Precise if not needed.
    • Disable Background App Refresh for that app.
    • Reduce notifications or turn off Live Activities.
  3. Check storage: Settings → General → iPhone Storage. Low free space can cause extra background work.
  4. Restart the device; stuck processes clear and radios reset.
  5. Reset settings (last resort): Settings → General → Transfer or Reset iPhone → Reset → Reset All Settings. This doesn’t delete data but resets preferences.

Myths vs Facts

Myth: “You must always go 0% → 100%.”

Fact: Frequent partial charges are healthier for lithium-ion than deep cycles.

Myth: “Force-quitting apps saves battery.”

Fact: iOS suspends apps efficiently; relaunching repeatedly can use more power.

Myth: “Only dark mode matters.”

Fact: Brightness and screen on-time dominate. Dark mode helps, but less than simply dimming.

Myth: “Wireless charging is always bad.”

Fact: Heat is the issue. Cool, quality wireless chargers are fine; avoid hot surfaces.

Monthly Maintenance Checklist

  • Review Battery → Usage by App; tame any new power hogs.
  • Purge or offload apps you don’t use.
  • Update iOS and apps.
  • Scan notifications and disable noisy ones.
  • Clean charging ports and cables; replace frayed cables.
  • Skim Privacy → Location Services for apps that don’t need Always-on.

Tip: Add this checklist as a monthly reminder.

Sunday, 7 September 2025

The Littke Known Settings on Your iPhone (That Actually Make Life Easier)

Unlock power features you already own: faster actions, calmer notifications, stronger privacy, and “why didn’t I know this?” automations.

1) Back Tap = Secret Double-Tap Shortcuts

Settings → Accessibility → Touch → Back Tap

Assign actions to double- or triple-tap the back of your iPhone. Great for screenshotting, launching the camera, toggling the flashlight, or running a Shortcut.

Ideas

  • Double-tap → Screenshot
  • Triple-tap → Open Camera or Toggle Flashlight
  • Run a Shortcut: log water intake, append a note, start a timer
Pro tip: Pair Back Tap with a Shortcut that toggles Low Power Mode for instant battery savings.

2) Focus That Changes with Time/Place

Settings → Focus → Work/Driving/Sleep/Custom → Add Schedule

Focus lets you filter notifications and Home Screens. The gold is in automation: trigger a Focus by time, location, or app use.

  • Create a “Deep Work” Focus.
  • Allow only critical people/apps.
  • Add a schedule for weekdays 9–12, or “when I arrive at the office”.
  • Set a custom Home Screen that hides distracting apps during that Focus.
Bonus: Link a Focus to a Lock Screen style (e.g., minimal widgets) for a distraction-free vibe.

3) Sound Recognition & Background Sounds

Settings → Accessibility → Sound Recognition

Your iPhone can listen for specific sounds (doorbell, smoke alarm, baby crying) and notify you.

Settings → Accessibility → Audio/Visual → Background Sounds

Play gentle ambient audio (rain, ocean, stream) under music or alone to improve focus or sleep.

Note: Sound Recognition may reduce Siri “Hey Siri” performance and can affect battery life.

4) Make Haptic Touch Faster

Settings → Accessibility → Touch → Haptic Touch

Set the “Touch Duration” to Fast for snappier menus and link previews.

5) Keyboard Power Moves & Text Replacements

Settings → General → Keyboard → Text Replacement
  • Create snippets like ;em → your email, ;addr → your mailing address.
  • Enable One-Handed Keyboard (press and hold globe/emoji icon).
  • Trackpad mode: press and hold the space bar, then move the cursor with your thumb.

6) Privacy That Actually Matters: Location & Wi-Fi

Per-App “Precise Location”

Settings → Privacy & Security → Location Services → App → Precise Location

Turn off Precise for apps that don’t need your exact spot (e.g., weather can use approximate).

System Services (the “hidden” list)

Settings → Privacy & Security → Location Services → System Services
  • Significant Locations: clear or disable if you prefer not to save a travel log.
  • Product Improvement toggles: opt out if you want fewer background pings.

Private Wi-Fi Address

Settings → Wi-Fi → (ⓘ for your network) → Private Wi-Fi Address

Helps reduce tracking across networks. If a network blocks you, toggle off temporarily, then back on.

iCloud+ Privacy

Settings → [Your Name] → iCloud → iCloud Private Relay / Hide My Email

Private Relay obscures IP/addressing in Safari. Hide My Email creates burner addresses that forward to your inbox.

7) Safety Check & Emergency SOS

Settings → Privacy & Security → Safety Check

Quickly audit and revoke access you’ve shared (location, photos, notes) with people or apps.

Settings → Emergency SOS
  • Enable “Call with Hold and Release” or “Call with 5 Button Presses”.
  • Add emergency contacts in Health → Medical ID.
Heads-up: Test features carefully—triggering SOS will call local emergency services.

8) Lockdown Mode (for High-Risk Users)

Settings → Privacy & Security → Lockdown Mode

Extremely limits attack surface by restricting attachments, web tech, and invitations. Turn on only if you believe you’re at specific risk.

9) Battery Health, Optimized Charging & Clean Energy

Settings → Battery → Battery Health & Charging
  • Optimized Battery Charging learns your routine to reduce aging.
  • Clean Energy Charging (region-dependent) favors times when the grid is cleaner.
  • Check Battery Usage by App to spot silent drainers.
Quick win: Add a Low Power Mode toggle to Control Center: Settings → Control Center → + Low Power Mode.

10) Auto-Answer, Silence Unknown Callers & Announce Notifications

Auto-Answer Calls

Settings → Accessibility → Touch → Call Audio Routing → Auto-Answer Calls

Great for gloves, workouts, or if you often miss calls on the move.

Silence Unknown Callers

Settings → Phone → Silence Unknown Callers

Unknown numbers go to voicemail; you still see them in Recents.

Announce Notifications

Settings → Siri & Search → Announce Notifications

Hear important messages via AirPods/CarPlay without looking at your screen.

11) Shortcuts: NFC, Menus & Personal Automations

Shortcuts app → Automations → New Automation
  • NFC tag: tap your phone to a sticker to start a routine (log gym set, open a playlist, run a Home scene).
  • Time of day: auto-enable a Focus, send a message, or speak a reminder.
  • App opens: when Camera opens, set brightness to 100% and enable Do Not Disturb for 10 minutes.
Pro tip: Create a “Share Sheet” shortcut to instantly resize images or create a PDF from photos.

12) AirDrop, NameDrop & “Share via Camera”

Settings → General → AirDrop
  • NameDrop: Quickly share contact posters by bringing iPhones together (toggle in AirDrop settings).
  • Receiving: Set to Contacts Only by default; switch to Everyone for 10 Minutes when needed.
  • Share via Camera: Scan a QR code to add contacts or join Wi-Fi quickly.

Quick Reference Table

Setting Path What It Does Best For
Back Tap Accessibility → Touch → Back Tap Double/triple-tap back to trigger actions Fast screenshots, flashlight, Shortcuts
Focus Schedules Focus → Add Schedule Time/location/app-based notification filters Work blocks, driving, sleep hygiene
Sound Recognition Accessibility → Sound Recognition Alerts for alarms, doorbells, baby crying Hearing support, home awareness
Background Sounds Accessibility → Audio/Visual Play ambient audio under other apps Focus, masking noise, sleep
Haptic Touch Speed Accessibility → Touch → Haptic Touch Quicker context menus Power users
Text Replacement General → Keyboard Expand snippets into full text Emails, addresses, canned replies
Precise Location Privacy & Security → Location Services Limit exact GPS per app Privacy without breaking features
System Services Privacy & Security → Location → System Services Control Apple/location diagnostics Battery, privacy tuning
Private Wi-Fi Address Wi-Fi → (ⓘ) Randomizes MAC to reduce tracking Public networks
Safety Check Privacy & Security Review/revoke shared access quickly Safety & privacy hygiene
Lockdown Mode Privacy & Security Extreme hardening for high-risk users Journalists, activists, targets
Battery Health & Charging Battery Optimize charge & reduce aging Longevity, greener charging
Auto-Answer / Silence Unknown Accessibility → Touch / Phone Hands-free pickup; cut spam calls Workouts, focus time, travel
Shortcuts Automations Shortcuts → Automations Run actions by NFC/time/app Home, health, journaling
AirDrop & NameDrop General → AirDrop Faster sharing and contact exchange Events, meetings, classrooms

FAQ & Notes

  • Will these paths match my iOS exactly? Menu names can vary slightly between iOS 15–18 and by region. If you can’t find an item, use the search bar at the top of Settings.
  • Will this drain battery? Features like Sound Recognition and Background Sounds use more power. Toggle when needed.
  • Can I revert? Yes—just switch off the toggle or remove an automation.
Save this post: Bookmark and revisit after updates—Apple often adds options under the same menu names.

Python 3 Unit Testing

Python 3 · Testing

Learn how to write fast, reliable tests using the built-in unittest and the popular pytest framework—plus fixtures, mocking, parameterization, coverage, and CI.

1) Why Unit Testing?

Unit tests check small, isolated pieces of code (functions/classes) to catch bugs early. They also document behavior and enable safe refactoring. With a fast test suite, you’ll ship changes with confidence.

2) A Clean Project Structure

Recommended layout

myapp/
├─ src/
│  └─ myapp/
│     ├─ __init__.py
│     ├─ mathy.py
│     └─ io_helpers.py
├─ tests/
│  ├─ test_mathy.py
│  └─ test_io_helpers.py
├─ pyproject.toml
└─ README.md

Tip: Put application code in src/myapp and tests in tests/. Tools like pytest discover tests named test_*.py.

Example code (to be tested)

# src/myapp/mathy.py
def add(a: float, b: float) -> float:
    return a + b

def divide(a: float, b: float) -> float:
    if b == 0:
        raise ZeroDivisionError("b must not be zero")
    return a / b

3) The Built-in unittest (Batteries Included)

unittest ships with Python 3—no install needed.

# tests/test_mathy_unittest.py
import unittest
from myapp.mathy import add, divide

class TestMathy(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertAlmostEqual(add(0.1, 0.2), 0.3, places=7)

    def test_divide_ok(self):
        self.assertEqual(divide(10, 2), 5.0)

    def test_divide_by_zero(self):
        with self.assertRaises(ZeroDivisionError) as cm:
            divide(1, 0)
        self.assertIn("must not be zero", str(cm.exception))

if __name__ == "__main__":
    unittest.main()

Run: python -m unittest or python -m unittest tests/test_mathy_unittest.py

4) pytest (Fast, Friendly, Powerful)

Install with pip install pytest then run pytest. It offers concise tests, rich output, and powerful plugins.

# tests/test_mathy_pytest.py
from myapp.mathy import add, divide
import pytest

def test_add():
    assert add(2, 3) == 5

def test_divide_ok():
    assert divide(9, 3) == 3.0

def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError):
        divide(1, 0)

Run: pytest -q

5) Fixtures: Reusable Setup/Teardown

Fixtures provide test data or resources and clean up automatically.

# tests/conftest.py
import tempfile, shutil, pathlib, pytest

@pytest.fixture
def temp_dir():
    d = tempfile.mkdtemp()
    try:
        yield pathlib.Path(d)
    finally:
        shutil.rmtree(d)

# tests/test_io_helpers.py
def test_write_and_read(temp_dir):
    p = temp_dir / "hello.txt"
    p.write_text("hi")
    assert p.read_text() == "hi"

Tip: Place shared fixtures in tests/conftest.py for auto-discovery.

6) Mocking with unittest.mock

Mock external calls (network, file system, time) so tests are fast and deterministic.

# src/myapp/io_helpers.py
import requests

def fetch_title(url: str) -> str:
    r = requests.get(url, timeout=5)
    r.raise_for_status()
    return r.text.split("<title>")[1].split("</title>")[0]

# tests/test_io_helpers_mock.py
from unittest.mock import patch, MagicMock
from myapp.io_helpers import fetch_title

@patch("myapp.io_helpers.requests.get")
def test_fetch_title_mocks_requests(mock_get):
    fake = MagicMock()
    fake.text = "<html><title>Hello</title></html>"
    fake.raise_for_status = lambda: None
    mock_get.return_value = fake

    assert fetch_title("https://example.com") == "Hello"
    mock_get.assert_called_once()

Rule of thumb: Patch where the object is used, not where it’s defined.

7) Parameterization (More Cases, Less Boilerplate)

# tests/test_mathy_param.py
import pytest
from myapp.mathy import add

@pytest.mark.parametrize(
    "a,b,expected",
    [
        (0, 0, 0),
        (2, 3, 5),
        (-1, 5, 4),
        (0.1, 0.2, 0.3),
    ],
)
def test_add_param(a, b, expected):
    assert add(a, b) == pytest.approx(expected)

Why it rocks: Easier to read, great failure messages, and one test turns into many.

8) Coverage: Know What You Tested

Install pip install coverage, then:

# with pytest
coverage run -m pytest
coverage report -m
coverage html  # open htmlcov/index.html

Aim for meaningful coverage (e.g., 80%+), without gaming the metric.

9) A Tiny TDD Loop

  1. Write a small failing test (red).
  2. Implement the simplest code to pass (green).
  3. Refactor for clarity/perf while keeping tests green.
# 1) failing test first
def test_is_even():  # tests/test_even.py
    from myapp.mathy import is_even
    assert is_even(2) is True
    assert is_even(3) is False

# 2) minimal implementation
# src/myapp/mathy.py
def is_even(n: int) -> bool:
    return (n % 2) == 0

10) Run Tests on Every Push (CI)

Here’s a minimal GitHub Actions workflow to run tests on Python 3.10–3.12 and generate coverage.

# .github/workflows/tests.yml
name: tests

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.10", "3.11", "3.12"]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: { python-version: ${{ matrix.python-version }} }
      - run: python -m pip install --upgrade pip
      - run: pip install -e . pytest coverage
      - run: coverage run -m pytest -q
      - run: coverage report -m

Pro tip: Fail the build if coverage drops using coverage report --fail-under=80.

11) Assertions & Cheatsheet

unittest assertions

AssertionUse
assertEqual(a, b)Exact equality
assertAlmostEqual(a, b, places=7)Floats
assertTrue(x) / assertFalse(x)Truthiness
assertIn(x, seq)Membership
assertIsNone(x)None checks
assertRaises(E)Exceptions

pytest power-ups

FeatureExample
Simple assertsassert func(x) == y
Parameterize@pytest.mark.parametrize(...)
Fixtures@pytest.fixture + autouse
Marks@pytest.mark.slow, -m "not slow"
Skip/xfailpytest.skip(), @pytest.mark.xfail

12) FAQ

Do I need both unittest and pytest?

No. Many teams use just pytest for new projects. You can still run legacy unittest tests under pytest.

How many tests should I write?

Focus on critical paths and tricky logic. Aim for high coverage with meaningful scenarios—not just lines executed.

How do I test time, random, or network calls?

Use unittest.mock to patch functions like time.time, random.random, or HTTP clients. Inject dependencies where possible.

Copy-Paste Quickstart

# 1) install
pip install pytest coverage

# 2) create files
mkdir -p src/myapp tests
# add src/myapp/mathy.py and tests/test_mathy_pytest.py (from above)

# 3) run tests + coverage
pytest -q
coverage run -m pytest
coverage report -m

Python 2.7 vs Python 3

What changed, why it matters, and how to migrate safely.

Quick Summary Table

Topic Python 2.7 Python 3.x Notes
Lifecycle End-of-life (EOL) Jan 1, 2020 Actively maintained Security and new features only in Python 3.
Print print "hi" print("hi") (function) Use parentheses in Py3; enables redirection like any function.
Integer Division 5/2 == 2 5/2 == 2.5 Use // for floor division consistently.
Text vs Bytes str = bytes; unicode = text str = text (Unicode); bytes = binary Explicit encodes/decodes in Py3 when crossing boundaries.
Input raw_input() (text), input() evals input() returns text Safer and simpler in Py3.
Range & Iterators xrange() (lazy), range() (list) range() is lazy No xrange in Py3.
Exceptions except ValueError, e: except ValueError as e: New syntax only in Py3.
Libraries Many packages dropped support Full ecosystem support Modern libs target Py3.8+.
Strings Literals "abc" is bytes; u"abc" unicode "abc" is Unicode; b"abc" bytes Prefer Unicode text, bytes for I/O.
F-Strings Not available f"Hello {name}" Fast, readable formatting (Py3.6+).
Type Hints 3rd-party stubs only Built-in typing Better tooling & readability.
Dict Views .keys()/.items() return lists Return dynamic views (iterable) Wrap with list(...) if you need a list.
Unicode I/O Implicit conversions common Explicit, consistent Open files with encoding="utf-8".
Metaclass Syntax __metaclass__ = M class C(metaclass=M): Cleaner and explicit in Py3.
Standard Library Old module names/locations Reorganized (e.g., urllib) Use modern imports or compatibility layers.

Why Python 3 Happened

Python 3 fixed long-standing design issues—especially the confusing split between text and bytes, integer division, and a few syntax inconsistencies. The result is a cleaner language that’s easier to teach, localize, and maintain.

Common Code Differences

Print & Division

# Python 2.7
print "Hello"
print 5/2        # 2
from __future__ import division
print 5/2        # 2.5 with future import
# Python 3.x
print("Hello")
print(5/2)       # 2.5
print(5//2)      # 2  (floor division)

Unicode vs Bytes

# Python 2.7
u_text = u"café"
b_data = "café"              # bytes
print(type(u_text)), print(type(b_data))
# Python 3.x
text = "café"                # str (Unicode)
data = "café".encode("utf-8")# bytes
with open("out.txt", "w", encoding="utf-8") as f:
    f.write(text)

Ranges & Iteration

# Python 2.7
for i in xrange(3):
    pass
# Python 3.x
for i in range(3):  # lazy like xrange
    pass

Exceptions & Input

# Python 2.7
try:
    1/0
except ZeroDivisionError, e:
    print e
name = raw_input("Name: ")
# Python 3.x
try:
    1/0
except ZeroDivisionError as e:
    print(e)
name = input("Name: ")

Standard Library Reorg Highlights

URLs

# Python 2.7
import urllib2
data = urllib2.urlopen("https://example.com").read()
# Python 3.x
from urllib.request import urlopen
data = urlopen("https://example.com").read()

Itertools / Dicts

# Python 2.7
d = {"a":1}
d.keys()    # list
# Python 3.x
d = {"a":1}
list(d.keys())   # materialize if needed

Migration Tips (2.7 → 3)

  • Target a modern Python 3 (3.10+ recommended) for long-term support and features (pattern matching, better typing, speedups).
  • Run python3 -m venv .venv and port code inside an isolated environment.
  • Use 2to3 or python-modernize/futurize for a first pass; then hand-tune text/bytes boundaries.
  • Adopt from __future__ import print_function and unicode_literals in 2.7 to reduce diffs before switching.
  • Replace xrangerange, iteritems()items(), raw_inputinput.
  • Open files explicitly with encodings: open(..., encoding="utf-8").
  • Pin and upgrade dependencies that still assume Py2; most modern versions are Py3-only.
  • Add tests (e.g., pytest), run type checks (mypy), and format (black) once on Py3.
Rule of thumb: Treat all in-memory text as Unicode (str) and only encode/decode at I/O boundaries (files, sockets, HTTP).

Which Should You Use in 2025?

Use Python 3 for everything new. Python 2.7 is unmaintained and unsupported by the modern ecosystem. If you maintain legacy 2.7 code, prioritize a staged migration to Python 3 with automated tests and incremental refactors.