Forum

Learn Python Functi…
 
Notifications
Clear all

Learn Python Functions

1 Posts
1 Users
0 Reactions
11 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

Python functions are like reusable mini-programs that help you organize and simplify your code. Let’s break it down 🧠🔧


🧱 What Is a Function?

A function is a block of code that performs a specific task. You define it once and call it whenever you need it.

def greet():
    print("Hello there!")
  • def starts the function definition.
  • greet is the function name.
  • The code inside runs when you call greet().

🎯 Why Use Functions?

  • Avoid repetition: Write code once, reuse it.
  • Improve readability: Break complex tasks into smaller chunks.
  • Make debugging easier: Isolate logic into testable units.

🧪 Functions with Parameters

You can pass data into functions using parameters:

def greet(name):
    print(f"Hello, {name}!")
  • Call it like greet("Alice") → Output: Hello, Alice!

🔙 Returning Values

Functions can also return results:

def add(a, b):
    return a + b

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

🧠 Advanced Features

  • Default values: def greet(name="friend")
  • Arbitrary arguments: def greet(*names)
  • Keyword arguments: def greet(**info)
  • Nested functions: Functions inside functions!

🧪 Real-Life Example

def calculate_discount(price, discount):
    return price * (1 - discount)

print(calculate_discount(100, 0.2))  # Output: 80.0

 


   
Quote
Share: