Python Functions and Methods
Python Functions:
A function is a block of code that performs a task, and it can be called anywhere in your program.
Syntax:
def function_name(): #function definition
#your code goes here
function_name() #function call
Example:
create a program to find a max number between these 2 no(10,20) without using max method and use custom function.
#Function definition
def maximum():
marksofenglish = 10
marksofscience = 20
result = marksofenglish if marksofenglish > marksofscience else marksofscience
print(result)
#Function call
maximum()
#output: 20
Explanation:
def maximum():
This line defines a function named maximum. A function is a reusable block of code that performs a specific task. In this case, the task is finding the maximum between two values. The function doesn’t take any arguments in this case.
marksofenglish = 10
marksofscience = 20
Inside the function, a variable marksofenglish is created and assigned the value 10 and marksofscience is created and assigned 20.
result = marksofenglish if marksofenglish > marksofscience else marksofscience
This line uses a ternary conditional operator to compare marksofenglish and marksofscience.
The expression checks: “If marksofenglish is greater than marksofscience, assign marksofenglish to the variable result. Otherwise, assign marksofscience to result.”
In this case, marksofscience is greater, so the result variable is assigned the value 20.
print(result)
This line prints the value of the result. Since the result is 20 (because marksofscience is greater), the output will be 20.
maximum()
This line calls (executes) the function maximum(). When the function is called, the code inside the function is executed, and the result (20) is printed.
Note: function call is very important, if you create or define a function and don’t call it, it won’t execute.
Python Methods:
In Python, methods are functions that are defined inside a class and are used to perform operations on objects or interact with the data of that class.
Syntax:
class class_name:
def method_name(self): #method definition
#your code goes here
obj = class_name() # creating object
obj.method_name() #method call
Example 1:
class Greeting:
# A method that prints a greeting message
def say_hello(self):
print(“Hello, welcome to Python!”)
# Create an instance of the Greeting class
greet = Greeting()
# Call the method without any parameters
greet.say_hello()
Explanation:
class Greeting:
This line defines a class named Greeting.
def say_hello(self):
This line defines a method inside the Greeting class called say_hello
print(“Hello, welcome to Python!”)
Inside the say_hello method, we have the print() statement, which prints the message “Hello, welcome to Python!” when the method is called.
greet = Greeting()
Here, an instance of the Greeting class is created and stored in the variable greet.
greet.say_hello()
This line calls the say_hello() method on the greet instance.
Example 2: Explain in detail
class MathOperations:
# defining a method
def add(self, a, b):
return a + b
#def is keyword, add if method name and self,a and b are parameters.
#self parameter is compulsory, a and b are optional as per our need.
obj = MathOperations()
# Creating an object of MathOperations to use the method (add)
result_regular = obj.add(5, 10)
# Calling the method (add()) using object ‘obj’
print(f”Method Result: {result_regular}”)
#output: Method Result: 15
Explanation:
class MathOperations:
This line defines a class named MathOperations.
def add(self, a, b):
Here, a method named add is defined inside the MathOperations class using the keyword def.
return a + b
This line returns the sum of the two parameters, a and b, which are passed to the method when it’s called.
obj = MathOperations()
This line creates an object obj of the MathOperations class.
result_regular = obj.add(5, 10)
This line calls the add method of the MathOperations class using the object obj.
The numbers 5 and 10 are passed as arguments to the add method, where a = 5 and b = 10.
The result of 5 + 10 (which is 15) is returned and assigned to the variable result_regular.
print(f”Method Result: {result_regular}”)
This line prints the result of the add() method, which was stored in result_regular.
f”Method Result: {result_regular}” uses an f-string to format the string and include the value of result_regular in the output.
Basically, Method is the function inside a class with parameter self that is a reference to the current object. We will learn the self parameter in detail in __init__() method topic.
Difference between Function and Method
Function | Method |
---|---|
A standalone block of code that performs a task. | A function defined inside a class. |
Defined outside of classes. | Defined inside a class. |
Called by its name directly. (e.g. func_name()) | Called on an object (e.g., obj.method_name()). |
Does not require a self parameter. | Requires self to access object attributes. |
Independent of any class. | Always associated with an instance of a class. |
Tasks:
1. Create a function greet. Print hello world using this function.
2. Create a function check_greater(a,b). Take two parameters a and b and print the greater one.
3. Create a method get_remainder(a,b). Take two numbers as parameters and return the remainder of it.
4. Create a method employee_details(name,age,salary). Take three parameter name, age and salary and print it
5. Create a function Arithmetic(a,b). Take two parameters a and b and perform addition, subtraction, multiplication and division on it