Functions are like mini-programs within your program. They allow you to write a block of code once and use it multiple times by calling the function's name. Functions can also take inputs (arguments) and return outputs.
Why use Functions?
- Code Reusability: Write once, use it anywhere.
- Organization: Break large programs into smaller, more manageable pieces.
- Readability: Makes your code easier to read and understand.
- Debugging: Easier to test and debug specific parts of your code.
Defining a Function in Python
To define a function, use the def
Here’s the syntax:
def function_name(parameters):
# Code block
return value
Example: A simple Function
Let’s create a function that greets someone:
def greet():
print("Hello! Welcome to Python programming.")
: Defines the function.def
: Name of the function.greet
: Code inside the function.print("...")
You can call this function like so:
greet()
# Output: Hello! Welcome to Python programming.
Adding parameters
Parameters allow you to pass information to functions. For example:
def greet_person(name):
print(f"Hello, {name}! Welcome to Python programming.")
Now, you can call it with different names:
greet_person("Alice")
# Output: Hello, Alice! Welcome to Python programming.
greet_person("Bob")
# Output: Hello, Bob! Welcome to Python programming.
Using return
to get outputs
return
Functions can return values to the code that called them:
def add_numbers(a, b):
return a + b
Call the function and store the result:
result = add_numbers(3, 5)
print(result)
# Output: 8
Scope: where variables live
- Local Variables: Exist only inside the function.
- Global Variables: Exist everywhere in your program.
Example:
x = 10 # Global variable
def multiply_by_two():
x = 5 # Local variable
return x * 2
print(multiply_by_two()) # Output: 10
print(x) # Output: 10 (global x is unchanged)
Conclusion
Functions are powerful tools that make your code more efficient and easier to manage. By learning to define and use them, you’re taking a significant step toward writing better programs!