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 learn python")
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 learn python")
fun()
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.
def evenOdd(x):
if (x % 2 == 0):
return "Even"
else:
return "Odd"
print(evenOdd(16))
print(evenOdd(7))
Types of Arguments:
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)
2. Keyword Arguments: pass values using parameter names, so argument order does not matter.
def student(fname, lname):
print(fname, lname)
student(fname='Kamalesh', lname='A')
student(lname='A', fname='Kamalesh')
3. Positional Arguments: values are assigned to parameters based on their order in the function call.
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
print("Case-1:")
nameAge("Kamal", 22)
print("Case-2:")
nameAge(22, "Kamal")

Top comments (0)