As you all know there are many built-in function is python 3. Like, range(), print(), map(), eval() and many more.
Function in python is made for do some certain task according to to given input. Like, Addition of given two number, check whether the number is prime or not, etc.
In other words function is a block of code that runs when we call it. Let’s go with syntax:
Function Syntax In Python 3
User defined function start with def keyword after that you have to mention function name.
Here is the basic syntax of function in python 3
#Function syntax in python 3 def function_name(parameters): code
Here you can see :
- User defined function starts with def keyword
- Then mention function name and in the brackets give parameters (not compulsory)
- Next line of function in python 3 starts with indentation and then your code
This is the basic syntax of function in python 3. Now Let’s move toward function example in python
Function Example in Python
Let’s make a function that greet user. Code mentioned below :
#function in python example def greet_user(name): print("Hello " + name) greet_user("Yash") #Output Hello Yash
Function code explanation :
- As I said user defined function starts with def keyword
- Then we mention our function name which is greet_user
- greet_user function take one parameter called name
- This function will print “Hello” with mentioned name with + operator
- At the end we call greet_user function and give argument “Yash”
- Output will be Hello Yash as you can see above
Here is a small project on Function,
Project on Python Function
Make a function that take 2 arguments which will be a number and return the sum of this two numbers.
Lambda Function in Python
Lambda function is also called as anonymous function. Anonymous function means that a function is without a name and it is single line function
Syntax of Lambda Function in Python
we have used def keyword user defined function same like that we use lambda keyword to create lambda function in python.
#lambda function in python add = lambda x,y : x + y print(add(7,3)) #Output 10
Code explanation :
- Here lambda function take two numbers as an argument
- And return the sum of this two numbers
This is how you can define function in python 3