With this Python tutorial, we aim to teach all basic to advanced level Python programming concepts to a large no. of aspirants in the most efficient way. We’ve organized this course in such a manner that you can learn Python with least efforts, without investing a lot of your time and finally be able to apply this knowledge to your live projects.
- Python History
- How was Python invented?
- Why is it named Python?
- Notable Python releases
- Silent Features in Python
- Code quality
- Developer productivity
- Code portability
- Rich library set
- Component integration
- Free to use
- OOP enabled
- Python Domains
- Web app development
- Science & computing
- GUI programming
- Software prototyping
- Professional training
- Why Learn Python?
- Easy syntax
- No explicit declaration
- OOP support
- Powerful debugging
- Run Python
- Install Python On Mac
- Install Python On Linux
- Install Python On Win
- Your First Python Program
- Program description
- Program source code
- Program walk-through
Python today stands amongst the top 5 most popular and fastest growing programming languages as per the latest TIOBE Index. It is a multipurpose, high-level, object-oriented, interactive, interpreted and extremely user-friendly programming language.
The interactive mode is a feature of Python shell which provides immediate feedback for every statement you type on the console.
Python has a simple coding style which is easy to catch with a little knowledge and the right tools. Hence, it is the preferred language for beginners planning to make a career in Programming.
Not only Python is the 4th most popular language as per TIOBE index but also the 3rd highest earning programming language. Please refer to the above developer’s salaries chart.
Python has applications in a variety of areas be they are desktop apps, web apps, data mining or machine learning.
You can make websites, create games, use it for web scrapping, robotics, and browser automation, i.e., using Selenium with Python. And almost everything that any object-oriented programming language can do.
Python Tutorial – Let’s Get Started.
Let’s first get some background before you further dive into reading the Python tutorial. It is always propitious to know about the tool which you are planning to learn.
Python is a general-purpose programming language which began as a solution to automate system level tasks in its early phases. However, soon, it became quite famous due to its extensive application development support. It allowed creating websites with a backend, GUI tools using PyQt/Tkinter, predicting stocks using machine learning (libraries like scikit-learn), data analysis using Pandas modules and game development with PyGame.
Python is easy to learn, highly readable, and simple to use. It has a clean and english-like syntax which requires less coding and let the programmer focus on the business logic rather than thinking about the nitty-gritty of the language.
It was a Dutch programmer, Guido Van Rossum, who wrote Python as a hobby programming project back in the late 1980s. Since then it has grown to become one of the most polished languages of the computing world.
In his own words, Guido revealed the secret behind the inception of Python. He started working on it as a weekend project utilizing his free time during Christmas in Dec’1989. He originally wanted to create an interpreter, a descendant of the ABC programming language which he was a contributing developer. And we all know that it was none other than Python which gradually transformed into a full-fledged programming language.
Guido initially thought the Unix/C hackers to be the target users of his project. And more importantly, he was fond of watching the famous comedy series [The Monty Python’s Flying Circus]. Thus, the name Python struck his mind as not only has it appealed to his taste but also to his target users.
|Python Version||Date of Release|
|Python v0.1.0 (The First Edition)||1990|
|Python v0.9.5 (Macintosh support)||2nd Jan’1992|
|Python v1.0.0||26th Jan’1994|
|Python v1.1.0||26th Jan’1994|
|Python v1.5.0||3rd Jan’1998|
|Python v1.6.0 (Latest updated version)||5th Sep’2000|
|Python v2.0.0 (Added list comprehensions)||16th Oct’2000|
|Python v2.7.0 (Latest updated version)||3rd Jul’2010|
|Python v3.0.0||3rd Dec’2008|
|Python v3.6.X (Latest updated version)||Mar’2017 and continued.|
Python code is highly readable which makes it more reusable and maintainable. It has broad support for advanced software engineering paradigms such as object-oriented (OO) and functional programming.
Python has a clean and elegant coding style. It uses an english-like syntax and is dynamically-typed. So, you never declare a variable. A simple assignment binds a name to an object of any type. Python code is significantly smaller than the equivalent C++/Java code. It implies there is less to type, limited to debug, and fewer to maintain. Unlike compiled languages, Python programs don’t need to compile and link which further boosts the developer speed.
Since Python is an interpreted language, so the interpreter has to manage the task of portability. Also, Python’s interpreter is smart enough to execute your program on different platforms to produce the same output. So, you never need to change a line in your code.
Python packages a large no. of the prebuilt and portable set of libraries. You can load them as and when needed to use the desired functionality.
Some applications need interaction across different components to support the end to end workflows. Onc such component could be a Python script while other be a program written in languages like Java/C++ or any other technology.
Python has several ways to support the cross-application communication. It allows mechanisms like loading of C and C++ libraries or vice-versa, integration with Java and DotNET components, communication using COM/Silverlight, and interfacing with USB devices over serial ports. It can even exchange data over networks using protocols like SOAP, XML-RPC, and CORBA.
Python is an OSS. You are free to use it, make amends in the source code and redistribute, even for commercial interests. It is because of such openness that Python has garnered a vast community base which is continually growing and adding value.
Python primarily follows object-oriented programming (OOP) design. OOP provides an intuitive way of structuring your code, and a solid understanding of the concepts behind it can let you make the most out of your coding. With OOP, it is easy to visualize the complex problem into smaller flows by defining objects and how they correlate. And then we can form the actual logic to make the program work.
Python has the lion’s share in the field of web development. Many employers look for full-stack programmers who know Python. And you can become one of them by learning frameworks (WAF) like Django, Flask, CherryPy, and Bottle which give extensive support for web development. All of these are developed using Python. These frameworks deliver essential features to simplify tasks related to content management, accessing backend database, and handling network protocols like HTTP, SMTP, XML-RPC, FTP, and POP. Some of the known online products created in Python are Plone (Content Management System), Zope application server, Quixote web framework, and ERP5, an open source enterprise solution used in the aerospace field.
Python has become the obvious choice for working in Scientific and Numeric Applications. And there are multiple reasons for this advancement. First and foremost is that Python is a free and open source language. And it allows to modify and redistribute its source code.
Next, the reason for becoming it more dominant in the field of Scientific and Numeric is the rapidly growing number of specialized modules like NumPy, SciPy, Pandas, matplotlib, and IPython. All of these are available for free and provide a fair alternative to paid products like Matlab.
Hence, Python is becoming a leader in this field. The focus of Python language is to bring more productivity and increase readability.
Python has some inherent qualities like clean and straightforward coding syntax as well as dynamic typing support. These work as the catalyst while developing complex GUI and image processing applications.
Python’s clean syntax and tremendous support of many GUI libraries (like wxWidgets, pyqt or pyside) made Programmers deliver graphics software like Inkscape, Scribus, Paint Shop Pro, and GIMP.
In addition to the 2D imaging solutions given above, Python is even propelling many 3D animation software like 3ds Max, Blender, Cinema 4D, Houdini, and Maya. These applications integrate with Python for automation to speed up their workflows and eliminate the need for doing them manually.
Python has many qualities that make it a natural choice for prototyping. The first is being an open source programming language, a massive no. of users follow and contribute to its development. Further, the lightness, versatility, scalability, and flexibility of refactoring code in Python speed up the development process from the initial prototype.
Hence, Python gives you an easy-to-use interface to create prototypes. For example, with Pygame (a multimedia library), you can prototype a game in different forms, test, and tailor it to match your requirements. Finally, you can take clues from the selected prototype and develop it using languages like C++/Java.
Python is indeed the right programming language for teaching and training purposes. It can be a stepping stone for beginners to enter into the professional training. They can even cover the overlapping areas like Data Analytics and Machine Learning.
Hence, there is a huge demand for professional trainers who can teach both basic and advanced level Python programming. You can impart training offline in a classroom or use tools like Skype or hangout to do it online.
Python is the language that even a non-programmer can understand. It is a highly readable, problem-oriented language that lets you focus on writing the logic instead of getting into the syntax nitty-gritty.
Here is a sample program for implementing an Interest Calculator. By looking at it, you can feel how easy it is to write and understand the code in Python.
print('Interest Calculator:') amount = float(input('Principal amount ?')) roi = float(input('Rate of Interest ?')) yrs = int(input('Duration (no. of years) ?')) total = (amount * pow(1 + (roi/100), yrs)) interest = total - amount print('\nInterest = %0.2f' %interest)
In Python, don’t use type specifier for declaring variables. You can do so without mentioning any data types in Python. Also, there is no need to use any separator like a semicolon to mark the end of a statement.
In Python, indentation replaces brackets to group a block of instructions. And you can use either tabs or spaces to indent the code.
However, Python enforces some rules (PEP 8) such as to use four spaces per indentation level. So, there are many such facets in Python which make learning simpler for beginners.
Object-Oriented Programming (OOP) comes built into the Python language. It lays down a model which derive solution by creating objects, defining relationships, and binding data. However, the procedural programming methodology takes on a top-down approach and solves one problem at a time while splitting it into smaller ones. On the other hand, OOP is a bottom-up problem-solving technique which seeks a blueprint of the solution at the onset and leaves implementation for the later.
Using classes, building inheritance and constructing objects are keys to developing yourself as a professional programmer. And you can quickly master these concepts in Python and produce better quality projects, quicker than in other languages.
Python lets you minimize the size of code you write and accomplishes more.
If you have a product in dev and QA logged a defect, then debugging is what you should be doing. However, if a customer has reported an issue, then debugging gets far more critical. Here also, Python leads the way by providing tools like pdb, pudb, and PyDebug that makes debugging experience easier than ever.
For example, the pudb tool can quickly guide a programmer to traverse through the code and nail down the problem.
It is a fact that most languages are working to improve their debugging tools. But with Python, they are only getting better.
☛ The latest version of Mac OS X is 10.13 (High Sierra) which has Python 2.7 pre-installed. Beginners can start to use Python 2 and learn to program. However, professional programmers should upgrade to Python 3.6.
☛ For installing Python on Mac, just go to the Download Python for Mac OS X page, select the desired package and click to download. Next, launch the downloaded package, follow the steps, and finish the installation.
☛ If you are a command line geek and love to use a console for routine system tasks, then run the following commands to install Python.
Firstly, open the terminal and install the HomeBrew package manager for Mac OS X.
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Enter the below command to check the Brew installation status.
$ brew --version
Now, use the Brew package manager to install Python 3.x.
$ brew install python3
☛ Installing Python with Brew also installs the PIP tool (pip3). It is a quick update manager to check out the available modules in the Python repository.
☛ Since now you have Python installed, it’s time to start coding. But you would need an IDE for professional development. It would turn you more efficient and productive. We recommend the community version of PyCharm and Eclipse with PyDev. Both of these are free and with full of features. However, you can read our reviews of world’s best Python IDEs and choose one for yourself.
☛ However, you can also begin with IDLE, the default IDE that comes with Python. Or even use the Python console to run your first few lines of code. In Python, you can do a lot with a single line of code. For example, you can write a function which checks for odd no, call it with input and print the outcome but all of that in one single line. Please see the code below.
print((lambda isOdd: isOdd(3))(lambda x: x % 2 != 0))
If you type the above line on a Python CLI, then it would just take an enter key to execute. However, if you are using IDLE to write this code in a script, then press F5 to run it. In either way, this simple one line of code would print “True” in its output.
☛ Ubuntu 16.04 has both Python 2 and Python 3 installed by default. However, you can double check if they are up to date or not using the apt-get commands.
$ sudo apt-get update $ sudo apt-get -y upgrade
☛ Once the above process completes, verify Python version with the following command.
$ python3 -V
☛ To manage available modules and libraries for Python, let’s install PIP.
$ sudo apt-get install -y python3-pip
☛ The PIP tool downloads new and updates existing packages you may like to use during the development. Here is the command to install the Python packages.
$ pip3 install <package_to_install>
# For example.
$ pip3 install numpy
☛ Now is the time to check out a few more libs and dev tools that could be pretty useful later. Run the below command to add them to your Python installation.
$ sudo apt-get install build-essential libssl-dev libffi-dev python-dev
☛ You can also set up an isolated space on your system for Python projects. For this, install the venv module, it is a component of the standard Python 3 library.
$ sudo apt-get install -y python3-venv
☛ Now, you are all set to create environments. Go ahead and run the following commands.
$ mkdir environments $ cd environments $ python3 -m venv test_env
☛ Before you can use the <test_env>, you have to activate it first. The following command will do the activation for you.
$ source test_env/bin/activate
Your prompt will now a little different than the standard one.
This prefix indicates that the environment test_env is currently active. And you can create programs to use environment’s settings and packages.
☛ We have our virtual env set up, let’s write a simple “Hello, World!” script. To do this, open up a command-line text editor such as vi and create a new file.
(test_env) techbeamers@techbeamers:~/environments$ vi world.py
The vi editor will open the text file in the terminal. Write the code given below. Press “:wq” to save and exit from the editor.
☛ Once you exit out of vi and return to the shell, let’s run the script.
(test_env) techbeamers@techbeamers:~/environments$ python3 hello.py
To log out of the environment, type the command “deactivate,” and it’ll return to your original directory.
☛ For installing Python on Windows, just go to the Download Python for Windows page, select the desired package and click to download. We recommend Python 2.7 as it is one of the most stable packages. Next, launch the downloaded package, follow the steps, and finish the installation.
☛ During installation, select the option “Install for all users” and use the destination directory (C:\Python27) as default.
☛ Next, open the “Start” menu and type “cmd” into the search box. Right-click on the “cmd.exe” link and choose to run as an administrator.
☛ Change directory to “C:\Python27” and run the following command to set Python on the system’s path.
setx PATH "%cd%;%path%;" pause
The above command (setx) will set Python path for all future instances of the cmd.exe, but not for the current one. So, you’ll need to reopen the command window to use Python.
☛ Now, you are ready to write your first Python program on Windows. As we stated above, you must use a professional IDE for better development. However, here, we’ll tell you to use IDLE that comes as the default editor for Python.
☛ From the “Start” menu, open “All Programs” and select “Python 2.7”. Click on the “IDLE (Python GUI)” link to launch the editor.
☛ To start with IDLE, press CTRL+N to create a new file. Then, name it as “world.py” while saving using the CTRL+S.
☛ Place the following instruction in the newly created file.
Save the file and go to [Run >> Run Module] or press F5 to execute your first Python script.
Usually, it is the “Hello, World!” program which every language recommends as a starting point to learn Programming. It is a simple program which prints the “Hello, World!” message on the standard output.
It obviously would be very trivial if we write it in Python, just one statement as print(“Hello, World!”). Hence, we’ll use the Interest Calculator program for illustration.
This program computes the interest accrued over the specified no. of years on the principal amount with one year as a fixed value for the compound interval.
print('Interest Calculator:') amount = float(input('Principal amount ?')) roi = float(input('Rate of Interest ?')) years = int(input('Duration (no. of years) ?')) total = (amount * pow(1 + (roi/100), years)) interest = total - amount print('\nInterest = %0.2f' %interest)
In the first line, we are calling the print() function to display an informational message. It’s same as printing like the “Hello, World!”.
In the next three lines, we are using the following variables to store the input provided by the user.
The variable ‘amount’ represents the principal amount borrowed.
Another one is the ‘roi’ which represents the rate of interest levied on the principal amount.
Next, there is ‘years’ which is the no. of years representing the borrowing period.
Also, you must note here that we are using the Python’s input() function to prompt the user for entering the values. Furthermore, you can observe that we’ve used Python’s conversion operators (int() and float()) in this code.
int(value) -> It converts any value to a plain integer.
float(value) -> It converts a value to a float type number.
So far, we’ve covered the first four lines. Let’s continue exploring the remainder of the program.
In the fifth line of code, we are using a variable called “total” to store the result of a complex assignment.
The total -> It represents the total amount to be paid after the borrowing period.
But this line is a little different from the previous ones. It is because the first line was an output statement and the next three were the simple assignment operations. Here, in the fifth line of code, we are computing the Total amount including the Interest part with the help of the following formula.
Further to add, this assignment involves the use of the following Python’s arithmetic operators and functions.
+ Addition -> It adds numbers on either side of the operator.
* Multiplication -> It multiplies numbers on either side of the operator.
/ Division -> It divides left-hand operand by right-hand operand.
pow(X, Y, Z) -> It determines [X to the power Y]. If Z is available, then it’ll return X to the power Y, modulo Z.
In the sixth line, we are using Python’s subtraction operator (-) to calculate the interest amount.
Finally, there is a print statement displaying the interest amount. Since it is a float value, so the print() function will show the full number by default. Hence, we are using the floating point format specifier “%0.2f” in print() function so that we can limit the printing up to two decimal points.
- Python Keyword
- Python Statement
- Python Comment
- Python Data Types
- Python Numbers
- Python List
- Python Set
- Python Tuple
- Python Dictionary
- Python Operators
- Operator Precedence
- Python Namespace
- Python String
- Python Class
- Python Inheritance
- Python File I/O
- Python Copy File
- Python Exception
- Python Try Except
- Python Pickle
- Python Time
- Python Random
- Python For Loop
- Python While Loop