List Python 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 Interest Over Time
Why to learn Python Programming?
- Python programming is very simple, elegant, and English like. So it’s very easy to learn and a good programming language to start your IT career.
- Python is open source and you are free to extend it and make something beautiful out of it.
- Python has vast community support. There are over a million questions on StackOverflow in Python category.
- There are tons of free modules and packages to help you in every area of development.
- Most of the Machine Learning, Data Science, Graphs, Artificial Intelligence APIs are built on top of Python. So if you want to work in the area of cutting-edge technologies then it’s a great choice for you.
- Python is used by almost every major company in the world. So the chances of getting a job are much better if you know Python programming. If you are applying for any Python job, please go through Python Interview Questions.
- There are no limitations to Python programming, you can use it in IoT, web applications, game development, cryptography, blockchain, scientific calculations, graphs and many other areas.
Python Tutorial
Python Tutorial can be broadly divided into the following categories.
- Python Basics – syntax, data types, variables, loops, functions, numbers, strings, classes, objects etc.
- Python Built-in Functions – format(), len(), super(), range(), slice(), tuple(), list() etc.
- Python Modules – collections, json, xml, io, os, sys, time, datetime etc.
- Web Applications Frameworks – Django, Flask
- Advanced Topics – Graphs, AI, ML modules such as Matplotlib, NumPy, TensorFlow, SciKit, Pandas etc.
Python Tutorial Important Points
- If you are completely new to Python, spend enough time to go through basics. If your basics in Python won’t be strong then your code won’t be pythonic in nature.
- Python has two running major versions – Python-2 and Python-3. Python-3 is not backward compatible with Python-2. However, Python 3 is the recommended version to use. That’s why all the Python tutorials here are based on Python 3.
- While reading through the Python tutorials, please follow the examples and run them in your IDE for better understanding.
- PyCharm from JetBrains is the perfect IDE for Python programming. Its community edition is free to use.
- Most of our examples are present in our GitHub Repository. You can download them and look at the examples. I would recommend you to fork the project and then play around with the code.
- We have covered extensively on Python if you think we have missed some important topic. Please feel free to comment here and I will include them too.
Python Basics
Topic | Description |
---|---|
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. |
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. |
Python Operators | Arithmetic, Comparison, Bitwise, Logical, and Assignment Operators. Learn about the operator precedence in Python programming. |
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. |
Python loop | Learn how to loop over a sequence, reverse looping, traversing through multiple sequences at once. |
Python functions | Learn how to define a function in Python, different types of arguments |
Python Recursion | How to implement recursion in Python, printing Fibonacci series using recursion. |
Python Modules | Understand what is a module in Python. Difference between module and package and how to import a module in your program. |
Python Package | Quick introduction to Python packages and how to use them. |
Python Numbers | Different types of numbers, type conversion and complex numbers in Python |
Python List | Python List functions – create, update, delete, append and iterate through elements. |
Python Tuple | Learn about accessing tuple elements, update and delete tuple, important tuple functions. |
Python String | A brief introduction of String in Python and important Python string functions. |
Python set | Learn how to work with Set in Python. |
Python Dictionary | Python dictionary operations, accessing key-value pairs, deleting dict elements. |
Python File | Python file operations – read, open, write, delete and copy file. |
Python Directory | How to create, rename and delete a directory in Python. |
Learn how to sort a List elements in Python, sort in decending order and with custom logic.
Learn about Python List Comprehension to create list from some source sequence, string or list.
Learn how to perform exception handling in Python using try-except block.
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 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 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.
Short example for using list append() function in Python.
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.
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 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.
Learn how to effectively use Python ternary operator to reduce boiler plate code.
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 are input parameters passed to the script when executing them. Learn how to effectively read and parse command line parameters in Python.
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 is the memory management mechanism in python.
Python ElementTree XML API provides us easy way to read XML file and extract useful data.
We can use String join() function to concatenate a list of string with specified delimiter to create a new string.
A complete tutorial for Python class init() function.
Learn how to route Python print() function output to a file.
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.
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.
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.
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.
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.
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 Environment Variable
Python Built-In Functions
Topic
Description
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() 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 is used to parse an expression string as python expression and then execute it.
Python exec() function provides support for dynamic code execution.
Python String Functions
Topic
Description
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 class has contains() function that we can use to check if it contains another string or not.
Python string split() function is used to split a string into the list of strings based on a delimiter.
Python string replace() function is used to create a string by replacing some parts of another string.
Python String format() function is used to create a formatted string from the template string and the supplied values.
Python String Template class is used to create a simple template string, where fields can be replaced later on to create a string object.
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 can be performed using equality (==) and comparison (<, >, !=, <=, >=) operators.
Python String join() function returns a string that is the concatenation of the strings in iterable with string object as a delimiter.
Learn about five different ways to concatenate Strings in Python.
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.
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 is created by prefixing a string literal with ‘r’ or ‘R’. Python raw string treats backslash () as a literal character.
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 provides three methods that can be used to trim whitespaces from the string object.
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 String doesn’t have a built-in reverse() function. However, there are various ways to reverse a string in Python.
Learn how to convert a list to string in a Python program.
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.
Learn the best way to append multiple strings to create a new string.
Python String translate() function returns a new string with each character in the string replaced using the given translation table.
We can convert a string to float in Python using float() function.
We can convert a string to list in Python using split() function.
Python String count() function returns the number of occurrences of a substring in the given string.
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.
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 contains some constants, utility function, and classes for string manipulation.
Python provides two common ways to check if a string contains another string.
Python string startswith() function returns True if the string starts with the given prefix, otherwise it returns False.
Python string endswith() function returns True if the string ends with the given suffix, otherwise it returns False.
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() 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() function returns a centered string of specified size.
Python string casefold() function returns a casefolded copy of the string. This function is used to perform case-insensitive string comparison.
Python string expandtabs() function returns a new string with tab characters (\t) replaced with one or more whitespaces.
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() function returns a formatted version of the string using substitutions from the mapping provided.
Python String ljust(), rjust()
Python Modules
Topic
Description
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 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() 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.
We can use os.system() function or subprocess.call() function to run shell commands from Python programs.
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 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 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 module provides us with the HTMLParser class, which can be sub-classed to parse HTML-formatted text files.
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.
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 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 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 Web Application Frameworks
Topic
Description
Python flask module allows us to create web applications in Python.
Learn how to get started with Django framework to create a simple web application.
Python Advanced Topics
Topic
Description
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 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.
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.
References:
- Python Built-In Functions
- Python Built-in Types
- Python 3 Official Documentation
- Python Wikipedia Page
- Python GitHub Source Code
- Python Package Index (PyPI)
- Python Reddit Community
Source journaldev.com.