Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List
  • Python Tuple
  • Python String
  • Python Sets
  • Python Dictionary

Python Functions

Python Function Arguments

  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension

Python Lambda/Anonymous Function

  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures

Python Decorators

  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python User-defined Functions

A function is a block of code that performs a specific task.

Suppose we need to create a program to make a circle and color it. We can create two functions to solve this problem:

  • function to create a circle
  • function to color the shape

Dividing a complex problem into smaller chunks makes our program easy to understand and reuse.

  • Create a Function

Let's create our first function.

Here are the different parts of the program:

Create a Python Function

Here, we have created a simple function named greet() that prints Hello World!

Note: When writing a function, pay attention to indentation, which are the spaces at the start of a code line.

In the above code, the print() statement is indented to show it's part of the function body, distinguishing the function's definition from its body.

  • Calling a Function

In the above example, we have declared a function named greet() .

If we run the above code, we won't get an output.

It's because creating a function doesn't mean we are executing the code inside it. It means the code is there for us to use if we want to.

To use this function, we need to call the function.

Function Call

  • Example: Python Function Call

In the above example, we have created a function named greet() . Here's how the control of the program flows:

Python Function Working

  • When the function greet() is called, the program's control transfers to the function definition.
  • All the code inside the function is executed.
  • The control of the program jumps to the next statement after the function call.

Arguments are inputs given to the function.

Sample Output 1

Here, we passed ' John' as an argument to the greet() function.

We can pass different arguments in each call, making the function re-usable and dynamic.

Let's call the function with a different argument.

Sample Output 2

  • Example: Function to Add Two Numbers

In the above example, we have created a function named add_numbers() with arguments: num1 and num2 .

Python Function Argument

Parameters are the variables listed inside the parentheses in the function definition. They act like placeholders for the data the function can accept when we call them.

Think of parameters as the blueprint that outlines what kind of information the function expects to receive.

In this example, the print_age() function takes age as its input. However, at this stage, the actual value is not specified.

The age parameter is just a placeholder waiting for a specific value to be provided when the function is called.

Arguments are the actual values that we pass to the function when we call it.

Arguments replace the parameters when the function executes.

Here, during the function call, the argument 25 is passed to the function.

  • The return Statement

We return a value from the function using the return statement.

In the above example, we have created a function named find_square() . The function accepts a number and returns the square of the number.

How function works in Python?

Note: The return statement also denotes that the function has ended. Any code after return is not executed.

  • The pass Statement

The pass statement serves as a placeholder for future code, preventing errors from empty code blocks.

It's typically used where code is planned but has yet to be written.

Note : To learn more, visit Python Pass Statement .

  • Python Library Functions

Python provides some built-in functions that can be directly used in our program.

We don't need to create the function, we just need to call them.

Some Python library functions are:

  • print() - prints the string inside the quotation marks
  • sqrt() - returns the square root of a number
  • pow() - returns the power of a number

These library functions are defined inside the module. And to use them, we must include the module inside our program.

For example, sqrt() is defined inside the math module.

Note : To learn more about library functions, please visit Python Library Functions .

  • Example: Python Library Function

Here, we imported a math module to use the library functions sqrt() and pow() .

More on Python Functions

In Python, functions are divided into two categories: user-defined functions and standard library functions. These two differ in several ways:

User-Defined Functions

These are the functions we create ourselves. They're like our custom tools, designed for specific tasks we have in mind.

They're not part of Python's standard toolbox, which means we have the freedom to tailor them exactly to our needs, adding a personal touch to our code.

Standard Library Functions

Think of these as Python's pre-packaged gifts. They come built-in with Python, ready to use.

These functions cover a wide range of common tasks such as mathematics, file operations , working with strings , etc.

They've been tried and tested by the Python community, ensuring efficiency and reliability.

Python allows functions to have default argument values. Default arguments are used when no explicit values are passed to these parameters during a function call.

Let's look at an example.

Here, message has the default value of Hello . When greet() is called with only one argument, message uses its default value.

Note: To learn more about default arguments in a function, please visit Python Function Arguments .

We can handle an arbitrary number of arguments using special symbols *args and **kwargs .

*args in Functions

Using *args allows a function to take any number of positional arguments.

*kwargs in Functions

Using **kwargs allows the function to accept any number of keyword arguments.

To learn more, visit Python *args and **kwargs .

  • Python Recursive Function

Table of Contents

  • Introduction

Write a function to check if a given number is prime or not.

  • A prime number is only divisible by 1 and itself. For example, 13 .
  • Return True if the number is prime, otherwise return False .

Video: Introduction to Python Functions

Sorry about that.

Related Tutorials

Python Tutorial

Python Function Examples – How to Declare and Invoke with Parameters

Dionysia Lemonaki

Python has a bunch of helpful built-in functions you can use to do all sorts of stuff. And each one performs a specific task.

But did you know that Python also allows you to define your own functions?

This article will show you how to create and call your own Python functions. It will also give you an overview of how to pass input parameters and arguments to your functions.

What is a Function?

A function is an isolated block of code that performs a specific task.

Functions are useful in programming because they eliminate needless and excessive copying and pasting of code throught a program.

If a certain action is required often and in different places, that is a good indicator that you can write a function for it. Functions are meant to be reusable.

Functions also help organize your code.

If you need to make a change, you'll only need to update that certain function. This saves you from having to search for different pieces of the same code that have been scattered in different locations in your program by copying and pasting.

This complies with the DRY (Don't Repeat Yourself) principle in software development.

The code inside a function runs only when they the function is called.

Functions can accept arguments and defaults and may or not return values back to the caller once the code has run.

How to Define a Function in Python

The general syntax for creating a function in Python looks something like this:

Let's break down what's happening here:

  • def is a keyword that tells Python a new function is being defined.
  • Next comes a valid function name of your choosing. Valid names start with a letter or underscore but can include numbers. Words are lowercase and separated by underscores. It's important to know that function names can't be a Python reserved keyword.
  • Then we have a set of opening and closing parentheses, () . Inside them, there can be zero, one, or more optional comma separated parameters with their optional default values. These are passed to the function.
  • Next is a colon, : , which ends the function's definition line.
  • Then there's a new line followed by a level of indentation (you can do this with 4 spaces using your keyboard or with 1 Tab instead). Indentation is important since it lets Python know what code will belong in the function.
  • Then we have the function's body. Here goes the code to be executed – the contents with the actions to be taken when the function is called.
  • Finally, there's an optional return statement in the function's body, passing back a value to the caller when the function is exited.

Keep in mind that if you forget the parentheses () or the colon : when trying to define a new function, Python will let you know with a SyntaxError .

How to Define and Call a Basic Function in Python

Below is an example of a basic function that has no return statement and doesn't take in any parameters.

It just prints hello world whenever it is called.

Once you've defined a function, the code will not run on its own.

To execute the code inside the function, you have make a function invokation or else a function call .

You can then call the function as many times as you want.

To call a function you need to do this:

Here's a breakdown of the code:

  • Type the function name.
  • The function name has to be followed by parentheses. If there are any required arguments, they have to be passed in the parentheses. If the function doesn't take in any arguments, you still need the parentheses.

To call the function from the example above, which doesn't take in any arguments, do the following:

How to Define and Call Functions with Parameters

So far you've seen simple functions that don't really do much besides printing something to the console.

What if you want to pass in some extra data to the function?

We've used terms here like parameter and arguments .

What are their definitions exactly?

Parameters are a named placeholder that pass information into functions.

They act as variables that are defined locally in the function's definition line.

In the example above, there is one parameter, name .

We could've used f-string formatting instead – it works the same way as the previous example:

There can be a list of parameters inside the parentheses, all separated by commas.

Here, the parameters in the function are name and age .

When a function is called, arguments are passed in.

Arguments, like parameters, are information passed to functions.

In particular, they are the actual values that correspond to the parameters in the function definition.

Calling the function from a previous example and passing in an argument would look like this:

The function can be called many times, passing in different values each time.

The arguments presented so far are called positional arguments .

All positional arguments are very much required .

The number of positional arguments matters

When calling functions, you need to pass the correct number of arguments, otherwise there will be an error.

When it comes to positional arguments, the number of arguments passed in to the function call has to be exactly the same as the number of parameters in the function's definition.

You can't leave any out or add in any more.

Say that you have this function that takes in two parameters:

If the function is called with just one argument passed in, like this, there will be an error:

If the function is called with three arguments passed in, there will again be an error:

There will also be an error if we pass in no arguments.

Instead, we need two arguments, since two parameters are listed in the function definition.

The order of positional arguments matters

Besides including the correct number of arguments, it is important to note that the order in which the arguments are passed in matters.

Arguments need to be passed in the exact same order as the order of the parameters that have been declared in the function's definition.

It works like variable assignment.

The first argument is the value of the first parameter in the function's definition. The second argument is the value of the second parameter in the function's ddefinition – and so on.

If the order is not correct, the output might not make much sense and not be what you intended it to be.

How to use keyword arguments in Python functions

So far you've seen one type of argument, positional arguments.

With positional arguments, functions are called with just the values passed in the function call. There, each value directly corresponds with the number, order, and position of each parameter in the function definition.

However, functions in Python can accept another type of argument, that is keyword arguments .

In this case, instead of just passing in values in the function call, you instead specify the name of the parameter and then the value you want to assign it, in the form of key = value .

Each key matches each parameter in the function definition.

Explicitely calling the name of parameters and the values they take helps in being extra clear about what you're passing in and avoids any possible confusion.

Keyword arguments, as seen above, can be in a particular order. But they are more flexible than positional arguments in the sense that order of arguments now does not matter.

So you could do this and there would be no errors:

But you still have to give the correct number of arguments.

You can use both positional and keyword arguments together in a function call, like the example below where there is one positional argument and one keyword argument:

In this case, order matters again.

Positional arguments always come first and all keyword arguments should follow the positional arguments. Otherwise there will be an error:

How to define a parameter with a default value in Python

Function arguments can also have default values. They are known as default or optional arguments .

For a function argument to have a default value, you have to assign a default value to the parameter in the function's definition.

You do this with the key=value form, where value will be the default value for that parameter.

As you see, default arguments are not required in the function call, and the value of language will always default to Python if another value isn't provided in the call.

However, default values can be easily overriden if you provide another value in the function's call:

There can be more than one default value passed to the function.

When the function is called, none, one, some, or all of the default arguments can be provided and order does not matter.

Default arguments can be combined with non-default arguments in the function's call.

Here is a function that accepts two arguments: one positional, non-default ( name ) and one optional, default ( language ).

The default argument, langyage="Python" , is optional . But the positional argument, name , will always always required. If another language is not passed in, the value will always default to Python.

Another thing to mention here is that, when defaults and non defaults are used together, the order they are defined in the function defintion matters.

All the positional arguments go first and are followed by the default arguments.

This will not work:

In this article, you learned how to declare functions and invoke them with parameters in the Python programming language.

This was an introduction on how to create simple functions and how to pass data into them, with parameters. We also went over the different types of arguments like positional , keyword , and default arguments.

  • The order and number of positional arguments matters.
  • With keyword arguments, order does not matter. Number does matter, though, since each keyword argument corresponds with each parameter in the function's definition.
  • Default arguments are entirely optional. You can pass in all of them, some of them, or none at all.

If you are interested in going more in-depth and learning more about the Python programming language, freeCodeCamp has a free Python certification .

You'll start from the basics and fundamentals of the language and then progress to more advanced concepts like data structures and relational databases. In the end you'll build 5 projects to put to practice what you've learnt.

Thank you for reading and happy learning.

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Home » Python OOP » Python Class Methods

Python Class Methods

Summary : in this tutorial, you’ll learn about Python class methods and when to use them appropriately.

Introduction to Python class methods

So far, you learned about instance methods that are bound to a specific instance of a class .

Instance methods can access instance variables within the same class. To invoke instance methods, you need to create an instance of the class first.

The following defines the Person class:

The Person class has three instance methods including __init__() , get_full_name() , and introduce() .

Suppose that you want to add a method that creates an anonymous person to the Person class.

In order to do so, you would come up with the following code:

The create_anonymous() is an instance method that returns an anonymous person.

However, to invoke the create_anonymous() method, you need to create an instance, which doesn’t make sense in this case.

This is why Python class methods come into play.

A class method isn’t bound to any specific instance. It’s bound to the class only.

To define a class method:

  • First place the @classmethod decorator above the method definition. For now, you just need to understand that the @classmethod decorator will change an instance method to a class method.
  • Second, rename the self parameter to cls . The cls means class . However, class is a keyword so you cannot use it as a parameter.

The following shows the new version of the Person class:

The create_anonymous() method cannot access instance attributes. But it can access class attributes via the cls variable.

Calling Python class methods

To call a class method, you use the class name, followed by a dot, and then the method name like this:

The following example shows how to call the create_anonymous() class method of the Person class:

Class methods vs. instance methods

The following table illustrates the differences between class methods and instance methods:

When to use Python class methods

You can use class methods for any methods that are not bound to a specific instance but the class. In practice, you often use class methods for methods that create an instance of the class.

When a method creates an instance of the class and returns it, the method is called a factory method . For example, the create_anonymous() is a factory method because it returns a new instance of the Person class.

  • Python class methods aren’t bound to any specific instance, but classes.
  • Use @classmethod decorator to change an instance method to a class method. Also, pass the cls as the first parameter to the class method.
  • Use class methods for factory methods.
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Lists

  • Get a list as input from user in Python
  • Python | Create list of numbers with given range
  • How to add Elements to a List in Python

Python List Access/Iteration Operations

  • Iterate over a list in Python
  • How to iterate through a nested List in Python?
  • Python | Iterate over multiple lists simultaneously
  • Iterate Over a List of Lists in Python
  • Python Program to Accessing index and value in list
  • Python | Accessing all elements at given list of indexes
  • Check if element exists in list in Python
  • Python | Check if any element in list satisfies a condition

Python List Search Operations

  • How To Find the Length of a List in Python
  • Python | Find elements of a list by indices
  • Python program to find the String in a List
  • Python | Ways to find indices of value in list
  • Python | Find most frequent element in a list

Python List Remove Operations

  • How to Remove an Item from the List in Python
  • Python | Remove given element from the list
  • Ways to remove particular List element in Python
  • Remove multiple elements from a list in Python

Python List Concatenation Operations

  • Python | Concatenate two lists element-wise
  • Merge Two Lists in Python
  • Python - Concatenate two list of lists Row-wise
  • Python program to concatenate every elements across lists
  • Python program to Concatenate all Elements of a List into a String
  • Python | Concatenate All Records
  • Python | Merge list elements
  • Python | Concatenate N consecutive elements in String list
  • Python | Merge two lists alternatively
  • Python | Union of two or more Lists

Python List Sorting and Comparison

  • Python | Sort a List according to the Length of the Elements
  • Python | Element repetition in list
  • Python - Repeat Alternate Elements in list
  • Python | Difference between two lists
  • Python | Check if two lists are identical
  • Python | Combining two sorted lists
  • Python | Cloning or Copying a list
  • Sort the values of first list using second list in Python

Python List Comprehension Operations

  • Python List Slicing
  • Python - List Comprehension
  • Python List Comprehension and Slicing

Python List Reverse Operations

  • Python List reverse()
  • Reversing a List in Python

Python Nested Lists

  • Nested List Comprehensions in Python
  • Python | Test for nested list
  • Python | How to copy a nested list
  • Python | Convert given list into nested list
  • Python | Split nested list into two lists
  • Python - Nested List to single value Tuple
  • Python | Column wise sum of nested list
  • Python | Intersection of two nested list
  • Python | Check if a nested list is a subset of another nested list

Python List Flatten Operation

  • Python - Flatten List to individual elements
  • Python | Convert a nested list into a flat list
  • Python Program to Flatten a List without using Recursion
  • Python | Sort Flatten list of list
  • Flatten A List of Lists in Python
  • Python | Split flatten String List
  • Python | Flatten given list of dictionaries
  • Python | Grouped Flattening of list
  • Python | Ways to flatten a 2D list

Python List Methods and Exercises

  • Find size of a list in Python
  • Python - Elements Lengths in List
  • Python List Exercise
  • Python List methods

Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). In simple language, a Python list is a collection of things, enclosed in [ ] and separated by commas. 

The list is a sequence data type which is used to store the collection of data. Tuples and String are other types of sequence data types.

Example of list in Python

Here we are creating Python List using [].

Lists are the simplest containers that are an integral part of the Python language. Lists need not be homogeneous always which makes it the most powerful tool in Python . A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation.

Creating a List in Python

Lists in Python can be created by just placing the sequence inside the square brackets[]. Unlike Sets , a list doesn’t need a built-in function for its creation of a list. 

Note: Unlike Sets, the list may contain mutable elements.  

Example 1: Creating a list in Python

Complexities for creating lists.

Time Complexity: O(1)

Space Complexity: O(n)

Example 2:  Creating a list with multiple distinct or duplicate elements

A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values can be passed as a sequence at the time of list creation.

Accessing elements from the List

In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. The index must be an integer. Nested lists are accessed using nested indexing. 

Example 1: Accessing elements from list

Example 2: Accessing elements from a multi-dimensional list

Negative indexing

In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.

Complexities for Accessing elements in a Lists:

Space Complexity: O(1)

Getting the size of Python list

Python len() is used to get the length of the list.

Taking Input of a Python List

We can take the input of a list of elements as string, integer, float, etc. But the default one is a string.

Example 1: 

To know more see this .

Adding Elements to a Python List

Method 1: using append() method.

Elements can be added to the List by using the built-in append() function. Only one element at a time can be added to the list by using the append() method, for the addition of multiple elements with the append() method, loops are used. Tuples can also be added to the list with the use of the append method because tuples are immutable. Unlike Sets, Lists can also be added to the existing list with the use of the append() method.

Complexities for Adding elements in a Lists(append() method):

S pace Complexity: O(1)

Method 2: Using insert() method

append() method only works for the addition of elements at the end of the List, for the addition of elements at the desired position, insert() method is used. Unlike append() which takes only one argument, the insert() method requires two arguments(position, value). 

Complexities for Adding elements in a Lists(insert() method):

Time Complexity: O(n)

Method 3: Using extend() method

Other than append() and insert() methods, there’s one more method for the Addition of elements, extend() , this method is used to add multiple elements at the same time at the end of the list.

Note: append() and extend() methods can only add elements at the end.

Complexities for Adding elements in a Lists(extend() method):

Reversing a list, method 1:  a list can be reversed by using the reverse() method in python ., method 2: using the reversed() function:.

The reversed() function returns a reverse iterator, which can be converted to a list using the list() function.

Removing Elements from the List

Method 1: using remove() method.

Elements can be removed from the List by using the built-in remove() function but an Error arises if the element doesn’t exist in the list. Remove() method only removes one element at a time, to remove a range of elements, the iterator is used. The remove() method removes the specified item.

Note: Remove method in List will only remove the first occurrence of the searched element.

Complexities for Deleting elements in a Lists(remove() method):

Method 2: using pop() method.

pop() function can also be used to remove and return an element from the list, but by default it removes only the last element of the list, to remove an element from a specific position of the List, the index of the element is passed as an argument to the pop() method.

Complexities for Deleting elements in a Lists(pop() method):

Time Complexity: O(1)/O(n) (O(1) for removing the last element, O(n) for removing the first and middle elements)

Slicing of a List

We can get substrings and sublists using a slice. In Python List, there are multiple ways to print the whole list with all the elements, but to print a specific range of elements from the list, we use the Slice operation . 

Slice operation is performed on Lists with the use of a colon(:). 

To print elements from beginning to a range use:

To print elements from end-use:

To print elements from a specific Index till the end use 

To print the whole list in reverse order, use 

Note – To print elements of List from rear-end, use Negative Indexes. 

python-list-slicing

UNDERSTANDING SLICING OF LISTS:

  • pr[0] accesses the first item, 2.
  • pr[-4] accesses the fourth item from the end, 5.
  • pr[2:] accesses [5, 7, 11, 13], a list of items from third to last.
  • pr[:4] accesses [2, 3, 5, 7], a list of items from first to fourth.
  • pr[2:4] accesses [5, 7], a list of items from third to fifth.
  • pr[1::2] accesses [3, 7, 13], alternate items, starting from the second item.

Negative index List slicing

List comprehension.

Python List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. 

newList = [ expression(element) for element in oldList if condition ]

Example:  

For better understanding, the above code is similar to as follows: 

Refer to the below articles to get detailed information about List Comprehension.

  • List comprehension and ord() in Python

Basic Example on Python List

  • Python program to interchange first and last elements in a list
  • Python program to swap two elements in a list
  • Python – Swap elements in String list
  • Python | Ways to find length of list
  • Maximum of two numbers in Python
  • Minimum of two numbers in Python

To Practice the basic list operation, please read this article – Python List of program

List Methods

To know more refer to this article – Python List methods

The operations mentioned above modify the list Itself.

Built-in functions with List

Do go through recent articles on Lists

Useful Links:  

  • Recent Articles on Python List
  • Python Tutorials
  • Multiple Choice Questions
  • All articles in Python Category

Please Login to comment...

Similar reads.

  • python-list

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Hire Odoo Developer
  • Odoo Customization
  • Odoo Implementation
  • Odoo Integration
  • Odoo Migration
  • Odoo Support
  • Odoo Pricing
  • Odoo Success Pack
  • Odoo Licensing Consultancy
  • Odoo Training
  • Odoo Consultancy
  • Odoo Hosting
  • Manufacturing
  • Restaurant Management
  • E-commerce Website
  • Hotel Management
  • Service Management
  • Accounting & Finance
  • Warehouse Management
  • Human Resource
  • Project Management
  • Point of Sale
  • Customer Relationship (CRM)
  • Sales Management
  • Purchase Management
  • Odoo Community VS Enterprise
  • Odoo VS SAP
  • Odoo VS Ms. Dynamics
  • Odoo VS ERP Next
  • Odoo VS Netsuite
  • Odoo VS Sage
  • Odoo VS Zoho CRM
  • Odoo VS Sugar CRM
  • Odoo Community Features
  • Odoo Enterprise Features
  • Odoo Freelancer VS Partner
  • Odoo Book New-V17
  • Odoo Development Tutorial
  • Odoo Partner
  • Odoo Case Studies
  • Odoo 17 Features

odoo-book

  • Implementation
  • Customization
  • Employee Staffing
  • Hire Python Developer
  • Cybrosian's Life
  • View our Company

how-to-use-flush-and-close-function-in-python-file-handling.jpg

How to Use Flush & Close Function in Python File Handling

Flush() method.

When you use flush(), it doesn't clean out the original file, it only clears what's in the buffer inside.

Basic flush() Usage

Using Flush() in a loop

close() Method

In Python, the close() method shuts down the file that's currently open. It's widely understood that when a file is opened for a specific purpose, it should be closed once that purpose is fulfilled. This helps prevent the operating system from having too many open files, which could exceed its set limit. 

After a file is closed, it becomes inaccessible for reading or writing. Attempting any operation on a closed file will result in a ValueError because the file must be open for any action to take place.

The close() method can be called multiple times in a single program.

After running the program mentioned earlier, the text written using the write() method appears in the example.txt file as depicted below.

Note:  Once the file is closed, it's not possible to carry out any operations on it. Trying to do so will result in a ValueError being raised. For example,

We'll compile and execute the provided program to generate the following output:

In conclusion, the flush() function in Python ensures the immediate writing of data from the internal buffer to the file, facilitating prompt data persistence. This is particularly useful when you need to guarantee that data is saved without delay, even before closing the file. On the other hand, the close() function terminates the file, making it inaccessible for further reading or writing. It's crucial to close files once their purpose is fulfilled to prevent resource wastage and potential system errors.

To read more about How to Setup Odoo 17 Development Environment Using Pycharm in Ubuntu 20.04, refer to our blog How to Setup Odoo 17 Development Environment Using Pycharm in Ubuntu 20.04

Odoo Training Package

If you need any assistance in odoo, we are online, please chat with us.

whatsapp

Share this article:

favicon

Related Blogs

 How to Import Customers & Vendors in Odoo 17

How to Import Customers & Vendors in Odoo 17

 How to Add a Search Filter for Computed Fields in Odoo 17

How to Add a Search Filter for Computed Fields in Odoo 17

 How to Add Watermark in PDF Reports in Odoo 17

How to Add Watermark in PDF Reports in Odoo 17

 How to Configure the Checkout Process of Guests in Odoo 17 Website App

How to Configure the Checkout Process of Guests in Odoo 17 Website App

 How to Setup Subcontracting in Odoo 17 Manufacturing

How to Setup Subcontracting in Odoo 17 Manufacturing

Leave a comment, odoo 17 webinar.

odo-17-webinar

Cybro Awards 2023

cybrosys-awards-2023

Available at Amazon

odoo-udemy

Recent Posts

whatsapp

Cybrosys Technologies Pvt. Ltd. Neospace, Kinfra Techno Park Kakkancherry, Calicut Kerala, India - 673635

Cybrosys Limited Alpha House, 100 Borough High Street, London, SE1 1LB, United Kingdom

Cybrosys Technologies Pvt. Ltd. 1st Floor, Thapasya Building, Infopark, Kakkanad, Kochi, India - 682030.

Cybrosys Techno Solutions The Estate, 8th Floor, Dickenson Road, Bangalore, India - 560042

Quick Links

  • Odoo Partners
  • Buy Source code
  • Odoo Licensing
  • Odoo Software
  • Odoo vs SAP
  • Odoo vs Dynamics
  • Odoo vs ERP Next
  • Odoo vs Netsuite
  • Odoo vs Sage
  • Odoo vs Sugar CRM
  • Odoo vs Zoho CRM

STAY IN TOUCH

phone

Connect socially

facebook

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python object methods, object methods.

Objects can also contain methods. Methods in objects are functions that belong to the object.

Let us create a method in the Person class:

Insert a function that prints a greeting, and execute it on the p1 object:

Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.

Related Pages

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. PYTHON

    how to write python method

  2. A Beginner Guide For Python String Method

    how to write python method

  3. how to write python method

    how to write python method

  4. 10 Easy Steps: How to Write to a Text File in Python 2024

    how to write python method

  5. Methods in Python with Examples

    how to write python method

  6. What is Methods and Functions in Python

    how to write python method

VIDEO

  1. Python's insert method in list #coding

  2. 1.Python Programming: An Introduction for Beginners

  3. Creating & Running Your First Python Script

  4. Python String Methods part 3 #python3 #pythonforbeginners #pythontutorial #pythonlearning

  5. Write a python program stack implementation of list using python program

  6. Python Tutorial: Understanding the __init__ Method

