A method is called by its name but it is associated with an object (dependent). It is implicitly passed to an object on which it is invoked. It may or may not return any data. A method can operate the data (instance variables) that is contained by the corresponding class.
What does a method look like?
Basic Python method
class class_name def method_name(): ………… # method body …………
Example of method
class Meth: def method_meth (self): print ("This is a method_meth of Meth class.") class_ref = Meth() #object of Meth class class_ref.method_meth() This is a method_meth of Meth class.
Functions
The function is a block of code that is also called by its name (independent). A function can have different parameters or may not have any at all. If any data (parameters) are passed, they are passed explicitly. It may or may not return any data. The function does not deal with class and its instance concept.
How does a function look like?
def function_name(arg1, arg2, ….): ………….. #function body …………..
Rules for defining a function in Python
- Function block should always begin with the keyword ‘def, followed by the function name and parentheses.
- We can pass any number of parameters or arguments inside the parentheses.
- The block of a code of every function should begin with a colon (:)
- An optional ‘return’ statement to return a value from the function
Example of function
def Add (a,b): return(a+b) print(Add(50,70)) print(Add(150,50)) Output: 120 200
Difference between Method and Function – Method vs. Function
Function and method both look similar as they perform in an almost similar way, but the key difference is the concept of ‘Class and its Object’. Functions can be called only by its name, as it is defined independently. But methods cannot be called by its name only we need to invoke the class by reference of that class in which it is defined, that is, the method is defined within a class and hence they are dependent on that class.
Functions in Python
A function is an organized block of statements or reusable code that is used to perform a single/related action. Python programming three types of functions:
- Built-in/library functions
- User-defined functions
- Anonymous functions
Built-in functions in Python
In total, there are 69 built-in functions in Python. They are:
abs() delattr() hash() memoryview() set() all( dict() help() min() setattr() any() dir() hex() next() slice() ascii() divmod() id() object() sorted() bin() enumerate() input() oct() staticmethod() bool() eval() int() open() str() breakpoint() exec() isinstance() ord() sum() bytearray() filter() issubclass() pow() super() bytes() float() iter() print() tuple() callable() format() len() property() type() chr() frozenset() list() range() vars() classmethod() getattr() locals() repr() zip() compile() globals() map() reversed() __import__() complex() hasattr() max() round()
User-defined functions in Python
There are 4 steps in the construction of a user-defined function in Python:
- Use the keyword “def” to declare a user-defined function following up the function name
- Adding parameters to the function, and ending the line with a colon
- Adding statements that the function should execute
- Ending a function with a return statement if you want a function should output something. If you do not use the return statement, then the function will return an object “none”
Example
def hello(): print("Hello World") return
Anonymous functions in Python
Anonymous functions in python cannot be declared in an ordinary manner which means they are not defined using the “def” keyword. These functions don’t have a body and are not required to call. Hence, they can be directly declared using the “lambda” keyword. It also helps in shortening the code. Lambda function can have n number of arguments but has a single return value that is represented in the form of expression. Lambda function does not need commands or multiple expressions. This kind of anonymous function cannot be called directly for the output. As a Python coder, you can initialize your own local namespace and the inline statements are equivalent to C/C++, the purpose of which is bypassing function stack allocation.
Syntax
lambda [arg1 [,arg2,.....argn]]:expression
Example of Lambda function
The below example will demonstrate how a basic function is different from Lambda.
# normal function linear expression def lin(x): return 3*x + 2 print(lin(2)) # lambda function f = lambda x: 3*x + 2 print(f(2)) Output 8 8
The above example shows the presentation of a normal function and lambda function. As it can be clearly seen that giving logic in a normal function requires two steps but for anonymous functions, it can be represented in a single step.
Calling a function in Python
Calling a function means to execute a function that you have defined either directly from Python prompt or through another function (nested function).
Example
def greet(name): """ This function greets to the person passed in as a parameter """ print("Hello, " + name + ". Pythonists") greet('Codegnan') Output: Hello, Codegnan. Pythonists
Function Arguments
Python programming makes use of 4 types of function arguments:
- Required argument
- Keyword argument
- Default argument
- Variable-length argument
Required argument
These are the arguments that are passed in sequential order to a function. The only rule is that the number of arguments defined in a function should match with the function definition.
Example:
def addition(a, b): sum = a+b print("Sum after addition: ",sum) addition(5, 6) Output: Sum after addition: 11
Keyword argument
When the use of keyword arguments is done in a function call, the caller identifies the arguments by the argument name.
Example:
def language(lname): print(“We are learning a language called: ”, lname) language(lname = “Python”) Output: We are learning a language called: Python
Default argument
When a function is called without any arguments, then it uses the default argument.
Example:
def country(cName = “India”): print(“Current country is:”, cName) country(“New York”) country(“London”) country() Output: Current country is: New York Current country is: London Current country is: India
Variable-length arguments
If you want to process more arguments in a function than what you specified while defining a function, then these types of arguments can be used.
Example:
def add(*num): sum = 0 for n in num: sum = n+sum print(“Sum is:”, sum) add(2, 5) add(5, 3, 5) add(8, 78, 90) Output: Sum is: 7 Sum is: 13 Sum is: 176
Time to implement – Function Exercises
With this article, you have learned about functions in Python and the difference between methods and functions. Now, it’s time to get your hands dirty with some practical examples to introspect what you have learned until now!
Write a python function that takes in a person’s name, and prints out a greeting. The greeting must be at least three lines, and the person’s name should come in each line. Use your function to greet at least three different people. [Tip: Save your three people in a list, and call your function from a for loop]
Write a function that takes in a first name and the last name, and prints out a nicely formatted full name, in a sentence. Your sentence could be as simple as, “Hello, full_name.” Call your function three times, with a different name each time.
Write a function that takes in two numbers, and adds them together. Make your function print out a sentence showing the two numbers, and the result. Call your function with three different sets of numbers.
Modify Addition Calculator so that your function returns the sum of the two numbers. The printing should be outside of the function. I hope this article has helped you in learning the fundamentals of Python functions. I hope you are clear with the topic now, and soon I will come up with a few more blogs on python.