While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Python is one of the most popular programming languages. In the last few years, it has gained a lot of popularity due to the increasing interest in Data Science, Deep Learning, Machine Learning, and Artificial Intelligence.
Just have a look at the Google Trends chart for interest in Python programming language. It’s increasing continuously and it will keep on increasing over time.
Python Tutorial can be broadly divided into the following categories.
|Python Tutorial for Beginners
|Brief information about Python programming language and its advantages. Learn how to install Python on Windows, Linux/Ubuntu and Mac OS operating systems.
|Python Keywords & Identifiers
|An article about keywords, identifiers and variables in Python. Learn about the rules for writing valid identifiers. Also read Global Variables in Python.
|Python comments and statements
|Quick introduction to different types of comments and statements with example code.
|Python Data Types
|Numeric, String, List, Tuple and Dict data types introduction.
|File Operations - Read, Write, Open, Close. Taking input from user and import statement.
|Arithmetic, Comparison, Bitwise, Logical, and Assignment Operators. Learn about the operator precedence in Python programming.
|Python Conditional Logic, examples of if-else and elif conditional logic.
|Python for loop
|Python for loop examples. Also, learn about nested for loops in Python.
|Python while loop
|Python while loop, nested while loop and infinite while loop examples.
|Python break continue
|A brief tutorial on Python break keyword and continue statement.
|Python pass statement
|Learn about pass statement and the best practices to use them in your code.
|Learn how to loop over a sequence, reverse looping, traversing through multiple sequences at once.
|Learn how to define a function in Python, different types of arguments
|How to implement recursion in Python, printing Fibonacci series using recursion.
|Python Anonymous Function
|What is Python Anonymous function? How and when to use anonymous function in Python.
|Understand what is a module in Python. Difference between module and package and how to import a module in your program.
|Quick introduction to Python packages and how to use them.
|Different types of numbers, type conversion and complex numbers in Python
|Python List functions - create, update, delete, append and iterate through elements.
|Learn about accessing tuple elements, update and delete tuple, important tuple functions.
|A brief introduction of String in Python and important Python string functions.
|Learn how to work with Set in Python.
|Python dictionary operations, accessing key-value pairs, deleting dict elements.
|Python file operations - read, open, write, delete and copy file.
|How to create, rename and delete a directory in Python.
|Python sort list
|Learn how to sort a List elements in Python, sort in decending order and with custom logic.
|Python List Comprehension
|Learn about Python List Comprehension to create list from some source sequence, string or list.
|Python try except
|Learn how to perform exception handling in Python using try-except block.
|Python Custom Exception
|How to create custom exception in Python.
|Python namespace and variable scope
|Everything about Python Classes, how to define them with variables, constructors, and functions.
|Learn about inheritance in Python, method overloading, super class and sub class.
|Python Multiple Inheritance
|Python Multiple Inheritance Example. What is the difference between Multiple Inheritance and Multi-level Inheritance, Method Resolution Order (MRO) and logic to resolve the Conflicts with python multiple inheritance.
|Python Operator Overloading
|Python allows us to overload operators to work with custom object. Learn how to use operator overloading in Python.
|Python Iterator protocol, iterable elements, creating custom iterator example program.
|Learn about yield keyword in Python to create generator functions that returns a series of arguments and work as an iterator.
|A slightly complex topic with nested functions where outer function returns the nested function and nested function does some work on the enclosed function arguments.
|Python decorator is a function that helps to add some additional functionalities to an already defined function.
|Python Array contains a sequence of data. In python programming, there is no exclusive array object because we can perform all the array operations using list.
|Python list append
|Short example for using list append() function in Python.
|Python string to int
|Learn about different ways to convert string to int and vice versa in Python.
|A look into Python variable declaration and their scope.
|A brief introduction to Python lambda keyword to create anonymous functions.
|Pyton metaclass introduction and how to create a metaclass.
|Python switch case
|Unlike many other famous programming languages, Python doesn’t have switch-case statement. However, we can write code using dictionary to simulate the same behavior.
|Python modulo operation is used to get the reminder of a division. The basic syntax of Python Modulo is a % b. Here a is divided by b and the remainder of that division is returned.
|Python assert statement
|Python assert statement takes a condition, the condition needs to be true. If the condition is true, then the program will run smoothly and the next statements will be executed. But, if the condition is false then it raises an exception.
|Python yield has almost same purpose as return keyword except that it returns the values one by one. This is very useful keyword when you need to return a huge number of values.
|Python doesn’t provide any implementation of Stack data structure. This example shows how to implement stack data structure in Python.
|PIP is a package management system used to install and manage software packages written in Python.
|A brief article on the ‘self’ argument present in Python class constructors.
|Python ternary operator
|Learn how to effectively use Python ternary operator to reduce boiler plate code.
|Python print format
|In this lesson, we will study about various ways for Python print format, through which we can print our data on the console and interpolate it.
|Python Command Line Arguments
|Python Command line arguments are input parameters passed to the script when executing them. Learn how to effectively read and parse command line parameters in Python.
|Python main function
|Learn the special technique to define main method in python program, so that it gets executed only when the program is run directly and not executed when imported as a module.
|Python Garbage Collection
|Python garbage collection is the memory management mechanism in python.
|Python XML Parser
|Python ElementTree XML API provides us easy way to read XML file and extract useful data.
|Python Join List to String
|We can use String join() function to concatenate a list of string with specified delimiter to create a new string.
|Python __init__() function
|A complete tutorial for Python class __init__() function.
|Python print to file
|Learn how to route Python print() function output to a file.
|Python static method
|In this Python tutorial, we will learn how to create Python static method. We will also look at advantages and disadvantages of static methods and comparison with the instance methods.
|Python Calculator Program
|In this Python tutorial, we will learn how to create a very simple python calculator program. We will take input from the user about the operation he wants to perform and show the result on its basis.
|Learn how to use @classmethod annotation to create Python class methods.
|Python Counter class is part of Collections module. Counter is a subclass of Dictionary and used to keep track of elements and their count.
|Python OrderedDict is a dict subclass that maintains the items insertion order. When we iterate over an OrderedDict, items are returned in the order they were inserted.
|Python namedtuple object is part of collections module. Python namedtuple is an extension of tuple.
|Python Catch Multiple Exceptions
|Sometimes we call a function that may throw multiple types of exceptions depending on the arguments, processing logic etc. In this tutorial, we will learn how to catch multiple exceptions in python.
|Python add to dictionary
|There is no explicitly defined method to add a new key to the dictionary. If you want to add a new key to the dictionary, then you can use assignment operator with dictionary key.
|Python Current Date Time
|We can use Python datetime module to get the current date and time of the local system. Python pytz is one of the popular module to get the timezone aware date time objects.
|Python strftime() function is present in datetime and time modules to create a string representation based on the specified format string.
|Python timedelta object is used to perform datetime manipulations in an easy way. The timedelta class is part of datetime module.
|Python date class is part of datetime module.
|Python wait for specific time
|Sometimes we want our python program to wait for a specific time before executing the next steps. We can use time module sleep() function to pause our program for specified seconds.
|Python string to datetime – strptime()
|We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.
|Python Complex Numbers
|A complex number is created from two real numbers. Python complex number can be created using complex() function as well as using direct assignment statement.
|Python Set Intersection
|Python Set Difference
|Python Set Union
|Python Set to List
|Python Reverse List
|Python Set Environment Variable
|Python *args and **kwargs
|Python Not Equal Operator
|Python Return statement
|Python and operator
|Python logical operators
|Python Bitwise Operators
|Python Comparison Operators
|Python input() function is used to get the user input from the console.
|Python zip function takes iterable elements as input, and returns iterator.
|Python super() function allows us to refer to the parent class explicitly. It’s useful in case of inheritance where we want to call super class functions.
|Python getattr() function is used to get the value of an object’s attribute and if no attribute of that object is found, default value is returned.
|Python type() function example to determine the type of the object.
|Python range() function examples to generate list of numbers.
|Python enumerate takes a sequence, and then make each element of the sequence into a tuple.
|This built-in function is used to create a floating point number. We can convert a string to floating point number using this function.
|One of the most widely used Python function to print the values to a stream, or to sys.stdout by default.
|Python hash() function returns the hash value of the object, which is a fixed size integer which identifies a particular value.
|Python __str__() and __repr__()
|Python __str__() function returns the string representation of the object. This method is called when print() or str() function is invoked on an object. Python __repr__() function returns the object representation. It could be any valid python expression such as tuple, dictionary, string etc.
|Python eval() function
|Python eval() function is used to parse an expression string as python expression and then execute it.
|Python exec() function provides support for dynamic code execution.
|Python chr(), ord()
|Python String join()
|Python string join() function is used to concatenate a sequence of strings to create a new string.
|Python string to Uppercase – str.upper()
|We can convert a string to uppercase in Python using str.upper() function.
|Python String to Lowercase – str.lower()
|We can convert a string to lowercase in Python using str.lower() function. In this short tutorial, we will learn how to convert python string to lowercase.
|Python String contains
|Python String class has __contains__() function that we can use to check if it contains another string or not.
|Python String split
|Python string split() function is used to split a string into the list of strings based on a delimiter.
|Python String replace()
|Python string replace() function is used to create a string by replacing some parts of another string.
|Python String format()
|Python String format() function is used to create a formatted string from the template string and the supplied values.
|Python String Template
|Python String Template class is used to create a simple template string, where fields can be replaced later on to create a string object.
|Python String to bytes
|Learn how to convert String to bytes and then bytes to String in Python.
|Python Check Variable is String
|We can use isinstance() function to verify that a variable is string or not.
|Python String Comparison
|Python String comparison can be performed using equality (==) and comparison (<, >, !=, =) operators.
|Python String join()
|Python String join() function returns a string that is the concatenation of the strings in iterable with string object as a delimiter.
|Python String Concatenation
|Learn about five different ways to concatenate Strings in Python.
|Python slice string
|Python string supports slicing to create substring. Note that Python string is immutable, slicing creates a new substring from the source string and original string remains unchanged.
|f-strings in Python
|Python f-strings or formatted strings are the new way to format strings. This feature was introduced in Python 3.6 under PEP-498. It’s also called literal string interpolation.
|Python Raw String
|Python raw string is created by prefixing a string literal with ‘r’ or ‘R’. Python raw string treats backslash (\) as a literal character.
|Python String equals
|Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.
|Python String encode() decode()
|Python string encode() function is used to encode the string using the provided encoding. This function returns the bytes object. Python bytes decode() function is used to convert bytes to string object.
|Python Trim String
|Python provides three methods that can be used to trim whitespaces from the string object.
|Python String Length
|Python String length can be determined by using built-in len() function.
|Python Concatenate String and int
|Learn about different ways to concatenate String and int to create a new string.
|Python Reverse String
|Python String doesn’t have a built-in reverse() function. However, there are various ways to reverse a string in Python.
|Python List to String
|Learn how to convert a list to string in a Python program.
|Python String find()
|Python String find() method is used to find the index of a substring in a string.
|Python Remove Character from String
|Learn how to remove character from a string using replace() and translate() functions.
|Python String Append
|Learn the best way to append multiple strings to create a new string.
|Python String translate()
|Python String translate() function returns a new string with each character in the string replaced using the given translation table.
|Python String to float
|We can convert a string to float in Python using float() function.
|Python String to List
|We can convert a string to list in Python using split() function.
|Python String count()
|Python String count() function returns the number of occurrences of a substring in the given string.
|Python Find String in List
|We can use Python in operator to check if a string is present in the list or not. There is also a not in operator to check if a string is not present in the list.
|Python Remove Spaces from String
|Learn about the five ways to remove spaces from a string in Python.
|Python string provides various methods to create a substring, check if it contains a substring, index of substring etc. In this tutorial, we will look into various operations related to substrings.
|Python Generate Random String
|Sometimes we want to generate a random string for unique identifiers, session id or to suggest a password. Learn how to generate a random string in Python.
|Python String Module
|Python String module contains some constants, utility function, and classes for string manipulation.
|String contains substring?
|Python provides two common ways to check if a string contains another string.
|Python String startswith()
|Python string startswith() function returns True if the string starts with the given prefix, otherwise it returns False.
|Python String endswith()
|Python string endswith() function returns True if the string ends with the given suffix, otherwise it returns False.
|Python Multiline String
|Sometimes we have a very long string and we want to write it into multiple lines for better code readability. Python provides various ways to create multiline strings.
|Python String capitalize()
|Python String capitalize() function returns the capitalized version of the string. The first character of the returned string is converted to uppercase and rest of the characters are changed to lowercase.
|Python String center()
|Python string center() function returns a centered string of specified size.
|Python String casefold()
|Python string casefold() function returns a casefolded copy of the string. This function is used to perform case-insensitive string comparison.
|Python String expandtabs()
|Python string expandtabs() function returns a new string with tab characters (\t) replaced with one or more whitespaces.
|Python String index()
|Python String index() function returns the lowest index where the specified substring is found. If the substring is not found then ValueError is raised.
|Python String format_map()
|Python string format_map() function returns a formatted version of the string using substitutions from the mapping provided.
|Python String isalnum()
|Python String isalpha()
|Python String isdecimal()
|Python String isdigit()
|Python String isidentifier()
|Python String islower()
|Python String isnumeric()
|Python String isprintable()
|Python String isspace()
|Python String istitle()
|Python String isupper()
|Python String ljust(), rjust()
|Python String swapcase()
|Python String partition()
|Python String splitlines()
|Python String title()
|Python String zfill()
|Python String Functions
|Python os module
|Python OS module provides easy functions that allow us to interact and get Operating System related information and even control processes up to a limit.
|Python sys module
|Python sys module provides easy functions that allow us to interact with the interpreter directly.
|Python time module helps us in working with local system date and time. The article also covers calendar module to get data in the calendar format.
|Python pymysql module is used to connect to MySQL database and execute database queries.
|Python csv module allows us to easily read and write CSV files.
|Python multiprocessing module allows us to write code for parallel processing across multiple CPU. Process, Queue, and Lock are the most important classes in the multiprocessing module.
|Python pickle module is used to serialize and deserialize a python object structure. Any object on python can be pickled so that it can be saved on disk.
|Python time sleep
|Python time sleep() function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds.
|Python queue module provides the implementation of different kinds of Queue data structures such as Queue, LifoQueue, and Priority Queue.
|Python unittest module is used to test a unit of source code.
|Python socket module helps us in implementing socket server and client programs in Python code.
|Python SimpleHTTPServer module is a very handy tool. You can use Python SimpleHTTPServer to turn any directory into a simple HTTP web server.
|Python json module is used to convert object to JSON data and vice versa.
|Python signal module is required for almost all the basic signal handling operations in python.
|Python random module is used to generate random numbers.
|Python System Command
|We can use os.system() function or subprocess.call() function to run shell commands from Python programs.
|Python Daemon Thread
|Learn how to create daemon thread using Python threading module.
|Python copy module allows us to perform shallow and deep copy of objects.
|Python threading module
|Python threading module is used to implement multithreading in python programs.
|Python struct module is capable of performing the conversions between the Python values and C structs, which are represented as Python Strings.
|Python logging module defines functions and classes that provide a flexible event logging system for python applications.
|Python subprocess module provides easy functions that allow us to spawn a new process and get their return codes.
|Python argparse module is the preferred way to parse command line arguments.
|Python functools module provides us various tools which allows and encourages us to write reusable code.
|Python itertools module provide us various ways to manipulate the sequence while we are traversing it.
|Python getopt module is one of the option to parse python command line arguments.
|Python ftp module helps us in connecting to a FTP server, upload, and download files.
|Python tarfile module is used to read and write tar archives.
|Python lxml is the most feature-rich and easy-to-use library for processing XML and HTML data.
|To provide a quick summary, using configparser module, we can keep the configuration related to our application in a configuration file, anywhere in the system and access it inside our application.
|Python datetime module manipulating dates and times. We can also format date and create naive or timezone aware date and time objects.
|Python decimal module
|Python decimal module helps us in division with proper precision and rounding of numbers.
|Python collections module comes with with a number of container data types such as OrderedDict, defaultdict, counter, namedtuple, and deque.
|Python zipfile module helps us in working with zip files. In this article, we will learn how to read zip archive details, create and extract zip files using zipfile module.
|Python pdb module provides an interactive debugging environment for Developers to debug Python programs.
|Python io module allows us to manage the file-related input and output operations. The advantage of using IO module is that the classes and functions available allows us to extend the functionality to enable writing to the Unicode data.
|Python fractions module allows us to manage fractions in our Python programs.
|Abstract Syntax Tree is a very strong features in Python. Python AST module allows us to interact with Python code itself and modify it.
|Python HTTP module defines the classes which provide the client-side of the HTTP and HTTPS protocols. In this article, we will learn how to use a Python HTTP client to fire HTTP request and then parse response status and get response body data.
|We can use python xmltodict module to read XML file and convert it to Dict or JSON data. We can also stream over large xml files and convert them to Dictionary.
|Python gzip module provides a very simple way to compress and decompress files and work in a similar manner to GNU programs gzip and gunzip.
|Python HTML Parser
|Python html.parser module provides us with the HTMLParser class, which can be sub-classed to parse HTML-formatted text files.
|Python inspect module
|Python inspect module is a very useful module which is used to introspect live objects in a program and look at the source code of modules, classes and functions which are used throughout a program.
|Python Send Email
|Sending email is a very common task in any software program, we can use python smtplib module for sending email in the python program.
|Python tempfile module provides easy functions through which we can make temporary files and directories and access them easily as well.
|Python sqlite3 is an excellent module with which you can perform all possible DB operations with in-memory and persistent database in your applications.
|Python shutil module enables us to operate with file objects easily and without diving into file objects a lot. It takes care of low-level semantics like creating file objects, closing the files once they are copied and allows us to focus on the business logic of our program.
|Python timeit module helps us in measuring the time of execution for a piece of Python code. The timeit module runs a piece of code 1 million times (default value) and takes into account the minimum amount of time it took to run that piece of code.
|Python getpass module
|Python getpass module is the perfect choice when we want user to enter secret keys, pass-phrases or password through terminal.
|Python urllib module allows us to access URL data programmatically. Some of the common usage are calling REST web services and making HTTP requests and read response data.
|Python pytz module allows us to create timezone aware datetime instances.
|Python Pendulum module is a drop-in replacement for the built-in datetime module. Python pendulum module supports timezones and provides useful methods to format, parse and date time manipulations.
|Python arrow module
|Python Arrow module is a replacement library for datetime. It’s a simple module with a human-friendly approach to creating, manipulating, formatting and converting dates, times, and timestamps.
|Python flask module allows us to create web applications in Python.
|Python Django Tutorial
|Learn how to get started with Django framework to create a simple web application.
|Python NumPy is the core library for scientific computing in Python. NumPy provides a high-performance multidimensional array object and tools for working with these arrays.
|Matrix are used a lot in scientific and mathematical equations. Python NumPy module provides support for matrix creation, addition, multiplication, inverse, and transpose operations.
|Python math module provides access to the mathematical functions defined by the C standard. So, we can do many complex mathematical operations with the help of the Python Math functions.
|We can use python hashlib module to generate message digest or secure hash from the source message. Python hashlib hashing function takes variable length of bytes and converts it into a fixed length sequence. This is a one way function.
|Plotly’s Python graphing library makes interactive graphs online and allows us to save them offline if need be.
|Python matplotlib library helps us to plot data on graphs in its simplest terms. If you are familiar with MATLAB plotting, then Matplotlib will be easy to use for basic plotting.
|Python SciPy library is a set of convenience functions built on NumPy and mathematical algorithms.
|TensorFlow is a library for dataflow programming. It’s a symbolic math library and is also used for application of machine learning such as neural network.
|Keras Deep Learning
|Keras is a high-level neural networks API. It is written in Python and can run on top of Theano, TensorFlow or CNTK.
|Scikit-learn is a machine learning library for Python. It features several regression, classification and clustering algorithms including SVMs, gradient boosting, k-means, random forests and DBSCAN.
|Seaborn is a library for making statistical infographics in Python. It is built on top of matplotlib and also supports numpy and pandas data structures. It also supports statistical units from SciPy.
|Python StatsModels allows users to explore data, perform statistical tests and estimate statistical models. It is supposed to complement to SciPy’s stats module.
|Python Gensim Word2Vec
|Gensim is an open-source vector space and topic modelling toolkit. It is implemented in Python and uses NumPy & SciPy. It also uses Cython for performance.
|NetworkX – Python Graph Library
|NetworkX is a Python package that allows us to create, manipulate, and study structure, functions and dynamics of complex networks.
|Bokeh Python Data Visualization
|Bokeh is an interactive Python data visualization library which targets modern web browsers for presentation.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.