惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
T
Threatpost
P
Palo Alto Networks Blog
NISL@THU
NISL@THU
O
OpenAI News
Project Zero
Project Zero
G
GRAHAM CLULEY
P
Privacy International News Feed
A
Arctic Wolf
Microsoft Azure Blog
Microsoft Azure Blog
H
Help Net Security
M
MIT News - Artificial intelligence
T
Threat Research - Cisco Blogs
S
Security @ Cisco Blogs
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
D
Docker
aimingoo的专栏
aimingoo的专栏
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
W
WeLiveSecurity
P
Proofpoint News Feed
腾讯CDC
Cloudbric
Cloudbric
S
Secure Thoughts
C
Check Point Blog
博客园 - Franky
T
The Exploit Database - CXSecurity.com
T
Troy Hunt's Blog
GbyAI
GbyAI
Security Archives - TechRepublic
Security Archives - TechRepublic
Application and Cybersecurity Blog
Application and Cybersecurity Blog
月光博客
月光博客
C
Cyber Attacks, Cyber Crime and Cyber Security
I
Intezer
TaoSecurity Blog
TaoSecurity Blog
L
Lohrmann on Cybersecurity
V
Visual Studio Blog
F
Fortinet All Blogs
博客园 - 叶小钗
C
CXSECURITY Database RSS Feed - CXSecurity.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recorded Future
Recorded Future
C
Cisco Blogs
博客园 - 司徒正美
Stack Overflow Blog
Stack Overflow Blog
Y
Y Combinator Blog
Apple Machine Learning Research
Apple Machine Learning Research

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Python for Beginners — Part 6: Functions
Ramesh S · 2026-06-23 · via DEV Community

Part 6 of a beginner-friendly series on learning Python from scratch.

In Part 5, we learned to organize data with lists, dictionaries, and other collections. Now it's time to organize our code itself.

A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you write it once in a function, then call that function whenever you need it. This is the foundation of writing clean, maintainable programs.

Defining and Calling Functions

The basics

def greet():
    print("Hello, World!")

greet()  # Call the function

Use def to define a function. The function name is followed by parentheses and a colon. The indented block below is the function's body.

When you call the function (by typing its name with parentheses), Python runs the code inside it.

Functions with parameters

Most functions need information to work with. That's what parameters are for:

def greet(name):
    print(f"Hello, {name}!")

greet("Ramesh")   # Hello, Ramesh!
greet("Priya")    # Hello, Priya!

name is a parameter (placeholder). When you call greet("Ramesh"), name becomes "Ramesh" inside the function.

Multiple parameters:

def add(x, y):
    print(x + y)

add(5, 3)   # 8
add(10, 20) # 30

Return values

A function can calculate something and give the result back to you with return:

def add(x, y):
    return x + y

result = add(5, 3)
print(result)       # 8

The return statement stops the function and sends a value back. The caller can then use that value.

def greet(name):
    message = f"Hello, {name}!"
    return message

greeting = greet("Ramesh")
print(greeting)  # Hello, Ramesh!

A function can return multiple values as a tuple:

def get_user_info():
    return "Ramesh", 25, "Chennai"

name, age, city = get_user_info()
print(name, age, city)  # Ramesh 25 Chennai

Arguments: Positional vs Keyword

There are two ways to pass values to a function:

Positional arguments

Arguments are matched by position:

def describe(name, age):
    print(f"{name} is {age} years old")

describe("Ramesh", 25)  # Ramesh is 25 years old
describe(25, "Ramesh")  # 25 is Ramesh years old (wrong order, confusing)

Order matters.

Keyword arguments

You can use parameter names to be explicit:

def describe(name, age):
    print(f"{name} is {age} years old")

describe(age=25, name="Ramesh")  # Ramesh is 25 years old
describe(name="Ramesh", age=25)  # Ramesh is 25 years old (order doesn't matter)

Keyword arguments make code clearer and are less error-prone. Mix them freely:

describe("Ramesh", age=25)  # First positional, then keyword

Default Arguments

You can give parameters default values — they're optional:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Ramesh"))              # Hello, Ramesh!
print(greet("Ramesh", "Hi"))        # Hi, Ramesh!
print(greet("Ramesh", greeting="Hey"))  # Hey, Ramesh!

If the caller doesn't provide greeting, it defaults to "Hello".

Important rule: Parameters with defaults must come after parameters without defaults:

# Correct
def add(x, y, verbose=False):
    result = x + y
    if verbose:
        print(f"{x} + {y} = {result}")
    return result

# Wrong — SyntaxError
def add(x=0, y):
    return x + y

*args — Variable Number of Arguments

Sometimes you want a function to accept any number of arguments. Use *args:

def add_many(*numbers):
    total = 0
    for num in numbers:
        total += num
    return total

print(add_many(1, 2, 3))           # 6
print(add_many(1, 2, 3, 4, 5))     # 15
print(add_many())                  # 0 (no arguments)

*args (the name args is conventional) collects all extra arguments into a tuple. The * unpacks them.

def print_all(*items):
    for item in items:
        print(item)

print_all("apple", "banana", "cherry", 42)
# Prints each on its own line

**kwargs — Keyword Arguments as Dictionary

Similar to *args, use **kwargs to accept any number of keyword arguments:

def make_profile(**info):
    for key, value in info.items():
        print(f"{key}: {value}")

make_profile(name="Ramesh", age=25, city="Chennai")
# Output:
# name: Ramesh
# age: 25
# city: Chennai

**kwargs (convention) collects keyword arguments into a dictionary.

Combining everything

You can use *args and **kwargs together:

def my_function(required, *args, default_arg="default", **kwargs):
    print(f"Required: {required}")
    print(f"Args: {args}")
    print(f"Default: {default_arg}")
    print(f"Kwargs: {kwargs}")