COMMENTS

  1. Methods in Python with Examples

    Static methods in Python. To create a static method, we need to use the decorator @staticmethod. Similar to class methods, static methods can also be accessed either by the class name or the object name. For Example. class Student: no_of_students = 10. def __init__(self, name, age): self.name = name. self.age = age.

  2. Python Functions

    Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside ...

  3. What is a "method" in Python?

    In Python, a method is a function that is available for a given object because of the object's type. For example, if you create my_list = [1, 2, 3], the append method can be applied to my_list because it's a Python list: my_list.append(4). All lists have an append method simply because they are lists.

  4. Python Functions (With Examples)

    We don't need to create the function, we just need to call them. Some Python library functions are: print () - prints the string inside the quotation marks. sqrt() - returns the square root of a number. pow () - returns the power of a number. These library functions are defined inside the module.

  5. Documenting Python Code: A Complete Guide

    Documenting your Python code is all centered on docstrings. These are built-in strings that, when configured correctly, can help your users and yourself with your project's documentation. Along with docstrings, Python also has the built-in function help() that prints out the objects docstring to the console.

  6. Define and Call Methods in a Python Class

    Define And Call Methods In A Class In Python. Let's look at how to define and call methods in a class with the help of examples. Example 1: Simple Class with a Method. In this example, we define a class GeeksClass with a method say_hello. The say_hello method simply prints the message "Hello, Geeks!" when called.

  7. Python Functions: How to Call & Write Functions

    The four steps to defining a function in Python are the following: Use the keyword def to declare the function and follow this up with the function name. Add parameters to the function: they should be within the parentheses of the function. End your line with a colon. Add statements that the functions should execute.

  8. Python Classes: The Power of Object-Oriented Programming

    In this code snippet, you define Circle using the class keyword. Inside the class, you write two methods. The .__init__() method has a special meaning in Python classes. This method is known as the object initializer because it defines and sets the initial values for your attributes. You'll learn more about this method in the Instance Attributes section.

  9. Python Function Examples

    How to Define a Function in Python. The general syntax for creating a function in Python looks something like this: def function_name(parameters): function body. Let's break down what's happening here: def is a keyword that tells Python a new function is being defined. Next comes a valid function name of your choosing.

  10. Python Method

    Python Method. A Python method is like a Python function, but it must be called on an object. And to create it, you must put it inside a class. Now in this Car class, we have five methods, namely, start(), halt(), drift(), speedup(), and turn(). In this example, we put the pass statement in each of these, because we haven't decided what to do ...

  11. Python Class Methods

    To define a class method: First place the @classmethod decorator above the method definition. For now, you just need to understand that the @classmethod decorator will change an instance method to a class method. Second, rename the self parameter to cls. The cls means class.

  12. Python Functions

    Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.

  13. How to Use Python: Your First Steps

    Why You Should Use Python. Python, named after the British comedy group Monty Python, is a high-level, interpreted, interactive, and object-oriented programming language. Its flexibility allows you to do many things, both big and small.With Python, you can write basic programs and scripts and also to create complex and large-scale enterprise solutions.

  14. 9. Classes

    9. Classes ¶. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.

  15. Python Class Method Explained With Examples

    Example 2: Create Class Method Using classmethod () function. Apart from a decorator, the built-in function classmethod() is used to convert a normal method into a class method. The classmethod() is an inbuilt function in Python, which returns a class method for a given function. Syntax:

  16. Python Tutorial

    Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python ... write, and delete files. Python File Handling. Python Database Handling. In our database section you will learn how to access and work with MySQL and ...

  17. 7. Input and Output

    (Note that the one space between each column was added by the way print() works: it always adds spaces between its arguments.). The str.rjust() method of string objects right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods str.ljust() and str.center().These methods do not write anything, they just return a new string.

  18. Python Static Method With Examples

    In Object-oriented programming, at the class level, we use class methods and static methods.. Class methods: Used to access or modify the state of the class. if we use only class variables, we should declare such methods as a class method.; Static methods: A static method is a general utility method that performs a task in isolation.Inside this method, we don't use instance or class variable ...

  19. Mastering Python: 7 Strategies for Writing Clear, Organized, and

    The method returns an object of type <class generator>. When we iterate over this object, it continues execution from where the last yield statement is. Therefore, a single document is loaded and processed, improving Python code efficiency. ... How To Write Efficient Python Code: A Tutorial for Beginners; Announcing a Blog Writing Contest ...

  20. Defining Main Functions in Python

    Execution Modes in Python. There are two primary ways that you can instruct the Python interpreter to execute or use code: You can execute the Python file as a script using the command line.; You can import the code from one Python file into another file or into the interactive interpreter.; You can read a lot more about these approaches in How to Run Your Python Scripts.

  21. Python Lists

    Adding Elements to a Python List Method 1: Using append() method. Elements can be added to the List by using the built-in append() function. Only one element at a time can be added to the list by using the append() method, for the addition of multiple elements with the append() method, loops are used. ... Write and publish your own Article ...

  22. 8. Errors and Exceptions

    The try statement works as follows. First, the try clause (the statement (s) between the try and except keywords) is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished. If an exception occurs during execution of the try clause, the rest of the clause is skipped.

  23. Object-Oriented Programming (OOP) in Python 3

    When writing your own classes, it's a good idea to have a method that returns a string containing useful information about an instance of the class. However, .description() isn't the most Pythonic way of doing this. When you create a list object, you can use print() to display a string that looks like the list:

  24. How to Read and Write With CSV Files in Python?

    Steps to read a CSV file using csv reader: The . open () method in python is used to open files and return a file object. The type of file is " _io.TextIOWrapper " which is a file object that is returned by the open () method. Create an empty list called a header. Use the next () method to obtain the header.

  25. How to Use Flush & Close Function in Python File Handling

    fo.write("Hello World") ValueError: I/O operation on closed file. In conclusion, the flush () function in Python ensures the immediate writing of data from the internal buffer to the file, facilitating prompt data persistence. This is particularly useful when you need to guarantee that data is saved without delay, even before closing the file.

  26. Python Object Methods

    Python File Handling Python Read Files Python Write/Create Files Python Delete Files Python Modules ... Object Methods. Objects can also contain methods. Methods in objects are functions that belong to the object. Let us create a method in the Person class: Example.

  27. Answered: Python help. 38) What method of…

    Using python 1.Assume the variable dct references a dictionary (create dct first). Write an if statement that determines whether the key 'Jim' exists in the dictionary. If so, delete 'Jim' and its associated value. (write as a function) 2. Assume the variable dct references a dictionary.

  28. Reading and Writing Files in Python (Guide)

    Let's say you wanted to access the cats.gif file, and your current location was in the same folder as path.In order to access the file, you need to go through the path folder and then the to folder, finally arriving at the cats.gif file. The Folder Path is path/to/.The File Name is cats.The File Extension is .gif.So the full path is path/to/cats.gif. ...