#PYTHON(DAY16)
functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
We may call the function and reuse the code contained within it with different variables rather than repeatedly creating the same code block for different input variables.
Advantages of Functions in Python
Python functions have the following Perks.
- By including functions, we can prevent repeating the same code block repeatedly in a program.
- Python functions, once defined, can be called many times and from anywhere in a program.
Syntax of Python Function
# An example Python Function
def function_name( parameters ):
# code block
Creating a function
def my_function():
print("Hello from a function")
calling a function
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
How the position of argument matters?
def greet(name, greeting):
print(greeting+' '+name)
greet('good mrng','x')
And the output is:
x good mrng
As, here the greeting is good mrng we get name as good mrng instead of x
so, here we discuss about the arguments
Arguments
positional arguments
- while passing the argument/s, the value/s of arg/s will be assigned to parameters based on the order of parameters at time of defining function
- while calling ‘greet’ function, we inter changed the order and this resulted in a different o/p
- these kind of passing the arguments based on positions are called as positional arguments
Example for positional arguments
def abc(x,y,z):
print(x+y+z)
abc(1,2,3)
And the output is:
6
keyword arguments
- at the time of calling the func, if we pass the arguments by using the parameter name, these kind of arguments are called as keyword arguments
- func_name(para1=arg1, para2=arg2)
Example for keyword arguments
def greet(greeting,firstname,lastname):
print(greeting+' '+firstname+' '+lastname)
greet(greeting ='hi', firstname='bhavitha',lastname='cherukuri')
And the output is:
hi bhavitha cherukuri
No comments:
Post a Comment