PYTHON - Quick Guide
Python - Quick Guide
PreviousNext
Python - Overview
Python is a high-level, multi-paradigm programming language. As Python is an interpreter-based language, it is easier to learn compared to some of the other mainstream languages. Python is a dynamically typed language with very intuitive data types.
Python is an open-source and cross-platform programming language. It is available for use underPython Software Foundation License(compatible to GNU General Public License) on all the major operating system platforms Linux, Windows and Mac OS.
The design philosophy of Python emphasizes on simplicity, readability and unambiguity. Python is known for its batteries included approach as Python software is distributed with a comprehensive standard library of functions and modules.
Python’s design philosophy is documented in theZen of Python. It consists of nineteen aphorisms such as −
- Beautiful is better than ugly
- Explicit is better than implicit
- Simple is better than complex
- Complex is better than complicated
To obtain the complete Zen of Python document, typeimport thisin the Python shell −
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!Python supports imperative, structured as well as object-oriented programming methodology. It provides features of functional programming as well.
Python - History
Guido Van Rossum, a Dutch programmer, created Python programming language. In the late 80’s, he had been working on the development of ABC language in a computer science research institute namedCentrum Wiskunde & Informatica(CWI) in the Netherlands. In 1991, Van Rossum conceived and published Python as a successor of ABC language.
For many uninitiated people, the word Python is related to a species of snake. Rossum though attributes the choice of the name Python to a popular comedy series “Monty Python’s Flying Circus” on BBC.
Being the principal architect of Python, the developer community conferred upon him the title of “Benevolent Dictator for Life(BDFL). However, in 2018, Rossum relinquished the title. Thereafter, the development and distribution of the reference implementation of Python is handled by a nonprofit organizationPython Software Foundation.
Important stages in the history of Python −
Python 0.9.0
Python’s first published version is 0.9. It was released in February 1991. It consisted of support for core object-oriented programming principles.
Python 1.0
In January 1994, version 1.0 was released, armed with functional programming tools, features like support for complex numbers etc.
Python 2.0
Next major version − Python 2.0 was launched in October 2000. Many new features such as list comprehension, garbage collection and Unicode support were included with it.
Python 3.0
Python 3.0, a completely revamped version of Python was released in December 2008. The primary objective of this revamp was to remove a lot of discrepancies that had crept in Python 2.x versions. Python 3 was backported to Python 2.6. It also included a utility named aspython2to3to facilitate automatic translation of Python 2 code to Python 3.
EOL for Python 2.x
Even after the release of Python 3, Python Software Foundation continued to support the Python 2 branch with incremental micro versions till 2019. However, it decided to discontinue the support by the end of year 2020, at which time Python 2.7.17 was the last version in the branch.
Current Version
Meanwhile, more and more features have been incorporated into Python’s 3.x branch. As of date, Python3.11.2is the current stable version, released in February 2023.
What’s New in Python 3.11?
One of the most important features of Python’s version 3.11 is the significant improvement in speed. According to Python’s official documentation, this version is faster than the previous version (3.10) by up to 60%. It also states that the standard benchmark suite shows a 25% faster execution rate.
- Python 3.11 has a better exception messaging. Instead of generating a long traceback on the occurrence of an exception, we now get the exact expression causing the error.
- As per the recommendations of PEP 678, theadd_note()method is added to the BaseException class. You can call this method inside the except clause and pass a custom error message.
- It also adds thecbroot()function in themathsmodule. It returns the cube root of a given number.
- A new moduletomllibis added in the standard library. TOML (Tom’s Obvious Minimal Language) can be parsed with tomlib module function.
Python - Features
In this chapter, let’s highlight some of the important features of Python that make it widely popular.
Python is Easy to Learn
This is one of the most important reasons for the popularity of Python. Python has a limited set of keywords. Its features such as simple syntax, usage of indentation to avoid clutter of curly brackets and dynamic typing that doesn’t necessitate prior declaration of variable help a beginner to learn Python quickly and easily.
Python is Interpreter Based
Instructions in any programming languages must be translated into machine code for the processor to execute them. Programming languages are either compiler based or interpreter based.
In case of a compiler, a machine language version of the entire source program is generated. The conversion fails even if there is a single erroneous statement. Hence, the development process is tedious for the beginners. The C family languages (including C, C++, Java, C Sharp etc) are compiler based.
Python is an interpreter based language. The interpreter takes one instruction from the source code at a time, translates it into machine code and executes it. Instructions before the first occurrence of error are executed. With this feature, it is easier to debug the program and thus proves useful for the beginner level programmer to gain confidence gradually. Python therefore is a beginner-friendly language.
Python is Interactive
Standard Python distribution comes with an interactive shell that works on the principle of REPL (Read − Evaluate − Print − Loop). The shell presents a Python prompt >>>. You can type any valid Python expression and press Enter. Python interpreter immediately returns the response and the prompt comes back to read the next expression.
>>> 2*3+1
7
>>> print ("Hello World")
Hello WorldThe interactive mode is especially useful to get familiar with a library and test out its functionality. You can try out small code snippets in interactive mode before writing a program.
Python is MultiParadigm
Python is a completely object-oriented language. Everything in a Python program is an object. However, Python conveniently encapsulates its object orientation to be used as an imperative or procedural language − such as C. Python also provides certain functionality that resembles functional programming. Moreover, certain third-party tools have been developed to support other programming paradigms such as aspect-oriented and logic programming.
Python’s Standard Library
Even though it has a very few keywords (only Thirty Five), Python software is distributed with a standard library made of large number of modules and packages. Thus Python has out of box support for programming needs such as serialization, data compression, internet data handling, and many more. Python is known for its batteries included approach.
Python is Open Source and Cross Platform
Python’s standard distribution can be downloaded fromhttps://www.python.org/downloads/without any restrictions. You can download pre-compiled binaries for various operating system platforms. In addition, the source code is also freely available, which is why it comes under open source category.
Python software (along with the documentation) is distributed under Python Software Foundation License. It is a BSD style permissive software license and compatible to GNU GPL (General Public License).
Python is a cross-platform language. Pre-compiled binaries are available for use on various operating system platforms such as Windows, Linux, Mac OS, Android OS. The reference implementation of Python is called CPython and is written in C. You can download the source code and compile it for your OS platform.
A Python program is first compiled to an intermediate platform independent byte code. The virtual machine inside the interpreter then executes the byte code. This behaviour makes Python a cross-platform language, and thus a Python program can be easily ported from one OS platform to other.
Python for GUI Applications
Python’s standard distribution has an excellent graphics library called TKinter. It is a Python port for the vastly popular GUI toolkit called TCL/Tk. You can build attractive user-friendly GUI applications in Python. GUI toolkits are generally written in C/C++. Many of them have been ported to Python. Examples are PyQt, WxWidgets, PySimpleGUI etc.
Python’s Database Connectivity
Almost any type of database can be used as a backend with the Python application. DB-API is a set of specifications for database driver software to let Python communicate with a relational database. With many third party libraries, Python can also work with NoSQL databases such as MongoDB.
Python is Extensible
The term extensibility implies the ability to add new features or modify existing features. As stated earlier, CPython (which is Python’s reference implementation) is written in C. Hence one can easily write modules/libraries in C and incorporate them in the standard library. There are other implementations of Python such as Jython (written in Java) and IPython (written in C#). Hence, it is possible to write and merge new functionality in these implementations with Java and C# respectively.
Python’s Active Developer Community
As a result of Python’s popularity and open-source nature, a large number of Python developers often interact with online forums and conferences. Python Software Foundation also has a significant member base, involved in the organization’s mission to “promote, protect, and advance the Python programming language”
Python also enjoys a significant institutional support. Major IT companies Google, Microsoft, and Meta contribute immensely by preparing documentation and other resources.
Python vs C++
Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this chapter, we shall take a look at their characteristic features.
Compiled vs Interpreted
Like C, C++ is also a compiler-based language. A compiler translates the entire code in a machine language code specific to the operating system in use and processor architecture.
Python is interpreter-based language. The interpreter executes the source code line by line.
Cross platform
When a C++ source code such as hello.cpp is compiled on Linux, it can be only run on any other computer with Linux operating system. If required to run on other OS, it needs to be compiled.
Python interpreter doesn’t produce compiled code. Source code is converted to byte code every time it is run on any operating system without any changes or additional steps.
Portability
Python code is easily portable from one OS to other. C++ code is not portable as it must be recompiled if the OS changes.
Speed of Development
C++ program is compiled to the machine code. Hence, its execution is faster than interpreter based language.
Python interpreter doesn’t generate the machine code. Conversion of intermediate byte code to machine language is done on each execution of program.
If a program is to be used frequently, C++ is more efficient than Python.
Easy to Learn
Compared to C++, Python has a simpler syntax. Its code is more readable. Writing C++ code seems daunting in the beginning because of complicated syntax rule such as use of curly braces and semicolon for sentence termination.
Python doesn’t use curly brackets for marking a block of statements. Instead, it uses indents. Statements of similar indent level mark a block. This makes a Python program more readable.
Static vs Dynamic Typing
C++ is a statically typed language. The type of variables for storing data need to be declared in the beginning. Undeclared variables can’t be used. Once a variable is declared to be of a certain type, value of only that type can be stored in it.
Python is a dynamically typed language. It doesn’t require a variable to be declared before assigning it a value. Since, a variable may store any type of data, it is called dynamically typed.
OOP Concepts
Both C++ and Python implement object oriented programming concepts. C++ is closer to the theory of OOP than Python. C++ supports the concept of data encapsulation as the visibility of the variables can be defined as public, private and protected.
Python doesn’t have the provision of defining the visibility. Unlike C++, Python doesn’t support method overloading. Because it is dynamically typed, all the methods are polymorphic in nature by default.
C++ is in fact an extension of C. One can say that additional keywords are added in C so that it supports OOP. Hence, we can write a C type procedure oriented program in C++.
Python is completely object oriented language. Python’s data model is such that, even if you can adapt a procedure oriented approach, Python internally uses object-oriented methodology.
Garbage Collection
C++ uses the concept of pointers. Unused memory in a C++ program is not cleared automatically. In C++, the process of garbage collection is manual. Hence, a C++ program is likely to face memory related exceptional behavior.
Python has a mechanism of automatic garbage collection. Hence, Python program is more robust and less prone to memory related issues.
Application Areas
Because C++ program compiles directly to machine code, it is more suitable for systems programming, writing device drivers, embedded systems and operating system utilities.
Python program is suitable for application programming. Its main area of application today is data science, machine learning, API development etc.
The following table summarizes the comparison between C++ and Python −
| Criteria | C++ | Python |
|---|---|---|
| Execution | Compiler based | Interpreter based |
| Typing | Static typing | Dynamic typing |
| Portability | Not portable | Highly portable |
| Garbage collection | Manual | Automatic |
| Syntax | Tedious | Simple |
| Performance | Faster execution | Slower execution |
| Application areas | Embedded systems, device drivers | Machine learning, web applications |
Python - Hello World Program
Hello World program is a basic computer code written in a general purpose programming language, used as a test program. It doesn’t ask for any input and displays a Hello World message on the output console. It is used to test if the software needed to compile and run the program has been installed correctly.
It is very easy to display the Hello World message using the Python interpreter. Launch the interpreter from a command terminal of your operating system and issue the print statement from the Python prompt as follows −
PS C:\Users\mlath> python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print ("Hello World")
Hello WorldSimilarly, Hello World message is printed in Linux.
mvl@GNVBGL3:~$ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print ("Hello World")
Hello WorldPython interpreter also works in scripted mode. Open any text editor, enter the following text and save as Hello.py
print ("Hello World")For Windows OS, open the command prompt terminal (CMD) and run the program as shown below −
C:\Python311>python hello.py
Hello WorldThe terminal shows the Hello World message.
While working on Ubuntu Linux, you have to follow the same steps, save the code and run from Linux terminal. We use vi editor for saving the program.
To run the program from Linux terminal
mvl@GNVBGL3:~$ python3 hello.py
Hello WorldIn Linux, you can convert a Python program into a self executable script. The first statement in the code should be a shebang. It must contain the path to Python executable. In Linux, Python is installed in /usr/bin directory, and the name of the executable is python3. Hence, we add this statement to hello.py file
#!/usr/bin/python3
print ("Hello World")You also need to give the file executable permission by using the chmod +x command
mvl@GNVBGL3:~$ chmod +x hello.pyThen, you can run the program with following command line −
mvl@GNVBGL3:~$ ./hello.pyTheoutputis shown below −
Thus, we can write and run Hello World program in Python using the interpreter mode and script mode.
Python - Application Areas
Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few years Python is the preferred language of choice for developers in following application areas −
Python for Data Science
Python’s recent meteoric rise in the popularity charts is largely due its Data science libraries. Python has become an essential skill for data scientists. Today, real time web applications, mobile applications and other devices generate huge amount of data. Python’s data science libraries help companies generate business insights from this data.
Libraries like NumPy, Pandas and Matplotlib are extensively used to apply mathematical algorithms to the data and generate visualizations. Commercial and community Python distributions like Anaconda and ActiveState bundle all the essential libraries required for data science.
Python for Machine Learning
Python libraries such as Scikit-learn and TensorFlow help in building models for prediction of trends like customer satisfaction, projected values of stocks etc. based upon the past data. Machine learning applications include (but not restricted to) medical diagnosis, statistical arbitrage, basket analysis, sales prediction etc.
Python for Web Development
Python’s web frameworks facilitate rapid web application development. Django, Pyramid, Flask are very popular among the web developer community. etc. make it very easy to develop and deploy simple as well as complex web applications.
Latest versions of Python provide asynchronous programming support. Modern web frameworks leverage this feature to develop fast and high performance web apps and APIs.
Python for Computer Vision and Image processing
OpenCV is a widely popular library for capturing and processing images. Image processing algorithms extract information from images, reconstruct image and video data. Computer Vision uses image processing for face detection and pattern recognition. OpenCV is a C++ library. Its Python port is extensively used because of its rapid development feature.
Some of the application areas of computer vision are robotics, industrial surveillance and automation, biometrics etc.
Python for Embedded Systems and IoT
Micropython (https://micropython.org/), a lightweight version especially for microcontrollers like Arduino. Many automation products, robotics, IoT, and kiosk applications are built around Arduino and programmed with Micropython. Raspberry Pi is also very popular alow cost single board computer used for these type of applications.
Python for Job Scheduling and Automation
Python found one of its first applications in automating CRON (Command Run ON) jobs. Certain tasks like periodic data backups, can be written in Python scripts scheduled to be invoked automatically by operating system scheduler.
Many software products like Maya embed Python API for writing automation scripts (something similar to Excel micros).
Try Python Online
If you are new to Python, it is a good idea to get yourself familiar with the language syntax and features by trying out one of the many online resources, before you proceed to install Python software on your computer.
You can launch Python interactive shell from the home page of Python’s official websitehttps://www.python.org/.
In front of the Python prompt (>>>), any valid Python expression can be entered and evaluated.
The CodesCompiler website also has aCoding Groundsection −
(https://www.codescompiler.com/codingground.htm)
Here you can find online compilers for various languages including Python. Visithttps://www.codescompiler.com/execute_python_online.php. You can experiment with the interactive mode and the scripted mode of Python interpreter.
Python - Interpreter
Python is an interpreter-based language. In a Linux system, Python’s executable is installed in/usr/bin/directory. For Windows, the executable (python.exe) is found in the installation folder (for exampleC:\python311). In this chapter, you willhow Python interpreter works, its interactive and scripted mode.
Python code is executed by one statement at a time method. Python interpreter has two components. The translator checks the statement for syntax. If found correct, it generates an intermediate byte code. There is a Python virtual machine which then converts the byte code in native binary and executes it. The following diagram illustrates the mechanism:
Python interpreter has an interactive mode and a scripted mode.
Interactive Mode
When launched from a command line terminal without any additional options, a Python prompt>>>appears and the Python interpreter works on the principle ofREPL (Read, Evaluate, Print, Loop). Each command entered in front of the Python prompt is read, translated and executed. A typical interactive session is as follows.
>>> price = 100
>>> qty = 5
>>> ttl = price*qty
>>> ttl
500
>>> print ("Total = ", ttl)
Total = 500To close the interactive session, enter the end-of-line character (ctrl+D for Linux and ctrl+Z for Windows). You may also typequit()in front of the Python prompt and press Enter to return to the OS prompt.
The interactive shell available with standard Python distribution is not equipped with features like line editing, history search, auto-completion etc. You can use other advanced interactive interpreter software such asIPythonandbpython.
Scripting Mode
Instead of entering and obtaining the result of one instruction at a time − as in the interactive environment, it is possible to save a set of instructions in a text file, make sure that it has.pyextension, and use the name as the command line parameter for Python command.
Save the following lines asprog1.py, with the use of any text editor such as vim on Linux or Notepad on Windows.
print ("My first program")
price = 100
qty = 5
ttl = price*qty
print ("Total = ", ttl)Launch Python with this name as command line argument.
C:\Users\Acer>python prog1.py
My first program
Total = 500Note that even though Python executes the entire script, it is still executed in one-by-one fashion.
In case of any compiler-based language such as Java, the source code is not converted in byte code unless the entire code is error-free. In Python, on the other hand, statements are executed until first occurrence of error is encountered.
Let us introduce an error purposefully in the above code.
print ("My first program")
price = 100
qty = 5
ttl = prive*qty #Error in this statement
print ("Total = ", ttl)Note the misspelt variablepriveinstead ofprice. Try to execute the script again as before −
C:\Users\Acer>python prog1.py
My first program
Traceback (most recent call last):
File "C:\Python311\prog1.py", line 4, in <module>
ttl = prive*qty
^^^^^
NameError: name 'prive' is not defined. Did you mean: 'price'?Note that the statements before the erroneous statement are executed and then the error message appears. Thus it is now clear that Python script is executed in interpreted manner.
In addition to executing the Python script as above, the script itself can be a selfexecutable in Linux, like a shell script. You have to add ashebangline on top of the script. The shebang indicates which executable is used to interpret Python statements in the script. Very first line of the script starts with#!And followed by the path to Python executable.
Modify the prog1.py script as follows −
#! /usr/bin/python3.11
print ("My first program")
price = 100
qty = 5
ttl = price*qty
print ("Total = ", ttl)To mark the script as self-executable, use thechmodcommand
user@ubuntu20:~$ chmod +x prog1.pyYou can now execute the script directly, without using it as a command-line argument.
user@ubuntu20:~$ ./hello.pyIPython
IPython (stands forInteractive Python) is an enhanced and powerful interactive environment for Python with many functionalities compared to the standard Python shell. IPython was originally developed by Fernando Perez in 2001.
IPython has the following important features −
- IPython’s object introspection ability to check properties of an object during runtime.
- Its syntax highlighting proves to be useful in identifying the language elements such as keywords, variables etc.
- The history of interactions is internally stored and can be reproduced.
- Tab completion of keywords, variables and function names is one of the most important features.
- IPython’s Magic command system is useful for controlling Python environment and performing OS tasks.
- It is the main kernel for Jupyter notebook and other front-end tools of Project Jupyter.
Install IPython with PIP installer utility.
pip3 install ipythonLaunch IPython from command-line
C:\Users\Acer>ipython
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type 'copyright', 'credits' or 'license' for more information
IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]:Instead of the regular >>> prompt as in standard interpreter, you will notice two major IPython prompts as explained below −
- In[1] appears before any input expression.
- Out[1]appears before the Output appears.
In [1]: price = 100
In [2]: quantity = 5
In [3]: ttl = price*quantity
In [4]: ttl
Out[4]: 500
In [5]:Tab completion is one of the most useful enhancements provided by IPython. IPython pops up appropriate list of methods as you press tab key after dot in front of object.
In the following example, a string is defined. Press tab key after the ”.” symbol and as a response, the attributes of string class are shown. You can navigate to the required one.
IPython provides information (introspection) of any object by putting ’?’ in front of it. It includes docstring, function definitions and constructor details of class. For example to explore the string object var defined above, in the input prompt enter var?.
In [5]: var = "Hello World"
In [6]: var?
Type: str
String form: Hello World
Length: 11
Docstring:
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.IPython’s magic functions are extremely powerful. Line magics let you run DOS commands inside IPython. Let us run thedircommand from within IPython console
In [8]: !dir *.exe
Volume in drive F has no label.
Volume Serial Number is E20D-C4B9
Directory of F:\Python311
07-02-2023 16:55 103,192 python.exe
07-02-2023 16:55 101,656 pythonw.exe
2 File(s) 204,848 bytes
0 Dir(s) 105,260,306,432 bytes freeJupyter notebook is a web-based interface to programming environments of Python, Julia, R and many others. For Python, it uses IPython as its main kernel.
Python - Environment Setup
First step in the journey of learning Python is to install it on your machine. Today most computer machines, especially having Linux OS, have Python pre-installed. However, it may not be the latest version.
In this section, we shall learn to install the latest version of Python,Python 3.11.2, on Linux, Windows and Mac OS.
Latest version of Python for all the operating system environments can be downloaded from PSF’s official website.
Install Python on Ubuntu Linux
To check whether Python is already installed, open the Linux terminal and enter the following command −
user@ubuntu20:~$ python3 --versionIn Ubuntu Linux, the easiest way to install Python is to useapt − Advanced Packaging Tool. It is always recommended to update the list of packages in all the configured repositories.
user@ubuntu20:~$ sudo apt updateEven after the update, the latest version of Python may not be available for install, depending upon the version of Ubuntu you are using. To overcome this, add thedeadsnakesrepository.
user@ubuntu20:~$ sudo apt-get install software-properties-common
user@ubuntu20:~$ sudo add-apt-repository ppa:deadsnakes/ppaUpdate the package list again.
user@ubuntu20:~$ sudo apt updateTo install the latest Python 3.11 version, enter the following command in the terminal −
user@ubuntu20:~$ sudo apt-get install python3.11Check whether it has been properly installed.
user@ubuntu20:~$ python3.11
Python 3.11.2 (main, Feb 8 2023, 14:49:24) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print ("Hello World")
Hello World
>>>Install Python on Windows
It may be noted that Python’s version 3.10 onwards cannot be installed on Windows 7 or earlier operating systems.
The recommended way to install Python is to use the official installer. Linn to the latest stable version is given on the home page itself. It is also found athttps://www.python.org/downloads/windows/.
You can find embeddable packages and installers for 32 as well as 64-bit architecture.
Let us download 64-bit Windows installer −
(https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe)
Double click on the file where it has been downloaded to start the installation.
Although you can straight away proceed by clicking the Install Now button, it is advised to choose the installation folder with a relatively shorter path, and tick the second check box to update the PATH variable.
Accept defaults for rest of the steps in this installation wizard to complete the installation.
Open the Window Command Prompt terminal and run Python to check the success of installation.
C:\Users\Acer>python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>Python’s standard library has an executable module calledIDLE− short forIntegrated Development and Learning Environment. Find it from Window start menu and launch.
IDLE contains Python shell (interactive interpreter) and a customizable multi-window text editor with features such as syntax highlighting, smart indent, auto completion etc. It is cross-platform so works the same on Windows, MacOS and Linux. It also has a debugger with provision to set breakpoints, stepping, and viewing of global and local namespaces.
Install Python on MacOS
Earlier versions of MacOS used to have Python 2.7 pre-installed in it. However, now that the version no longer supported, it has been discontinued. Hence, you need to install Python on your own.
On a Mac computer, Python can be installed by two methods −
- Using the official installer
- Manual installation with homebrew
You can find macOS 64-bit universal2 installer on the downloads page of the official website −
https://www.python.org/ftp/python/3.11.2/python-3.11.2-macos11.pkg
The installation process is more or less similar to that on Windows. Usually, accepting the default options during the wizard steps should do the work.
The frequently required utilities such as PIP and IDLE are also installed by this installation wizard.
Alternately, you can opt for the installation from command line. You need to installHomebrew, Mac’s package manager, if it is not already available. You can follow the instructions for installation athttps://docs.brew.sh/Installation.
After that, open the terminal and enter the following commands −
brew update && brew upgrade
brew install python3Latest version of Python will now be installed.
Install Python from Source Code
If you are an experienced developer, with good knowledge of C++ and Git tool, you can follow the instructions in this section to build Python executable along with the modules in the standard library.
You must have the C compiler for the OS that you are on. In Ubuntu and MacOS,gcccompiler is available. For Windows, you should install Visual Studio 2017 or later.
Steps to Build Python on Linux/Mac
Download the source code of Python’s latest version either from Python’s official website or its GitHub repository.
Extract the files with the command −
tar -xvzf /home/python/Python-3.11.2.tgzAlternately, clone the main branch of Python’s GitHub repository. (You should have git installed)
git clone -b main https://github.com/python/cpythonA configure script comes in the source code. Running this script will create the makefile.
./configure --enable-optimizationsFollowed by this, use the make tool to build the files and then make install to put the final files in /usr/bin/ directory.
make
make installPython has been successfully built from the source code.
If you use Windows, make sure you haveVisual Studio 2017andGit for Windowsinstalled. Clone the Python source code repository by the same command as above.
Open the windows command prompt in the folder where the source code is placed. Run the following batch file
PCbuild\get_externals.batThis downloads the source code dependencies (OpenSSL, Tk etc.)
Open Visual Studio andPCbuild/sbuild.slnsolution, and build (press F10) the debug folder showspython_d.exewhich is the debug version of Python executable.
To build from command prompt, use the following command −
PCbuild\build.bat -e -d -p x64Thus, in this chapter, you learned how to install Python from the pre-built binaries as well as from the source code.
Setting Up the PATH
When the Python software is installed, it should be accessible from anywhere in the file system. For this purpose, thePATHenvironment variable needs to be updated. A system PATH is a string consisting of folder names separated bysemicolon (;). Whenever an executable program is invoked from the command line, the operating system searches for it in the folders listed in the PATH variable. We need to append Python’s installation folder to the PATH string.
In case of Windows operating system, if you have enabled “add python.exe to system path” option on the first screen of the installation wizard, the path will be automatically updated. To do it manually, open Environment Variables section from Advanced System Settings.
Edit the Path variable, and add a new entry. Enter the name of the installation folder in which Python has been installed, and press OK.
To add the Python directory to the path for a particular session in Linux −
In the bash shell (Linux)− typeexport PATH=“$PATH:/usr/bin/python3.11”and press Enter.
Python Command Line Options
We know that interactive Python interpreter can be invoked from the terminal simply by calling Python executable. Note that no additional parameters or options are needed to start the interactive session.
user@ubuntu20:~$ python3.11
Python 3.11.2 (main, Feb 8 2023, 14:49:24) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print ("Hello World")
Hello World
>>>Python interpreter also responds to the following command line options −
-c <command>
Interpreters execute one or more statements in a string, separated by newlines (;) symbol.
user@ubuntu20:~$ python3 -c "a=2;b=3;print(a+b)"
5-m <module-name>
Interpreter executes the contents of named module as the main module. Since the argument is a module name, you must not give a file extension (.py).
Consider the following example. Here, the timeit module in standard library has a command line interface. The -s option sets up the arguments for the module.
C:\Users\Acer>python -m timeit -s "text = 'sample string'; char = 'g'
'char in text'"
5000000 loops, best of 5: 49.4 nsec per loop<script>
Interpreter executes the Python code contained in script with .py extension, which must be a filesystem path (absolute or relative).
Assuming that a text file with the name hello.py contains print (“Hello World”) statement is present in the current directory. The following command line usage of script option.
C:\Users\Acer>python hello.py
Hello World? Or -h or −help
This command line option prints a short description of all command line options and corresponding environment variables and exit.
-V or —version
This command line option prints the Python version number
C:\Users\Acer>python -V
Python 3.11.2
C:\Users\Acer>python --version
Python 3.11.2Python Environment Variables
The operating system uses path environment variable to search for any executable (not only Python executable). Python specific environment variables allow you to configure the behaviour of Python. For example, which folder locations to check to import a module. Normally Python interpreter searches for the module in the current folder. You can set one or more alternate folder locations.
Python environment variables may be set temporarily for the current session or may be persistently added in the System Properties as in case of path variable.
PYTHONPATH
As mentioned above, if you want the interpreter should search for a module in other folders in addition to the current, one or more such folder locations are stored as PYTHONPATH variable.
First, savehello.pyscript in a folder different from Python’s installation folder, let us sayc:\modulepath\hello.py
To make the module available to the interpreter globally, set PYTHONPATH
C:\Users\Acer>set PYTHONPATH= c:\modulepath
C:\Users\Acer>echo %PYTHONPATH%
c:\modulepathNow you can import the module even from any directory other than c:\modulepath directory.
>>> import hello
Hello World
>>>PYTHONHOME
Set this variable to change the location of the standard Python libraries. By default, the libraries are searched in/usr/local/pythonversionin case of Linux andinstalfolder\libin Windows. For example,c:\python311\lib.
PYTHONSTARTUP
Usually, this variable is set to a Python script, which you intend to get automatically executed every time Python interpreter starts.
Let us create a simple script as follows and save it asstartup.pyin the Python installation folder −
print ("Example of Start up file")
print ("Hello World")Now set the PYTHONSTARTUP variable and assign name of this file to it. After that start the Python interpreter. It shows the output of this script before you get the prompt.
F:\311_2>set PYTHONSTARTUP=startup.py
F:\311_2>echo %PYTHONSTARTUP%
startup.py
F:\311_2>python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Example of Start up file
Hello World
>>>PYTHONCASEOK
This environment is available for use only on Windows and MacOSX, not on Linux. It causes Python to ignore the cases in import statement.
PYTHONVERBOSE
If this variable is set to a non-empty string it is equivalent to specifying python -v command. It results in printing a message, showing the place (filename or built-in module) each time a module is initialized. If set to an integer − say 2, it is equivalent to specifying -v two times. (python —v).
PYTHONDONTWRITEBYTECODE
Normally, the imported modules are compiled to.pycfile. If this variable is set to a not null string,the .pyc files on the import of source modules are not created.
PYTHONWARNINGS
Python’s warning messages are redirected to the standard error stream,sys.stderr. This environment variable is equivalent to the python -W option. The following are allowed values of this variable −
- PYTHONWARNINGS=default # Warn once per call location
- PYTHONWARNINGS=error # Convert to exceptions
- PYTHONWARNINGS=always # Warn every time
- PYTHONWARNINGS=module # Warn once per calling module
- PYTHONWARNINGS=once # Warn once per Python process
- PYTHONWARNINGS=ignore # Never warn
Python - Virtual Environment
In this chapter, you will get to know what a virtual environment in Python is, how to create and use a virtual environment for building a Python application.
When you install Python software on your computer, it is available for use from anywhere in the filesystem. This is a system-wide installation.
While developing an application in Python, one or more libraries may be required to be installed using the pip utility (e.g.,pip3 install somelib). Moreover, an application (let us say App1) may require a particular version of the library − saysomelib 1.0. At the same time another Python application (for example App2) may require newer version of same library saysomelib 2.0. Hence by installing a new version, the functionality of App1 may be compromised because of conflict between two different versions of same library.
This conflict can be avoided by providing two isolated environments of Python in the samemachine. These are called virtual environment. A virtual environment is a separatedirectory structure containing isolated installation having a local copy of Python interpreter, standard library and other modules.
The following figure shows the purpose of advantage of using virtual environment. Using the global Python installation, more than one virtual environments are created, each having different version of the same library, so that conflict is avoided.
This functionality is supported byvenvmodule in standard Python distribution. Use following commands to create a new virtual environment.
C:\Users\Acer>md\pythonapp
C:\Users\Acer>cd\pythonapp
C:\pythonapp>python -m venv myvenvHere,myvenvis the folder in which a new Python virtual environment will be created showing following directory structure −
Directory of C:\pythonapp\myvenv
22-02-2023 09:53 <DIR> .
22-02-2023 09:53 <DIR> ..
22-02-2023 09:53 <DIR> Include
22-02-2023 09:53 <DIR> Lib
22-02-2023 09:53 77 pyvenv.cfg
22-02-2023 09:53 <DIR> ScriptsThe utilities for activating and deactivating the virtual environment as well as the local copy of Python interpreter will be placed in the scripts folder.
Directory of C:\pythonapp\myvenv\scripts
22-02-2023 09:53 <DIR> .
22-02-2023 09:53 <DIR> ..
22-02-2023 09:53 2,063 activate
22-02-2023 09:53 992 activate.bat
22-02-2023 09:53 19,611 Activate.ps1
22-02-2023 09:53 393 deactivate.bat
22-02-2023 09:53 106,349 pip.exe
22-02-2023 09:53 106,349 pip3.10.exe
22-02-2023 09:53 106,349 pip3.exe
22-02-2023 09:53 242,408 python.exe
22-02-2023 09:53 232,688 pythonw.exeTo enable this new virtual environment, executeactivate.batin Scripts folder.
C:\pythonapp>myvenv\scripts\activate
(myvenv) C:\pythonapp>Note the name of the virtual environment in the parentheses. The Scripts folder contains a local copy of Python interpreter. You can start a Python session in this virtual environment.
To confirm whether this Python session is in virtual environment check thesys.path.
(myvenv) C:\pythonapp>python
Python 3.10.1 (tags/v3.10.1:2cd268a, Dec 6 2021, 19:10:37) [MSC v.1929
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs',
'C:\\Python310\\lib', 'C:\\Python310', 'C:\\pythonapp\\myvenv',
'C:\\pythonapp\\myvenv\\lib\\site-packages']
>>>The scripts folder of this virtual environment also contains pip utilities. If you install a package from PyPI, that package will be active only in current virtual environment. To deactivate this environment, rundeactivate.bat.
Python - Basic Syntax
In Python, the term syntax refers to the rules of forming a statement or expression. Python language is known for its clean and simple syntax. It also has a limited set of keywords and simpler punctuation rules as compared to other languages. In this chapter, let us understand about basic syntax of Python.
A Python program comprises of predefined keywords and identifiers representing functions, classes, modules etc. Python has clearly defined rules for forming identifiers, writing statements and comments in Python source code.
Python Keywords
A predefined set of keywords is the most important aspect of any programming language. These keywords are reserved words. They have a predefined meaning, they must be used only for its predefined purpose and as per the predefined rules of syntax. Programming logic is encoded with these keywords.
As of Python 3.11 version, there are 35 (Thirty Five) keywords in Python. To obtain the list of Python keywords, enter the following help command in Python shell.
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more
help.| 1. False | 10. class | 19. from | 28. or |
|---|---|---|---|
| 2. None | 11. continue | 20. global | 29. pass |
| 3. True | 12. def | 21. if | 30. raise |
| 4. and | 13. del | 22. import | 31. return |
| 5. as | 14. elif | 23. in | 32. try |
| 6. assert | 15. else | 24. is | 33. while |
| 7. async | 16. except | 25. lambda | 34. with |
| 8. await | 17. finally | 26. nonlocal | 35. yield |
| 9. break | 18. for | 27. not | |
| Value Keywords | True, False, None | ||
| Operator Keywords | and, or, not, in, is | ||
| Conditional Flow Keywords | if, elif, else | ||
| Keywords for loop control | for, while, break, continue | ||
| Structure Keywords | def, class, with, pass, lambda | ||
| Keywords for returning | return, yield | ||
| Import Keywords | import, from, as | ||
| Keywords about ExceptionHandling | try, except, raise, finally, assert | ||
| Keywords for Asynchronous Programming | async, await | ||
| Variable Scope Keywords | del, global, nonlocal | ||
< | Less than | a < b | |
> | Greater than | a > b | |
<= | Less than or equal to | a<=b | |
>= | Greater than or equal to | a>=b | |
| ` | =`= | Is equal to | a==b |
!= | Is not equal to | a!=b | |
| a | b | a and b | |
| F | F | F | |
| F | T | F | |
| T | F | F | |
| T | T | T | |
| a | b | a or b | |
| F | F | F | |
| F | T | T | |
| T | F | F | |
| T | T | T | |
| a | not (a) | ||
| F | T | ||
| T | F | ||
| Sr.No. | Control Statement & Description | ||
| 1 | break statementTerminates the loop statement and transfers execution to the statement immediately following the loop. | ||
| 2 | continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. | ||
| 3 | pass statementThe pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. | ||
| Sr.No. | Name & Brief Description | ||
| 1 | osThis module provides a unified interface to a number of operating system functions. | ||
| 2 | stringThis module contains a number of functions for string processing | ||
| 3 | reThis module provides a set of powerful regular expression facilities. Regular expression (RegEx), allows powerful string search and matching for a pattern in a string | ||
| 4 | mathThis module implements a number of mathematical operations for floating point numbers. These functions are generally thin wrappers around the platform C library functions. | ||
| 5 | cmathThis module contains a number of mathematical operations for complex numbers. | ||
| 6 | datetimeThis module provides functions to deal with dates and the time within a day. It wraps the C runtime library. | ||
| 7 | gcThis module provides an interface to the built-in garbage collector. | ||
| 8 | asyncioThis module defines functionality required for asynchronous processing | ||
| 9 | CollectionsThis module provides advanced Container datatypes. | ||
| 10 | FunctoolsThis module has Higher-order functions and operations on callable objects. Useful in functional programming | ||
| 11 | operatorFunctions corresponding to the standard operators. | ||
| 12 | pickleConvert Python objects to streams of bytes and back. | ||
| 13 | socketLow-level networking interface. | ||
| 14 | sqlite3A DB-API 2.0 implementation using SQLite 3.x. | ||
| 15 | statisticsMathematical statistics functions | ||
| 16 | typingSupport for type hints | ||
| 17 | venvCreation of virtual environments. | ||
| 18 | jsonEncode and decode the JSON format. | ||
| 19 | wsgirefWSGI Utilities and Reference Implementation. | ||
| 20 | unittestUnit testing framework for Python. | ||
| 21 | randomGenerate pseudo-random numbers | ||
| Sr.No. | Function & Description | ||
| 1 | abs()Returns absolute value of a number | ||
| 2 | aiter()Returns an asynchronous iterator for an asynchronous iterable | ||
| 3 | all()Returns true when all elements in iterable is true | ||
| 4 | anext()Returns the next item from the given asynchronous iterator | ||
| 5 | any()Checks if any Element of an Iterable is True | ||
| 6 | ascii()Returns String Containing Printable Representation | ||
| 7 | bin()Converts integer to binary string | ||
| 8 | bool()Converts a Value to Boolean | ||
| 9 | breakpoint()This function drops you into the debugger at the call site and calls sys.breakpointhook() | ||
| 10 | bytearray()returns array of given byte size | ||
| 11 | bytes()returns immutable bytes object | ||
| 12 | callable()Checks if the Object is Callable | ||
| 13 | chr()Returns a Character (a string) from an Integer | ||
| 14 | classmethod()Returns class method for given function | ||
| 15 | compile()Returns a code object | ||
| 16 | complex()Creates a Complex Number | ||
| 17 | delattr()Deletes Attribute From the Object | ||
| 18 | dict()Creates a Dictionary | ||
| 19 | dir()Tries to Return Attributes of Object | ||
| 20 | divmod()Returns a Tuple of Quotient and Remainder | ||
| 21 | enumerate()Returns an Enumerate Object | ||
| 22 | eval()Runs Code Within Program | ||
| 23 | exec()Executes Dynamically Created Program | ||
| 24 | filter()Constructs iterator from elements which are true | ||
| 25 | float()Returns floating point number from number, string | ||
| 26 | format()Returns formatted representation of a value | ||
| 27 | frozenset()Returns immutable frozenset object | ||
| 28 | getattr()Returns value of named attribute of an object | ||
| 29 | globals()Returns dictionary of current global symbol table | ||
| 30 | hasattr()Returns whether object has named attribute | ||
| 31 | hash()Returns hash value of an object | ||
| 32 | help()Invokes the built-in Help System | ||
| 33 | hex()Converts to Integer to Hexadecimal | ||
| 34 | id()Returns Identify of an Object | ||
| 35 | input()Reads and returns a line of string | ||
| 36 | int()Returns integer from a number or string | ||
| 37 | isinstance()Checks if a Object is an Instance of Class | ||
| 38 | issubclass()Checks if a Class is Subclass of another Class | ||
| 39 | iter()Returns an iterator | ||
| 40 | len()Returns Length of an Object | ||
| 41 | list()Creates a list in Python | ||
| 42 | locals()Returns dictionary of a current local symbol table | ||
| 43 | map()Applies Function and Returns a List | ||
| 44 | max()Returns the largest item | ||
| 45 | memoryview()Returns memory view of an argument | ||
| 46 | min()Returns the smallest value | ||
| 47 | next()Retrieves next item from the iterator | ||
| 48 | object()Creates a featureless object | ||
| 49 | oct()Returns the octal representation of an integer | ||
| 50 | open()Returns a file object | ||
| 51 | ord()Returns an integer of the Unicode character | ||
| 52 | pow()Returns the power of a number | ||
| 53 | print()Prints the Given Object | ||
| 54 | property()Returns the property attribute | ||
| 55 | range()Returns a sequence of integers | ||
| 56 | repr()Returns a printable representation of the object | ||
| 57 | reversed()Returns the reversed iterator of a sequence | ||
| 58 | round()Rounds a number to specified decimals | ||
| 59 | set()Constructs and returns a set | ||
| 60 | setattr()Sets the value of an attribute of an object | ||
| 61 | slice()Returns a slice object | ||
| 62 | sorted()Returns a sorted list from the given iterable | ||
| 63 | staticmethod()Transforms a method into a static method | ||
| 64 | str()Returns the string version of the object | ||
| 65 | sum()Adds items of an Iterable | ||
| 66 | super()Returns a proxy object of the base class | ||
| 67 | tuple()Returns a tuple | ||
| 68 | type()Returns the type of the object | ||
| 69 | vars()Returns the dict attribute | ||
| 70 | zip()Returns an iterator of tuples | ||
| 71 | import()Function called by the import statement | ||
| Sr.No. | Function & Description | ||
| 1 | abs() functionThe abs() function returns the absolute value of x, i.e. the positive distance between x and zero. | ||
| 2 | max() functionThe max() function returns the largest of its arguments or largest number from the iterable (list or tuple). | ||
| 3 | min() functionThe function min() returns the smallest of its arguments i.e. the value closest to negative infinity, or smallest number from the iterable (list or tuple) | ||
| 4 | pow() functionThe pow() function returns x raised to y. It is equivalent to xy. The function has third optional argument mod. If given, it returns (xy) % mod value | ||
| 5 | round() Functionround() is a built-in function in Python. It returns x rounded to n digits from the decimal point. | ||
| 6 | sum() functionThe sum() function returns the sum of all numeric items in any iterable (list or tuple). An optional start argument is 0 by default. If given, the numbers in the list are added to start value. | ||
| Sr.No | Escape Sequence & Meaning | ||
| 1 | “\n“Backslash and newline ignored | ||
| 2 | \Backslash () | ||
| 3 | ’Single quote (‘) | ||
| 4 | ”Double quote (“) | ||
| 5 | \aASCII Bell (BEL) | ||
| 6 | \bASCII Backspace (BS) | ||
| 7 | \fASCII Formfeed (FF) | ||
| 8 | \nASCII Linefeed (LF) | ||
| 9 | \rASCII Carriage Return (CR) | ||
| 10 | \tASCII Horizontal Tab (TAB) | ||
| 11 | \vASCII Vertical Tab (VT) | ||
| 12 | \oooCharacter with octal value ooo | ||
| 13 | \xhhCharacter with hex value hh |