Functions in Python are blocks of reusable code that perform specific tasks. They allow you to break your program into smaller, more manageable pieces, making the code more organized and easier to maintain. Functions also promote code reusability, as you can call them multiple times from different parts of your program.
You can define a function in Python using the def
keyword, followed by the function name, parentheses, and a colon. The code block that follows the colon is the function body, where you write the code to execute when the function is called.
# Defining a simple function
def greet():
print("Hello, welcome!")
# Defining a function with parameters
def add(a, b):
return a + b
To use a function, you call it by its name followed by parentheses, optionally passing arguments inside the parentheses for functions that accept parameters.
# Calling the greet() function
greet()
# Calling the add() function with arguments
result = add(5, 3)
print("Sum:", result)
Functions can also return values using the return
keyword. When a function is called and returns a value, you can assign the result to a variable or use it directly in your code.
# Function with return value
def square(x):
return x * x
# Calling the square() function and using the returned value
num = 4
squared_num = square(num)
print("Square of", num, "is", squared_num)
Defining and calling functions is a fundamental concept in Python programming that enables you to modularize your code and create more organized and efficient programs.