Python functions are reusable blocks of code used to perform a specific task. They help organize programs into smaller sections and execute the same logic whenever needed by calling the function.

Defining a Function
A function can be defined using def keyword. Below is the syntax to define a function:

Here, we define a function using def that prints a welcome message when called.
def fun():
print("Welcome to GFG")
Calling a Function
After creating a function, call it by using the name of the functions followed by parenthesis containing parameters of that particular function.
def fun():
print("Welcome to GFG")
fun()
Output
Welcome to GFG
Function Arguments
Arguments are values passed to a function when it is called. They allow functions to receive input data and perform operations using those values.
Syntax
def function_name(arguments):
# function body
return value
- def function_name(arguments): defines a function with optional arguments.
- # function body contains the statements to be executed.
- return value returns a result from the function. If no return statement is used, it returns None by default.
Example: In this example, function checks whether the number passed as an argument is even or odd.
def evenOdd(x):
if (x % 2 == 0):
return "Even"
else:
return "Odd"
print(evenOdd(16))
print(evenOdd(7))
Output
Even Odd
Types of Function Arguments
Python supports different types of arguments that can be passed during a function call.
1. Default argument: Default argument use a predefined value when no value is passed during the function call.
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
myFun(10)
Output
x: 10 y: 50
Explanation:
- y=50 sets a default value for parameter y and myFun(10) passes only one argument.
- Since y is not provided, it uses the default value 50.
2. Keyword Arguments: pass values using parameter names, so argument order does not matter.