Why Don't Chefs Start by Growing Vegetables?

Imagine you order "Kung Pao Chicken" at a restaurant.
After receiving the order, the chef will directly turn around to grab chicken from the fridge, heat the wok, add special sauce, and serve the dish to you in five minutes.
They will absolutely not run to the backyard to hatch chicks, wait for them to grow, then plant scallions and garlic, and finally come back to cook for you. That would be ridiculous.

This restaurant operates efficiently because it has a set of "Standard Operating Procedures (SOP)."
Someone has already packaged all the complex actions like "chopping scallions," "marinating chicken," and "preparing sauce." The head chef only needs to "call" these pre-prepared semi-finished products to quickly whip up a perfect plate of Kung Pao Chicken.

In programming, we call this mechanism of "packaging complex actions for repeated use" a "Function."


Without Functions, Your Code Would Be a Disaster

In the previous two chapters, we learned to write if-else for calculating discounts and loops to find failing students.
But suppose you're the owner of a mega e-commerce site, and your website has three places that require "discount calculations":

  1. The flash sale section on the homepage
  2. The shopping cart in the member-exclusive area
  3. The refund system in the customer service backend

If you don’t use functions, you’d have to copy and paste that 20-line discount calculation code into these three places.
What’s the problem?
If one day you decide, "VIPs should get a 15% discount instead of 20%," you’re in trouble! You’d have to manually locate those three spots in thousands of lines of code and change them one by one. If you miss one, customers will call to complain!

Sealing the Magic: Building Your Own "Discount Calculator"

To solve this problem, engineers invented function.
It’s like a machine you’ve personally created. You can name this machine "Magical Discount Calculator" and instruct it:

  • Input Slot (Parameters): It needs to take in the "original price" and "whether it’s a VIP."
  • Internal Workings (Execution Logic): Inside the machine, you use if-else to calculate the price.
  • Output (Return Value): Finally, the machine spits out the "final price" to you.

Vibe Prompt in Action: Designing Your First Business Machine

【Function Encapsulation Prompt】
I’m using JavaScript.
Please write a function named calculatePrice.

  1. It should accept two parameters: originalPrice (number) and isVip (boolean true/false).
  2. The logic is: If it’s a VIP, apply a 20% discount. If not, apply a 10% discount.
  3. Finally, return the calculated final price.
  4. Below the code, demonstrate how to "call" this function twice (once for a VIP spending 1000, once for a regular customer spending 2000) and print the results.

AI-Generated Function Encapsulation and Call:

// 1. Building the machine: Define a function named calculatePrice
function calculatePrice(originalPrice, isVip) {
  let finalPrice;

  if (isVip === true) {
    // VIP gets 20% off
    finalPrice = originalPrice * 0.8;
  } else {
    // Regular customer gets 10% off
    finalPrice = originalPrice * 0.9;
  }

  // "Spit out" the calculated result
  return finalPrice;
}

// ==========================================

// 2. Using the machine: "Call" it where needed
// Case 1: VIP buys a 1000-yuan item
const price1 = calculatePrice(1000, true);
console.log(`VIP customer pays: ${price1} yuan`); // Expected output: 800

// Case 2: Regular customer buys a 2000-yuan item
const price2 = calculatePrice(2000, false);
console.log(`Regular customer pays: ${price2} yuan`); // Expected output: 1800

See? When you encapsulate the logic into a function, the code becomes so clean and efficient!
Even better, if you later decide to change the discount to 15%, you only need to modify one line inside the machine, and all places calling this machine will instantly update to 15%. This is the most important principle in software engineering: "DRY (Don’t Repeat Yourself)."


Conclusion: Congratulations, You’re Now a Vibe Coder!

After completing this five-chapter "Programming for Muggles 101" course, you’ve mastered the four core pillars of modern software development:

  1. Variables & Data Types (Nouns): Know how to store data.
  2. Conditional Logic: Know how to use if-else to teach computers to make decisions.
  3. Loops (Labor): Know how to make computers process thousands of data points.
  4. Functions (Arsenal): Know how to package complex actions for reuse.

In traditional computer science programs, mastering these four pillars usually takes an entire semester of midterms and finals.
But in the era of Vibe Coding, you don’t need to memorize brackets or obsess over indentation. You just need to understand "the nouns and logic of these concepts", then write clear prompts in plain language, and Cursor will generate flawless code for you.

You’re no longer a "laborer" cramming syntax; you’re an "architect" directing AI to build skyscrapers.
With these powerful tools, proceed to the next advanced course! Whether it’s building websites, creating Line bots, or writing scrapers, the entire programming world is now open to you!


