Functions

🔧 What Is a Function in Programming?

A function is a reusable block of code designed to perform a specific task. Instead of writing the same code repeatedly, you can define it once in a function and "call" it whenever needed.


✅ Why Use Functions?

  • Reusability: Write once, use many times.

  • Clarity: Makes code easier to read and understand.

  • Organization: Helps break large programs into smaller, manageable pieces.

  • Debugging: Easier to find and fix errors in isolated blocks of code.


🧠 How Functions Work

A basic function has:

  1. Name – to identify the function.

  2. Parameters (optional) – input values.

  3. Code block – what the function does.

  4. Return value (optional) – the result it gives back.


1. Basic Function Without Parameters

  • def: Defines a function named who_i_am.

  • Inside the function, variables are set and a message is printed.

  • who_i_am() calls the function and displays:


2. Function with One Parameter

  • Accepts one input (num), adds 100 to it, and prints the result.

  • Output:


3. Function with Two Parameters

  • Takes two inputs and prints their sum.

  • Output:


4. Function with Return Value

  • Multiplies x and y, then returns the result using return.

  • print() displays the returned value.

  • Output:


✅ Summary

  • Functions organize code into reusable blocks.

  • Use parameters to pass data in.

  • Use return to send data out.

  • Calling a function runs its code.

Last updated