my_function(1, 2, 3, 4, default_arg="custom", extra1="value1", extra2="value2")

# Output:
# Required: 1
# Args: (2, 3, 4)
# Default: custom
# Kwargs: {'extra1': 'value1', 'extra2': 'value2'}

Order: positional, *args, keyword defaults, **kwargs.

Scope and Variable Lifetime

Variables have scope — the region of code where they exist and are accessible.

Local scope

Variables created inside a function only exist inside that function:

def greet():
    message = "Hello"  # Local variable
    print(message)

greet()           # Hello
print(message)    # NameError — message doesn't exist here

Global scope

Variables created outside functions are global:

message = "Hello"  # Global variable

def greet():
    print(message)  # Can access global variables

greet()    # Hello
print(message)  # Hello

Modifying global variables

Be careful — inside a function, assignment creates a local variable:

count = 0

def increment():
    count = count + 1  # UnboundLocalError — trying to use local before assignment
    return count

increment()

To modify a global variable inside a function, use global:

count = 0

def increment():
    global count
    count = count + 1
    return count

increment()
print(count)  # 1

Tip: Generally, avoid modifying global variables. It makes code hard to understand. Instead, pass values in and return values out.

Lambda Functions — Quick Throwaway Functions

A lambda is a tiny anonymous function, useful for one-liners:

square = lambda x: x ** 2
print(square(5))  # 25

Syntax: lambda parameters: expression

Lambda functions are usually passed to other functions. For example, sorted() can take a function that determines the sort order:

people = [
    {"name": "Ramesh", "age": 25},
    {"name": "Priya", "age": 20},
    {"name": "Arun", "age": 30}
]

# Sort by age
sorted_by_age = sorted(people, key=lambda person: person["age"])
print(sorted_by_age)
# [{'name': 'Priya', 'age': 20}, {'name': 'Ramesh', 'age': 25}, {'name': 'Arun', 'age': 30}]

Or with map() to transform a list:

numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # [1, 4, 9, 16, 25]

Lambda is elegant for simple operations. For anything complex, write a proper function.

Recursion — Functions Calling Themselves

A recursive function calls itself. It's powerful for solving problems that repeat the same pattern at smaller scales.

Every recursive function needs a base case (when to stop) and a recursive case (how to shrink the problem):

def countdown(n):
    # Base case
    if n == 0:
        print("Blastoff!")
        return

    # Recursive case
    print(n)
    countdown(n - 1)

countdown(5)
# Output:
# 5
# 4
# 3
# 2
# 1
# Blastoff!

Without a base case, the function recurses infinitely and crashes:

def bad_countdown(n):
    print(n)
    bad_countdown(n - 1)  # Never stops!

bad_countdown(5)  # RecursionError: maximum recursion depth exceeded

Classic example: Factorial

def factorial(n):
    # Base case
    if n == 0 or n == 1:
        return 1

    # Recursive case
    return n * factorial(n - 1)

print(factorial(5))  # 120 (5 * 4 * 3 * 2 * 1)

Recursion is elegant but can be slow and memory-intensive. Use it when the problem naturally breaks into recursive patterns (like tree structures), not for simple loops.

Generators and Iterators

A generator is a function that yields values one at a time, instead of returning them all at once. Use yield:

def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

for num in count_up_to(5):
    print(num)

# Output:
# 1
# 2
# 3
# 4
# 5

The function pauses at yield and resumes where it left off. This is memory-efficient for large datasets:

# Without generator — creates entire list in memory
def range_list(n):
    result = []
    for i in range(n):
        result.append(i)
    return result

# With generator — creates values on-demand
def range_gen(n):
    for i in range(n):
        yield i

# Both work with for loops, but generator is more efficient
for num in range_list(1000000):  # Creates 1 million item list
    print(num)

for num in range_gen(1000000):   # Creates values as needed
    print(num)

Generators are a more advanced topic — understand them conceptually now; you'll use them more as you progress.

Practical Examples

Example 1: Simple calculator

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Cannot divide by zero"
    return x / y

print(add(10, 5))       # 15
print(divide(10, 0))    # Cannot divide by zero

Example 2: Processing collections

def find_max(numbers):
    if len(numbers) == 0:
        return None

    max_num = numbers[0]
    for num in numbers:
        if num > max_num:
            max_num = num
    return max_num

print(find_max([3, 7, 2, 9, 1]))  # 9

Example 3: Flexible greeting

def create_greeting(*names, greeting="Hello", punctuation="!"):
    message = f"{greeting}, {', '.join(names)}{punctuation}"
    return message

print(create_greeting("Ramesh", "Priya"))
# Hello, Ramesh, Priya!

print(create_greeting("Alice", "Bob", greeting="Hi", punctuation="?"))
# Hi, Alice, Bob?

Why This Matters

Functions are how you stop repeating yourself. Instead of copying the same code 10 times, you write it once, call it 10 times. This saves time, prevents bugs, and makes changes easier.

The most common beginner mistakes:

  • Forgetting parentheses when calling a function
  • Using return to print (they're different — one sends a value back, one displays it)
  • Trying to use variables defined inside a function outside of it
  • Infinite recursion (forgetting the base case)
  • Confusing *args with * unpacking operator

What's Next

In Part 7, we explored with modules, errors, and files — using other people's code, handling problems gracefully, and reading/writing data to disk. Functions you write will often read or write files.


This is Part 6 of an 8-part beginner Python series. Catch up on Part 1: Getting Started & Syntax, Part 2: Variables, Data Types & Numbers, Part 3: Strings & Booleans, Part 4: Operators & Control Flow, and Part 5: Collections.