🎁 [VIP Exclusive Bonus] Vibe Coding实战演练与商业思维

After learning basic programming syntax, many ask: "I understand loops and conditionals, but how do I monetize this?"
This is the blind spot of traditional rote learning. Traditional courses only teach "grammar" but not how to write "profitable content."

As a Vibe Coder, you must master these three core business mindsets—they’ll be your foundation for landing projects worth over 50,000 yuan:

1. Always Think "Business Value" Before "Technical Implementation"

When a client says, "I need a login system":

  • Junior Engineer’s Reaction: Start thinking about databases and password hashing algorithms.
  • Vibe Coder’s Reaction: Ask, "Who is this login system for? If it’s for general consumers, we should integrate LINE Login or Google Sign-In for higher conversion rates and no password security risks."
    See the difference? You don’t write a single line of password encryption code, but you create more value for the client.

2. Advanced Debugging with Cursor

In real development, you’ll encounter errors. When red text appears, follow these steps:

  1. Don’t Panic: Errors are the computer communicating with you, not scolding you.
  2. Copy the Full Error: Copy the error message from the terminal or browser console verbatim, including context.
  3. Explain Your Intent: Type in Cursor:

    "I’m trying to create a loop to render a product list but got this error: [paste error]. Is this a data format issue or syntax error? Please provide corrected code."
    With enough context, AI’s debugging accuracy jumps from 50% to 99%.

3. Turning Knowledge into Billable Services

Now that you know basic JS/Python, look for projects like these on Upwork or PTT:

  • "Need help merging 100 Excel files." (Use Python loops)
  • "Need a script to check if a website is down daily." (Use JS conditionals)

These projects are too small for senior engineers but too hard for traditional admins—this is your blue ocean.
Boldly quote 3,000–5,000 yuan, finish in 10 minutes with Cursor, and earn an hourly rate of 30,000 yuan!

Remember: You’re selling time saved, not code. With this mindset, proceed to advanced courses!

Functions in Python and JavaScript

Functions are reusable blocks of code that perform a specific task. They are the building blocks of organized, maintainable software.

Python Functions

# Basic function
def greet(name):
    return f"Hello, {name}!"

# Default parameters
def power(base, exponent=2):
    return base ** exponent

print(power(3))     # 9 (3 squared)
print(power(3, 3))  # 27 (3 cubed)

# Multiple return values
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([3, 1, 7, 2, 9])
print(f"Low: {low}, High: {high}")

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

JavaScript Functions

// Function declaration
function greet(name) {
    return `Hello, ${name}!`;
}

// Arrow function
const greet = (name) => `Hello, ${name}!`;

// Default parameters
const power = (base, exponent = 2) => base ** exponent;

// Rest parameters
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);
console.log(sum(1, 2, 3, 4));  // 10

Function Best Practices

| Practice | Why | |----------|-----| | Single responsibility | One function = one task | | Descriptive names | calculateTotal not calc or doStuff | | Limit parameters | 3 or fewer; use objects for more | | Return values, don't print | Functions should be testable | | Handle edge cases | Empty inputs, invalid types, boundary values | | Write docstrings/comments | Explain what, why, not how | | Keep functions small | < 20 lines is ideal, < 50 is acceptable | | Pure functions > side effects | Same input = same output, no mutations |

Pure vs Impure Functions

# Pure function (same input → same output, no side effects)
def add(a, b):
    return a + b

# Impure function (side effect: modifies external state)
total = 0
def add_to_total(value):
    global total
    total += value
    return total

| Aspect | Pure Function | Impure Function | |--------|--------------|-----------------| | Predictability | Same input = same output | Output may vary | | Testability | Easy to test | Harder to test | | Debugging | Simple | Complex (hidden state) | | Concurrency | Safe (no shared state) | May have race conditions | | Caching | Can cache results | Cannot cache |

Summary

Functions are reusable code blocks. Use them to organize, reuse, and simplify your code. Keep functions small, give them descriptive names, and prefer pure functions without side effects.

Key takeaways:

  • Functions = named, reusable code blocks
  • Parameters pass data in; return value passes data out
  • Default parameters handle missing arguments
  • Lambda/arrow functions for short, inline operations
  • Single responsibility: one function, one purpose
  • Pure functions: same input → same output, no side effects
  • Keep functions under 20 lines
  • Test functions independently

What's Next: Course Wrap-Up

The next chapter wraps up the coding-101 course with key takeaways and next steps.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!