December 22, 2024

Tirth's Blog

My technical notes

Python Functions: Defining and Calling

Functions in Python are blocks of code designed to perform specific tasks. They help in organizing code into reusable chunks.

**Defining Functions**
Functions are defined using the `def` keyword followed by the function name and parentheses:

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

**Calling Functions**
You call functions by using their name followed by parentheses:

greet(“Alice”) # Output: Hello, Alice!

**Function Arguments**
Functions can accept parameters to work with:

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

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

**Return Statement**
The `return` statement is used to send a result back from a function:

def square(x):
return x * x

**Example**:

print(square(4)) # Output: 16

**Conclusion**
Functions are essential for creating modular code and reusing code efficiently. They help in breaking down complex problems into simpler, manageable pieces.

About The Author

Copyright © All rights reserved. | Newsphere by AF themes.