A Python function is like a mini-program inside your main program.
It's a reusable
block of code that does a specific task. Instead of writing the same code over and
over, you put it in a function and just call it whenever you need it.
Here's the basic idea:
python
Copy
Edit
def greet():
print("Hello!")
def means “define a function”
greet is the name of the function
The code inside (indented) runs when you call the function like this:
python
Copy
Edit
greet()
Functions can also take inputs (called parameters):
python
Copy
Edit
def greet(name):
print("Hello, " + name + "!")
Now you can do:
python
Copy
Edit
greet("Alice")
greet("Bob")
Functions can also return a value:
python
Copy
Edit
def add(a, b):
return a + b
You can use it like this:
python
Copy
Edit
result = add(3, 5)
print(result) # This prints 8