Functions in python | Tutorial with Examples | CBSE Class 12
Functions in python
Introduction:
In this tutorials , we shell be learning about functions in python programming. This is the most important part of python programming for students to move from class 11th to class 12th. Python functions are very scoring in cbse class 12 examination as well as essential to learn advance concepts of python.
Functions are a core concept in Python, and they are used to group together code that performs a specific task. Functions in Python can be defined, called and reused, which makes coding more efficient and less repetitive.
In this tutorial, we will provide a comprehensive guide to Python functions, starting with the basics of functions, and moving on to more advanced concepts like function arguments, return statements, and lambda functions.
we’ll also take a comprehensive look at Python functions, starting from the basics and working our way up to more advanced techniques. We’ll cover everything you need to know to get started with functions in Python, including how to define functions, how to pass arguments, how to use return statements, and more.
We’ll also provide plenty of examples along the way to help you understand how functions work in practice.
After reading this tutorial Functions in python , you will be able to answer the following questions -:
- What is a function in python?
- Types of functions in python
- Why we need functions in python?
- How to create a functions in python?
- Explain the Components / parts of a functions in python?
- Can we write Python code without main function in python?
- How to use function in python?
Definition of function in general
When a number of instructions grouped and works together in a predefined sequence and accomplish a single task and this single task is given a specific name then it is called a function in python.
Before understanding “Functions in python“ in depth, we must understand first that what the term function actually is ?.
Functions in Real life – example
Suppose, if i say you that today is function at my home and you are invited at 7:00 PM, then tell me what comes in your mind ??????.
Let me tell you |||||
Functions !!!!!!!!!!! ……. Looks like …….. A party
A wedding function OR A Birthday function
A function, hurrah |||||| so many people get together and celebrate for only one purpose.
and the only purpose is marriage of my elder brother
The real python function
So, in the same way, more than two programming instructions or statements get together and perform for a single task. and the task is given a specific name. Now we can say that
In a python function all the activities are already defined and go on with an specific order/sequence of activities to finalize the last activity of the purpose.
Implement Real-life Function into Python Programming Function
From the above example real-life function, if we have a real life function in terms of python programming like this .
def birthday ():
-
-
print("Arrival of guests")
-
print("Time to breakfast")
-
print("Time to cut the cake")
-
print("Time to music & dance")
-
print("Time to dinner")
-
print("Time to say Good Bye |")
-
Here, you see that only a single name birthday() indicates the following sequential series of activities in mind and when you call this function for anything (like argument) then all the enclosed statements (like activities) are executed in a predefined order.
Here the function call birthday() will print all the statements in one shot because we know all the given activities are formally taken in a birthday party.
Now you have understood this term FUNCTION, let’s come to the technical perspective of python functions.
1. WHAT IS A FUNCTION IN PYTHON ?
To understand what is a function in terms of Python Programming we have an example of a polynomial equation from mathematics.
let’s say
f = 2 x2 + 1
And we know that to solve this equation and to find out the value of f finally we need to have some values of variable x. let’s say
x = 1
And now if we put x =1 in our equation then,
f(x)= 2 *(1) 2+ 1
= 2(1) + 1
= 3
Similarly,
for x=2, we have fx = 2(2)2+1=9
for x=3, we have fx = 2(3)2+1=19
for x=4, we have fx = 2(4)2+1=33
Then , we can say
f(1) = 3
f(2) = 5
f(3) = 19
f(4) = 33
Where
- f(x) = 2x2+1 is a function
- f() is a function name and x is a variable
- 2x2+1 is functionality ,the function performs for different values of x
2. HOW TO CTEATE A FUNCTIONS IN PYTHON?
As you have seen above , the mathematical function (Polynomial Equation) works for different inputs and provide results, Similarly, Python Programming also supports functions and we can create a function in Python that can have
-
- Argument like variable x
- can perform certain functionality like 2x2+1
- also it can return results
Hence the above-mentioned mathematical function can be written in Python like this
def calculate (x):
f= 2*x** 2 + 1
return f
Where
- def is a key word which must be used before starting the definition of function.
- Calculate (identifier) is the name of the function
- variable X inside the parentheses is the argument of or parameter to be pass during execution of this function.
- Colons (:) is the Indentations that means it requires block statements intended below the function that defines the functionality of given function and are called body of this function.
- Return statement returns the output outputted result.
Now to summarize the above concept we have the following diagram for your understanding.
Some other easy examples of functions
Example: 1
def sum(x,y):
s=x+y
return s
Example: 2
def greet():
print("Good morning")
Example: 3
def parameter(r):
return (2*3.14*r)
3. COMPONANTS / PARTS OF A FUNCTIONS IN PYTHON ?
- FUNCTION HEADER :- The first line of function definition that begins with the keyword def and ends with a colon (:) specifies the name of the function and its parameters
Example
def calculate (x):
def sum(x,y):
def greet():
def parameter(r):
- PARAMETER:- These are the variables listed within the parentheses () of a function header.
- FUNCTION BODY:- The block of a statement beneath the function header that defines the set of actions performed by the function.
Example
f=2*x**2
s=x+y
print ("Good morning ")
- INDENTATION:- The blank space in the beginning of a statement within a block all statements within the same block must have same indentation.
4. CALLING A FUNCTION IN PYTHON ?
Calling a function in Python is a straightforward process that involves using the function’s name followed by a pair of parentheses, with any required arguments passed inside the parentheses.
once, we have created a function, we need to use it for a program purpose to do this, we need to create a function call in the same program and the function call have the following format.
<(Functions name)> <(list values to be passed as argument)>
For example
-
-
Calculate (5)
Sum(2,3)
-
See here, for function calculate()
def calculate (x):
f=2*x**2
return f
calculate (5)
and for function sum()
def sum (x, y):
s=x+y
return s
sum(2,4)
A good example of Function Call
Here’s an example:
In this example, we define a function called add_numbers
that takes two arguments, x
and y
, and returns their sum. We then call the function with the arguments 2
and 3
, and store the result in a variable called result
. Finally, we print the value of result
to the console, which would be 5
.
To ensure that your content is optimized for SEO and readability, it’s important to use clear and descriptive function names that accurately reflect what the function does. Additionally, it’s a good practice to include comments that explain what the function does and how it works, so that other developers who read your code can easily understand it. Finally, be sure to format your code properly using consistent indentation and whitespace, as this can greatly improve its readability.
5. TYPES OF FUNCTIONS IN PYTHON
Python allow you to create your own functions and you can design these functions according to your requirement or interest but Python is also preloaded with a number of built-in functions that you can access and use for your purpose.
so that the question is here , how many types of functions are there in Python?. let’s get the answer
The function in Python Programming are of the following types
- Built in functions
- Functions defined in modulus
- User defined functions
let’s discuss of all of these types one by one
- Built in functions- These are preloaded or predefined functions and are always available for you to use like int(), float(), len(), type(), and input () etc. These are also a standard library functions and you can use them directly into your program You only need to write them in different parts of your program.
- Functions defined in modules- These functions are also predefined aur preloaded to use but are defined in a particular module which indicate the specific purpose like mathematics to use these functions in our program we always need to import corresponding module and they will be available to use like built-in functions for example if you want to use the predefined function sqrt to calculate square root through your program then you must import the corresponding module that is math to use this function.
Import math
num=int(input("Entrr a number:"))
sq_root= math.sqrt(num)
print("the square root is ", sq_root)
- User defined functions- These functions are designed or created by programmers like us it means as a programmer we can create our own functions and use them like earlier in this tutorial.
7. main() FUNCTIONS IN PYTHON ?
In Python, a function is a block of code that performs a specific task. The main()
function is not a special or reserved function in Python, but it is a common convention used to indicate the starting point of a program. When you define a main()
function in your Python program, you are essentially encapsulating the core functionality of your program within a single function.
Here’s an example of a simple Python program that uses a main()
function:
def main():
print("Hello, World!")
if __name__ == "__main__":
main()
In this program, the main()
function simply prints the string “Hello, World!” to the console. The if __name__ == "__main__":
line checks if the current script is being run as the main program. If it is, the main()
function is called and the “Hello, World!” message is printed.
When you run this program, the Python interpreter executes the if __name__ == "__main__":
block first. This block checks if the current script is the main program or if it is being imported as a module by another program. If it is the main program, the main()
function is called and the program prints “Hello, World!” to the console.
The benefit of using a main()
function in your Python program is that it allows you to separate the core functionality of your program from any other code that you may have in your script. By encapsulating your program’s core logic within a main()
function, you make it easier to read, test, and modify your code.
In summary, the main()
function in Python is a convention used to indicate the starting point of a program. It allows you to encapsulate the core functionality of your program within a single function, making your code more organized and easier to read.
The main() function is important because it defines the entry point of the program. When a program is executed, the interpreter looks for the main() function and starts executing the code from there. Without the main() function, the interpreter would not know where to start executing the code.
6. WHY WE NEED FUNCTIONS IN PYTHON ?
As a beginner, we always try to avoid writing large programs in Python Programming because it is difficult to manage or handle large programs in starting but it doesn’t mean that we should not start with it even after learning python basic programs. Obviously we must use functions but why ?. Because it makes easy to learn python programming by providing the following features.
Advantages of functions in python
When we use functions while writing our programs in python, it provides the following advantages
- It make our program more readable and understandable
- It is very easy to handle while editing our program
- It also reduces the complexity of repeating statements in our program
- Some times, It also reduces the size of our program
7. LIST OF FUNCTIONS IN PYTHON
Here is a list of some of the most commonly used functions in Python:
These are just a few of the many functions available in Python. Depending on your specific programming needs, you may find that other functions are more important or useful for your projects.
- print(): This function is used to output text or variables to the console or terminal.
- input(): This function is used to accept user input from the console or terminal.
- len(): This function is used to return the length of a string, list, tuple, or other iterable object.
- range(): This function is used to generate a sequence of numbers.
- type(): This function is used to return the data type of a variable.
- str(): This function is used to convert an object into a string.
- int(): This function is used to convert a string or other object into an integer.
- float(): This function is used to convert a string or other object into a floating-point number.
- list(): This function is used to convert a string or other object into a list.
- tuple(): This function is used to convert a string or other object into a tuple.
- set(): This function is used to create a set object.
- dict(): This function is used to create a dictionary object.
- sorted(): This function is used to sort a list or other iterable object.
- zip(): This function is used to combine two or more lists or other iterable objects.
- map(): This function is used to apply a function to each element in a list or other iterable object.
some more commonly used functions in Python:
- abs(): This function returns the absolute value of a number.
- max(): This function returns the largest item in an iterable or the largest of two or more arguments.
- min(): This function returns the smallest item in an iterable or the smallest of two or more arguments.
- sum(): This function returns the sum of all the items in an iterable.
- round(): This function rounds a number to a specified number of decimal places.
- open(): This function is used to open a file and return a file object.
- close(): This function is used to close a file object.
- write(): This function is used to write data to a file.
- read(): This function is used to read data from a file.
- isinstance(): This function is used to check if an object is an instance of a specified class or of a subclass thereof.
- any(): This function returns True if at least one item in an iterable is true.
- all(): This function returns True if all items in an iterable are true.
- enumerate(): This function is used to loop over an iterable with an index.
- filter(): This function is used to create a new iterable with elements that meet a certain condition.
- lambda(): This function is used to create an anonymous function.
some more commonly used functions in Python:
- join(): This function is used to join a list of strings into a single string.
- split(): This function is used to split a string into a list of substrings.
- replace(): This function is used to replace a substring in a string with another substring.
- strip(): This function is used to remove whitespace from the beginning and end of a string.
- format(): This function is used to format a string with specified values.
- chr(): This function is used to convert an integer into a character.
- ord(): This function is used to convert a character into its integer Unicode code point.
- dir(): This function is used to return a list of all the attributes and methods of an object.
- help(): This function is used to get help information about a Python object.
- eval(): This function is used to evaluate a string as a Python expression.
- exec(): This function is used to execute a string as a Python statement.
- locals(): This function is used to return a dictionary of the current local symbol table.
- globals(): This function is used to return a dictionary of the current global symbol table.
- id(): This function is used to return the unique identifier of an object.
- hash(): This function is used to return the hash value of an object.
These functions are ONLY commonly used in Python programming and can be very useful for a wide range of tasks.
Depending on your specific programming needs, you may find that other functions are more important or useful for your projects.
———————————————————————————————————————————
Exam Time
Class 12th Computer Science
———————————————————————————————————————————
Here are some important questions with answers on the topic of “Functions in Python” that will cover the basics of functions and their use in Python programming:
1. What are functions in Python?
Functions in Python are a block of reusable code that performs a specific task. They can take input, process that input, and return output. Functions are used to break down large programs into smaller, more manageable pieces of code.
2. How do you define a function in Python?
A function is defined using the def
keyword followed by the name of the function and a set of parentheses containing any arguments that the function takes. For example, the following code defines a function called greet
that takes one argument:
def greet(name):
print("Hello, " + name + "!")
3. What are the benefits of using functions in Python?
There are several benefits to using functions in Python, including:
- Reusability: Functions can be reused throughout a program, reducing the amount of code duplication and making the code easier to maintain.
- Modularity: Functions allow programs to be broken down into smaller, more manageable pieces, making it easier to develop, test, and debug code.
- Abstraction: Functions can hide complex logic and implementation details from the rest of the program, making the code more readable and easier to understand.
4. What is a return statement in Python?
The return
statement in Python is used to return a value from a function. When a function is called, it can perform some operations and then return a result to the caller. The return statement is followed by the value that is to be returned. For example, the following code defines a function called add
that takes two arguments and returns their sum:
def add(a, b):
return a + b
5. What is a function argument in Python?
A function argument in Python is a value that is passed to a function when it is called. Arguments are specified within the parentheses following the function name. Functions can take any number of arguments, including none. For example, the following code defines a function called multiply
that takes two arguments:
def multiply(a, b):
return a * b
6. How do you call a function in Python?
A function is called by using its name followed by a set of parentheses containing any arguments that the function takes. For example, the following code calls the greet
function defined earlier:
greet("John")
7. What is a default argument in Python?
A default argument in Python is a value that is used for an argument if no value is provided when the function is called. Default arguments are specified by setting a default value for an argument in the function definition. For example, the following code defines a function called say_hello
that takes one argument, with a default value of “World”:
def say_hello(name="World"):
print("Hello, " + name + "!")
8. What is a keyword argument in Python?
A keyword argument in Python is an argument that is passed to a function using its name. Keyword arguments are specified by using the argument name followed by an equals sign and the value. For example, the following code calls the say_hello
function with a keyword argument:
say_hello(name="John")
9. What is a lambda function in Python?
A lambda function in Python is an anonymous function that can be defined in a single line of code. Lambda functions are useful for creating small, one-time use functions. The syntax for defining a lambda function is to use the lambda
keyword.
Here is an example of a lambda function in Python:
# A lambda function that multiplies two numbers
multiply = lambda x, y: x * y
# Call the lambda function and print the
result
result = multiply(3, 4)
print(result)
This code defines a lambda function called multiply
that takes two arguments, x
and y
, and returns their product. The lambda function is then called with the values 3
and 4
, and the result is printed to the console. The output of this code would be 12
.
# A list of dictionaries representing people and their ages
people = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 20}
]
# Sort the list of dictionaries by age using a lambda function
sorted_people = sorted(people, key=lambda person: person["age"])
# Print the sorted list of dictionaries
print(sorted_people)
In this code, the sorted()
function is used to sort a list of dictionaries called people
based on the age
key of each dictionary. The key
argument of the sorted()
function is set to a lambda function that takes a person
argument and returns the value of the age
key of that person’s dictionary. The lambda function is used to tell the sorted()
function how to compare the dictionaries for sorting. The output of this code would be:
[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
This shows how lambda functions can be used in a variety of contexts, such as sorting, filtering, and mapping data.
Yes, the main()
function does exist in Python. However, unlike in some other programming languages such as C, the main()
function in Python is not a required element of a program. Instead, Python programs can be executed without explicitly defining a main()
function.
That being said, it is still common practice to define a main()
function in Python programs to serve as an entry point for the program and to organize the code into logical blocks. Additionally, if a Python module is designed to be run as a standalone program, it is often recommended to include an if __name__ == "__main__":
block to ensure that the code inside the main()
function is only executed when the module is run as a script and not imported as a module.
————————————————————————————————————————
- Also Read in COMPUTER SCIENCE CLASS 12 CBSE
PYTHON: Data Types
How to Learn Python free online
Syllabus : computer science with python
Cloud computing
Also Read in PHYSICS CLASS 12 CBSE
Important Concepts Electrostatic Chapter 2 : Electric potential and capacitance
physics reduced syllabus class 12 cbse 2020-21
Important notes and questions Class 12 Physics : electric charge and electric field