0% found this document useful (0 votes)
6 views30 pages

Python Notes

Python is a widely-used, high-level programming language known for its simplicity and versatility, applicable in various domains such as web development, data science, and automation. It is an interpreted and interactive language, making it easy to learn and use, with a rich set of libraries and frameworks. Python's evolution includes significant versions that introduced features enhancing its functionality and performance, culminating in the latest releases that focus on usability and speed improvements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views30 pages

Python Notes

Python is a widely-used, high-level programming language known for its simplicity and versatility, applicable in various domains such as web development, data science, and automation. It is an interpreted and interactive language, making it easy to learn and use, with a rich set of libraries and frameworks. Python's evolution includes significant versions that introduced features enhancing its functionality and performance, culminating in the latest releases that focus on usability and speed improvements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is Python?

Python is a very popular open source, general-purpose interpreted, interactive, object-


oriented, and high-level programming language. Python is dynamically-typed and garbage-
collected programming language. It was created by Guido van Rossum during 1985- 1990.
Like Perl, Python source code is also available under the GNU General Public License
(GPL).

1) High-level

Python is a high-level programming language that makes it easy to learn. Python doesn’t
require you to understand the details of the computer in order to develop programs
efficiently.

2) General-purpose

Python is a general-purpose language. It means that you can use Python in various domains
including:

 Web applications
 Big data applications
 Testing
 Automation
 Data science, machine learning, and AI
 Desktop software
 Mobile apps

The targeted language like SQL which can be used for querying data from relational
databases.

3) Interpreted

Python is an interpreted language. To develop a Python program, you write Python code into
a file called source code.

To execute the source code, you need to convert it to the machine language that the computer
can understand. And the Python interpreter turns the source code, line by line, once at a
time, into the machine code when the Python program executes.

Compiled languages like Java and C# use a compiler that compiles the whole source code
before the program executes.

4) Interactive

You can actually sit at a Python prompt and interact with the interpreter directly to write your
programs.

1
Features of Python
The latest release of Python is 3.x. As mentioned before, Python is one of the most widely
used languages on the web. I'm going to list a few of them here:

 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode that allows
interactive testing and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
 Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries, and Windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
 Scalable − Python provides a better structure and support for large programs than
shell scripting.

Applications of Python:
Python, a versatile programming language, finds applications in diverse fields, including web
development, data science, automation, and more, with notable uses in platforms like
Instagram, Spotify, and Pinterest.
Here's a more detailed look at Python's applications:
Web Development:

 Frameworks:

Python excels in web development thanks to frameworks like Django and Flask,
which simplify the creation of dynamic and robust web applications.

 Backend Infrastructure:
Many popular websites and applications, including Instagram, rely on Python for their
backend infrastructure.
Example:
Instagram, initially developed using Django, leverages Python for its backend.

Data Science and Analytics:

 Data Analysis:

Python's libraries like Pandas and SciPy make it a powerful tool for analyzing and
manipulating large datasets.

Data Visualization:

2
Python offers various libraries for creating interactive and informative visualizations,
aiding in data exploration and communication.
Machine Learning:
Python is a leading language for machine learning, with libraries like Scikit-learn and
TensorFlow enabling the development of predictive models and algorithms.
Automation and Scripting:
Task Automation: -Python scripts can automate repetitive tasks, streamlining
workflows and saving time.
System Administration:
Python's ability to interact with operating systems and network protocols makes it
useful for system administration tasks.
Web Scraping:
Python libraries like Beautiful Soup and Scrapy facilitate the extraction of data from
websites.
Other Applications:

 Desktop GUI:

Python offers libraries like Tkinter and PyQt for creating graphical user interfaces for
desktop applications.

Audio and Video Processing:


Python libraries like PyDub and MoviePy enable audio and video manipulation and
processing.
Embedded Systems:
Python's lightweight nature and ease of use make it suitable for embedded systems
programming, with frameworks like MicroPython and CircuitPython.
CAD Applications:
Python can be used as a scripting language in CAD software to automate tasks and
extend functionality.
Operating Systems:
Python is used to write system utilities, network protocols, and other components of
operating systems.

Is python a scripting language?

Python is a programming language. You can write programs in [Link] is also a


scripting language. You can write scripts in Python.

What is Scripting language?

Scripting languages are interpreted from source code directly, without the need for compilation,
using an interpreter to translate commands. It is important to note that all scripting languages are
programming languages, but not all programming languages are scripting languages.

Types of Scripting Language


Scripts are widely used in the creation of various dynamic web pages. Based on where the
script execution takes place, there are two types of scripting languages such as client side and
server side.

3
1. Server-side scripting language:

A server-side scripting language operates on the server to generate responses for client
requests, with the primary objective of creating dynamic content for web pages. In this
process, web servers execute these server-side scripts. This approach is considered more
secure than client-side scripting, as the server handles the execution, enhancing overall
security measures. Examples of server-side scripting languages include PHP, Java, Ruby,
Python, C#, and Go.

2. Client-side scripting language:

A client-side scripting language executes scripts directly in the client's web browser without
the need for server interaction. Its primary objectives encompass tasks such as data
validation, handling UI components, and managing dynamic elements like navigation tools.
In this scenario, the browser runs the code locally on the user's computer, independent of the
server. However, it's worth noting that client-side scripting is considered less secure
compared to server-side scripting due to its reliance on the user's browser. Examples of
client-side scripting languages include JavaScript, TypeScript, HTML/CSS, and AJAX.

Features
1. Cross Platform Dependency:

 The scripting languages are independent of the Operating system they are executing.

 These codes work on all types of OS without any major modifications.

2. Fast Development:

 The scripting languages are easy to code, test, and debug and make any changes faster than
other programming languages.

 Therefore the software development process takes place very fast.

3. Easy Integration:

 The scripting language can be easily integrated with other programming languages like Java,
and C++.

4. Versatile:

 Scripting languages are very versatile they can be used for different purposes.

 It can be used for web development, scientific study, administration, and analysis.

5. Easy to learn:

 One of the major benefits of scripting language is that it is easy to learn when compared to
programming languages.

 As it is open source it has an online community to support.

4
Usage of scripting languages
Different scripting languages have different usages, and they can be used in different
industries. Some of them include:

 Automation: They are widely used to automate tasks like data manipulation,
maintenance, maintenance, and managing updates and backups.

 Dynamic web development: Using JavaScript and its interactive framework greatly
enhances the user experience of the website. They are used to develop web
applications on the client and server sides.

 System administration and configuration: Scripting languages are widely used to


configure and manage networks using scripting languages like PowerShell and Bash.

 Data Analytics: Scripting languages like R programming and Python are widely used
as tools for the analysis of the data and also to visualize it.

 Testing: They are used to check the software product developed and ensure the
quality is maintained. Frameworks like Selenium and PyTest are used for testing
software components.

 Cross-platform development: They are used to develop cross-platform applications,


which include both web and mobile applications, with JavaScript frameworks like
[Link] and [Link].

 Embedded System: Scripts can be written to embed systems, IoT devices,


microprocessors, and microcontrollers into the hardware to collect and implement
different functionalities.

Difference between scripting language and Programming language

Scripting Language Programming Language


A scripting language is a language that A Programming language is a language which is
1. uses a naive method to bring codes to used by humans to navigate their communication
a runtime environment with computers.
Programming languages are of three types -:

 low-level Programming language


These are made for a particular
2.
runtime environment.  Middle-level Programming language

 High-level Programming language

They are used to create dynamic web Programming languages are used to write
3.
applications computer programs.
Scripting languages contain different
4. They are high-speed languages.
libraries
Example -: Bash, Ruby, Python,
5. Example -: C++, Java, PHP High-level etc.
JavaScript etc.
6. Scripting languages can be easily Programming languages are translation free
ported among various operating languages
5
systems.
7. These languages requires a host. These languages are self executable.
8. Do not create a .exe file. These generate .exe files.
Most of the scripting languages are Most of the programming languages are
9.
interpreted language. compiled languages.
All the scripting languages are All the programming languages are not scripting
10.
programming languages. languages.
It is easier to learn than programming
11. It can take significant amount of time to learn.
language.
It is less code intensive when
12. compared with programming It is code intensive.
language.
13. It does not create any binary files. It does creates binary files.
It is easy for the beginner to write and It is difficult for the beginner to write and
14.
understand the code. understand the code.
15. It is run inside another program. It is independently run.
16. It needs lesser line of codes. It needs numerous lines of code.
17. It has low maintenance cost. It has high maintenance cost.

What is Python Virtual Machine (PVM)?


The Python Virtual Machine (PVM), or more commonly CPython, is the runtime
environment that executes Python bytecode, a low-level set of instructions derived from
Python source code. It allows Python programs to run on various operating systems by
abstracting the underlying hardware.
Here's a more detailed breakdown:

What it is:

The PVM is an abstract machine that interprets and executes Python bytecode.

How it works:

Python source code (e.g., .py files) is compiled into bytecode (e.g., .pyc files).

The PVM then reads and executes this bytecode, effectively running your Python
program.
Why it's important:

Platform Independence: Bytecode is platform-independent, meaning Python


programs can run on any system with a compatible Python interpreter.

Abstraction: The PVM hides the complexities of the underlying hardware, allowing
developers to focus on writing code without worrying about platform-specific details. 
CPython:
The most widely used Python implementation, CPython, is the name of the VM that
interprets and executes Python bytecode.
Other Python Implementations:
Besides CPython, there are other Python implementations like Jython (runs on JVM)
and IronPython (runs on .NET), each with its own VM.

6
Python Version History

1. The Birth of Python


Python 0.9.0 (1991)

Python's journey began with version 0.9.0, released by Guido van Rossum in 1991. This
initial release included core features such as exception handling, functions, and the core data
types: list, dict, str, and others. It also introduced the module system, allowing the
organization of code into reusable libraries.

2. Early Versions and Growth


Python 1.0 (1994)

Python 1.0 marked the official public release, bringing in significant features such as:

 Lambda, Map, Filter, and Reduce: Functional programming constructs that allowed concise
and powerful data manipulation.

 Exception Handling: A structured way to handle errors and exceptions in code.

Python 1.5 (1997)

Version 1.5 introduced important updates, including:

 Standard Library Enhancements: Expansion of the standard library, making Python more
versatile.

 Unicode Support: Initial support for Unicode, facilitating internationalization.

3. Establishing a Strong Foundation


Python 2.0 (2000)

Python 2.0 was a pivotal release that laid the groundwork for modern Python with:

 List Comprehensions: A syntactic construct for creating lists based on existing lists.
7
 Garbage Collection: Automatic memory management to reclaim unused memory.

 Unicode Support: Full support for Unicode, enabling better handling of international text.

Python 2.7 (2010)

Python 2.7 was the final major release in the Python 2.x series, bringing several features from
Python 3.x to ease the transition:

 Ordered Dictionaries: Dictionaries that maintain the insertion order of keys.

 Set Literals: A more convenient way to define sets.

 Improved Syntax: Enhanced syntax features, including more robust error handling and new
string formatting methods.

4. The Shift to Python 3


Python 3.0 (2008)

Python 3.0, also known as "Python 3000" or "Py3k," was a revolutionary release designed to
fix inconsistencies and remove redundant constructs from Python 2.x:

 Print Function: print became a function, enhancing consistency and flexibility.

 New Syntax and Semantics: Changes to integer division, Unicode string handling, and more.

 Removal of Deprecated Features: Simplification of the language by removing outdated


features.

Python 3.4 (2014)

Version 3.4 introduced several significant enhancements:

 Asyncio: A framework for writing asynchronous programs, allowing for concurrent code
execution.

 Pathlib: An object-oriented filesystem paths library.

Python 3.5 (2015)

Python 3.5 brought in important features for modern programming:

 Type Hints: A syntax for adding type annotations to function arguments and return values.

 Async and Await: Syntactic support for asynchronous programming, making async code
more readable and maintainable.

5. Modern Python

8
Python 3.6 (2016)

Python 3.6 was a landmark release with multiple enhancements:

 Formatted String Literals (f-strings): A concise and readable way to embed expressions
inside string literals.

 Underscores in Numeric Literals: Improved readability of large numbers.

 Asynchronous Generators: Enhancements to asynchronous programming.

Python 3.7 (2018)

This version focused on performance and new features:

 Data Classes: A decorator for automatically generating special methods like __init__ and
__repr__ in classes.

 Context Variables: A way to manage context-local state.

Python 3.8 (2019)

Python 3.8 introduced several new features and optimizations:

 Walrus Operator (:=): An assignment expression that allows assignment and return of a
value within an expression.

 Positional-only Parameters: A way to specify arguments that can only be passed


positionally.

Python 3.9 (2020)

Python 3.9 continued to enhance the language:

 Dictionary Merge and Update Operators: New operators | and |= for merging and updating
dictionaries.

 String Methods: New methods like [Link]() and [Link]().

Python 3.10 (2021)

Python 3.10 focused on usability and language consistency:

 Pattern Matching: A powerful feature for matching complex data structures.

 Parenthesized Context Managers: Support for multiple context managers in a single with
statement.

Python 3.11 (2022)

Python 3.11 aimed at improving performance and developer experience:

 Performance Improvements: Significant speed improvements across various operations.


9
 Error Messages: More informative and precise error messages.

Python 3.12 (2023)

The future release of Python 3.12 bring more optimizations and features, continuing the
evolution of the language.

 Improved Error Messages in Python

 More Flexibility in Python F-String

 Type Parameter Syntax

 Improvement in Modules

 Syntactic Formalization of f-strings

Python 3.13 (2024)

The future release of Python 3.12 is expected to bring more optimizations and features,
continuing the evolution of the language.

Ways of executing code in Python


There are 3 standard ways of using Python, namely:

1. Using Interactive Mode


2. Using Command-line
3. Using an Integrated Development Environment (IDE)

Let’s explore them in detail.

Using Interactive mode:

In this mode, you basically call the Python interpreter and throw a bunch of commands to it
to execute. To enter into the interactive mode of Python use the below commands:

$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS

Example:

Here we will enter the interactive mode and ask Python to solve a simple computation. Look
at the image below:

10
Using command-line:

In this method of using python, you need to call the python interpreter first and then ask it to
run a python file.

Example:

Let’s make a python file that simply computes the sum of 5 and 10 and returns the result and
save it as [Link] file. This would look somewhat like the below:

Now execute the file by using the below command:

python [Link]

This will result in the following:


11
Using an IDE

There are plenty of IDEs available on the internet like VScode, Sublime editor, and pycharm,
etc. Here we will demonstrate the use of python using Jupyter Notebook, a python IDE from
Anaconda.

Example:

Here we will write a simple python code and ask the IDE to execute it in Python.

Now if you hit the Run Button on the IDE it will call for the interpreter automatically and
execute the program. This would look like below:

12
Python Data Types

1 Numeric Types int, float, complex

2 Sequence Types str, list, tuple, range

3 Set Types set, frozenset

4 Mapping Type dict

5 Boolean Type bool

6 Binary Types bytes, bytearray, memoryview

7 None Type NoneType

13
[Link]

Numeric Data Types


Numeric Data Types in Python are used to store data in the numeric form.
We can describe Numbers in different ways, including integer, floating-
point, or complex numbers.

There are mainly three types of Numeric data types:

S. Numeric Description
No. Data Type

1 int Store signed integers of non-limited length

2 float Store floating decimal points and accurate up to 15 decimal places

3 complex Store complex numbers

Let us these numeric data types in detail.

1. Integer (int)
An Integer is said to be a whole number (positive, negative, or zero)
without any decimal or fractional part. For example, 15, -7, 12, 0, -125,
14
268, and more. The integer values are represented by the 'int' class. In
Python, there is no limit to length of the integer values. The value can be
of any length and can reach the maximum available memory of the
system.

Let us consider an example illustrating how to declare an integer in


Python.

Example
1. # python program to show how to declare integers in Python
2.
3. # initializing some variables with integers
4. var_1 = 16 # positive integer
5. var_2 = -21 # negative integer
6. var_3 = 0 # zero
7.
8. # printing the types of initialized variables
9. print("Data Type of", var_1, "=", type(var_1))
[Link]("Data Type of", var_2, "=", type(var_2))
[Link]("Data Type of", var_3, "=", type(var_3))
Execute Now

Output:

Data Type of 16 = <class 'int'>


Data Type of -21 = <class 'int'>
Data Type of 0 = <class 'int'>
Explanation:

In the above snippet of code, we have initialized few variables having


some integer values. We have then used the type() method to return their
types and print them for the users. As a result, we can observe that all the
initialized variables belong to the 'int' class.

2. Floating-point (float)
A floating-point number is said to be a number that can have a decimal
point or be written in scientific notation. For example, 14.523, 3.14, 1.5e3,
and more. In Python, a class known as 'float' is used for storing decimal
numbers which can either be positive, negative or zero. It has a support
for scientific notations (e.g., 1.6e4 = 16000.0). The float class follows IEEE
754 floating-point standard and has a precision limit up to 15 decimal
points.

Let us consider an example illustrating how to declare a float in Python.

Example
1. # python program to show how to declare floating-point numbers in Python
2.
3. # initializing some variables with floating-point numbers
4. var_1 = 1.72 # positive float
5. var_2 = -0.05 # negative float
6. var_3 = 0.0 # zero as a float
7. var_4 = 1.6e4 # scientific notation
8.
15
9. # printing the types of initialized variables
[Link]("Data Type of", var_1, "=", type(var_1))
[Link]("Data Type of", var_2, "=", type(var_2))
[Link]("Data Type of", var_3, "=", type(var_3))
[Link]("Data Type of", var_4, "=", type(var_4))
Execute Now

Output:

Data Type of 1.72 = <class 'float'>


Data Type of -0.05 = <class 'float'>
Data Type of 0.0 = <class 'float'>
Data Type of 16000.0 = <class 'float'>
Explanation:

In the above snippet of code, we have initialized few variables having


some float values. We have then used the type() method to return their
types and print them for the users. As a result, we can observe that all the
initialized variables belong to the 'float' class.

3. Complex Numbers (complex)


A Complex Number is a number consisting of a real part and an imaginary
part. It is written in the form:

1. a + bj
where:

o a = It is the real part. It can either a float or integer.


o b = It is the imaginary part. It can either a float or integer.
o j = it represents √(-1). It is an imaginary unit used in Python.
In Python, the complex numbers are stored in a class called 'complex'.

Let us consider an example illustrating how to declare a complex number


in Python.

Example
1. # python program to show how to declare complex numbers in Python
2.
3. # initializing some variables with complex numbers
4. var_1 = 3 + 5j # where 2 is the real part and 5 is the imaginary part
5. var_2 = -3.4 + 2.8j
6. var_3 = -5 - 1.9j
7. var_4 = -6 + 0j
8.
9. # printing the types of initialized variables
[Link]("Data Type of", var_1, "=", type(var_1))
[Link]("Data Type of", var_2, "=", type(var_2))
[Link]("Data Type of", var_3, "=", type(var_3))
[Link]("Data Type of", var_4, "=", type(var_4))
Execute Now

Output:

Data Type of (3+5j) = <class 'complex'>


Data Type of (-3.4+2.8j) = <class 'complex'>
16
Data Type of (-5-1.9j) = <class 'complex'>
Data Type of (-6+0j) = <class 'complex'>
Explanation:

In the above snippet of code, we have initialized few variables with some
complex numbers. We have then used the type() method to return their
types and print them for the users. As a result, we can observe that all the
initialized variables belong to the 'complex' class.

Sequence Data Types


Sequence Data Types in Python are used to store multiple elements in an
ordered manner. There are mainly three types of sequence data types
available in Python:

S. Sequence Data Description


No. Type

1 list Ordered, mutable, and heterogeneous


collection of elements

2 tuple Ordered, and immutable collection of


elements

3 str Sequence of characters


Let us these sequence data types in detail.

1. Lists (list)
Similar to array in other programming languages, List in Python is an
ordered collection of data elements. It can simultaneously store elements
of different data types separately by commas. Lists are mutable in nature,
meaning that we can modify its elements anytime.

Let us see an example demonstrating how to initialize a list in Python:

Example
1. # simple python program to show how to initialize a list
2.
3. # creating a list
4. list_1 = [1, 0.5, 'hello', 1+5j, 1.7e2, -12, 'welcome'] # different types of element
s
5.
6. # printing details
7. print("Initialized List:", list_1) # printing elements of the list
8. print("Data Type:", type(list_1)) # printing data type
Execute Now

Output:

Initialized List: [1, 0.5, 'hello', (1+5j), 170.0, -12, 'welcome']


Data Type: <class 'list'>
Explanation:
17
In the above snippet of code, we have initialized a list with some items of
mixed data types. We have then printed the list for reference, and used
the type() method to return their types and print them for the users. As a
result, we can observe that the initialized list can store multiple data types
simultaneously and belongs to the 'list' class.

3. Tuples (tuple)
Tuples are the ordered sequence of data elements same as the lists. The
only difference between the two is that Tuples are immutable in nature.
This means that we cannot modify the elements of the tuple once created.

In Python, we use parentheses '()' in order to store elements in tuple. Let


us see an example demonstrating how to initialize a tuple in Python:

Example
1. # simple python program to show how to initialize a tuple
2.
3. # creating a tuple
4. tuple_1 = (1, 0.5, 'hello', 1+5j, 1.7e2, -12, 'welcome') # different types of eleme
nts
5.
6. # printing details
7. print("Initialized tuple:", tuple_1) # printing elements of the tuple
8. print("Data Type:", type(tuple_1)) # printing data type
Execute Now

Output:

Initialized tuple: (1, 0.5, 'hello', (1+5j), 170.0, -12, 'welcome')


Data Type: <class 'tuple'>
Explanation:

In the above snippet of code, we have initialized a tuple with some items
of mixed data types. We have then printed the tuple for reference, and
used the type() method to return their types and print them for the users.
As a result, we can observe that the initialized tuple can store multiple
data types simultaneously and belongs to the 'tuple' class.

3. String (str)
A String is a sequence of characters enclosed in single (') or double (")
quotes. Similar to Tuples, strings are also immutable in nature. In Python,
the strings are represented using the 'str' class.

Let us see an example demonstrating how to initialize a string in Python:

Example
1. # simple python program to show how to initialize string
2.
3. # initializing variables with some string
4. str_1 = 'TpointTech'
5. str_2 = 'I love learning Python from TpointTech'
6.
7. # printing details

18
8. print("String 1 :", str_1) # printing string
9. print("Data Type of String 1:", type(str_1)) # printing data type
10.
[Link]("String 2 :", str_2) # printing string
[Link]("Data Type of String 2:", type(str_2)) # printing data type
Execute Now

Output:

String 1 : TpointTech
Data Type of String 1: <class 'str'>
String 2 : I love learning Python from TpointTech
Data Type of String 2: <class 'str'>
Explanation:

In the above snippet of code, we have defined two variables as str_1 and
str_2 and initialized them with some text. We have then printed the
strings, and used the type() method to return their types and print them
for the users. As a result, the printed texts belong to the 'str' class.

4. Range (range)
Additionally, there is one more type belonging to the sequence data type.
This data type is known as range. A range is an object in Python used to
represent the sequence of numbers.

Let us consider an example illustrating the way of initializing range in


Python.

Example
1. # simple python program to show how to initialize a range
2.
3. # creating a range
4. r = range(3, 26, 2)
5.
6. # printing the results
7. print("Range:", r) # printing range
8. print("Range as List:", list(r)) # printing range as a list
9. print("Data Type:", type(r)) # printing data type
Execute Now

Output:

Range: range(3, 26, 2)


Range as List: [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]
Data Type: <class 'range'>
Explanation:

In the above snippet of code, we have used the range() function to create
a range from 3 to 26 incrementing by 2. We have then printed the range
for reference. We have also printed the range as a list displaying all the
elements of the generated sequence. At last, we have printed its data
type. As a result, we can observe that it belongs to the 'range' class.

Set Data Types


19
Set Data Types in Python are used to store unordered collections of
unique elements.

There are generally two types belonging to the set data types.

S. No. Set Data Description


Type

1 set Unordered, unique, mutable, and unindexed collection of elements

2 frozenset Unordered, unique, immutable, and unindexed collection of elements

Let us these set data types in detail.

1. set
A set in Python is said to be an unordered, mutable and unindexed
collection of unique data elements. Sets are useful in storing distinct
values and perform various mathematical operations like union,
intersection, and difference.

In order to create a set in Python, we need to use {} or the set()


constructor. Let us take an example illustrating the ways of initializing
sets in Python.

Example
1. # simple python program to show how to initialize a set
2.
3. # creating sets
4. set_1 = {"mango", "apple", "orange", "banana"} # using {}
5. set_2 = set(["ginger", "lemon", "potato", "tomato"])
6.
7. # printing the results
8. print("Set 1:", set_1) # set 1
9. print("Data type of Set 1:", type(set_1)) # data type of set 1
10.
[Link]("Set 2:", set_2) # set 2
[Link]("Data type of Set 2:", type(set_2)) # data type of set 2
Execute Now

Output:

Set 1: {'mango', 'orange', 'banana', 'apple'}


Data type of Set 1: <class 'set'>
Set 2: {'lemon', 'tomato', 'potato', 'ginger'}
Data type of Set 2: <class 'set'>
Explanation:

In the above example, we have initialized two sets using different


approaches. The first one is initialized using the {} brackets and the other
one is initialized using the set() constructor. We have then printed the

20
elements of both sets along with their data types. As a result, we can
observe that both sets belong to the 'set' class.

2. frozenset
In Python, a function called frozenset() is used to return a frozenset
object. This object is an immutable, unordered data type. A frozenset
consists of unique items, making it similar to the set data type; however,
it is unchangeable like tuples.

Let us look at an example illustrating the way of initializing a frozenset in


Python.

Example
1. # simple python program to show how to create a frozeset
2.
3. # creating an iterable
4. list_1 = ["berries", "orange", "mango", "apple"] # a list
5.
6. # using the frozenset() function to create a frozenset object
7. f_1 = frozenset(list_1)
8.
9. # printing results
[Link]("Frozenset:", f_1) # frozenset
[Link]("Data Type:", type(f_1)) # data type
Execute Now

Output:

Frozenset: frozenset({'mango', 'orange', 'berries', 'apple'})


Data Type: <class 'frozenset'>
Explanation:

In the above example, we have initialized a list as an iterable. We have


then used the frozenset() function passing the list. We then printed the
returned object along with its data type. As a result, we can observe that
the frozenset object has been created successfully and it belongs to the
'frozenset' class.

Mapping Data Type - Dictionary (dict)


In Python, we can store elements in key-value pair using Dictionaries.
Dictionary is an ordered collection of elements where the unique
identifiers are associated with each value.

Let us consider an example of initializing dictionary in Python.

Example
1. # simple python program to show how to create a dictionary
2.
3. # creating a dictionary
4. person_1 = {
5. 'name' : 'Mark',
6. 'age': '25',

21
7. 'gender' : 'Male',
8. }
9.
10.# printing results
[Link]("Person Details:\n", person_1) # dictionary
[Link]("Data Type:", type(person_1)) # its data type
Execute Now

Output:

Person Details:
{'name': 'Mark', 'age': '25', 'gender': 'Male'}
Data Type: <class 'dict'>
Explanation:

In the above example, we have created a dictionary and printed its data
type for reference. Here 'name', 'age', and 'gender' are the keys having
the values as 'Mark', '25', and 'Male', respectively.

Boolean Data Type (bool)


Boolean is a built-in data type in Python that has two constant values:

o True: The Boolean value 'True' represents 1 and is returned when the
expression or object are considered truthful.
o False: The Boolean value 'False' represents 0 and is returned when the
expression or object turns out to be false.
We can also evaluate non-Boolean objects in a Boolean context and
identify them as either True or False. A class called 'bool' is used to store
the Boolean objects in Python.

Note: Python is case-sensitive; therefore, it will return error


if the Boolean values (True and False) is passed in lowercase
(e.g., true, false).
Let us consider an example of Boolean data type in Python.

Example
1. # simple python program to show the Boolean data types
2.
3. # initializing variables
4. a = True
5. b = False
6. # c = true <= Will Return Error
7.
8. # printing the results
9. print("Value of a:", a)
[Link]("Data Type of a:", type(a))
[Link]("Value of b:", b)
[Link]("Data Type of b:", type(b))
13.# print("Value of c:", c)
14.# print("Data Type of c:", type(c))
Execute Now

Output:
22
Value of a: True
Data Type of a: <class 'bool'>
Value of b: False
Data Type of b: <class 'bool'>
Explanation:

In the above example, we have initialized two variables - a, and b with the
values - True and False, respectively. We then printed them for reference
and used the type() function to return their data types. As a result, we can
observe that the variable a, and b, belongs to the 'bool' class.

Binary Data Types


Python offers binary data types in order to handle raw binary data. These
data types include:

S. No. Binary Data Type Description

1 bytes Immutable sequence of byt

2 bytearray Mutable sequence of bytes

3 memoryview Efficient access to binary d

Let us these binary data types in detail.

1. bytes
The bytes data type is an immutable sequence of bytes, value ranging
from 0 to 255. It is useful for working with binary files, network
communication, or cryptographic functions.

Let us consider an example of the bytes data type in Python.

Example
1. # simple python program to show the creation of bytes object
2.
3. # creating bytes using a list of integers (0-255)
4. obj_1 = bytes([78, 79, 80, 81, 82]) # ASCII values
5.
6. # printing results
7. print("Value of Object 1:", obj_1)
8. print("Data Type of Object 1:", type(obj_1))
Execute Now

Output:

Value of Object 1: b'NOPQR'


Data Type of Object 1: <class 'bytes'>
Explanation:
23
In the above example, we have used the bytes() function to create a byte
object using the list of integers - 78, 79, 80, 81, and 82 respectively. We
then printed the initialized object and its type. As a result, we can observe
that the value of object is printed as b'NOPQR', belonging to the 'bytes'
class.

2. bytearray
Unlike bytes, the bytearray data type is a mutable sequence of bytes that
allows modification in the binary data in place.

In order to create an object of the bytearray class, we passes a given


iterable to the built-in bytearray() function.

Let us consider an example of the bytearray data type in Python.

Example
1. # simple python program to show the creation of bytearray object
2.
3. # creating a bytearray object using a list of integers
4. obj_1 = bytearray([78, 79, 80, 81, 82]) # ASCII values
5.
6. # printing results
7. print("Value of Object 1:", obj_1)
8. print("Data Type of Object 1:", type(obj_1))
Execute Now

Output:

Value of Object 1: bytearray(b'NOPQR')


Data Type of Object 1: <class 'bytearray'>
Explanation:

In the above example, we have used the bytearray() function to create a


bytearray object using the list of integers - 78, 79, 80, 81, and 82
respectively. We then printed the initialized object and its type. As a
result, we can observe that the value of object is printed as b'NOPQR',
belonging to the 'bytearray' class.

3. memoryview
memoryview is a data type that is used to provide a lightweight and
efficient way to access binary data without copying it. This data type is
useful for large data operations where performance has relevance.

Let us consider an example of the memoryview data type in Python.

Example
1. # simple python program to show the creation of bytearray object
2.
3. # creating a bytearray object using a list of integers
4. obj_1 = bytearray([78, 79, 80, 81, 82]) # ASCII values
5.
6. # creating a memoryview object
7. obj_2 = memoryview(obj_1)
24
8.
9. # printing results
[Link]("Value of Object 2:", obj_2)
[Link]("Data Type of Object 2:", type(obj_2))
Execute Now

Output:

Value of Object 2: <memory at 0x7ebcf57bf640>


Data Type of Object 2: <class 'memoryview'>
Explanation:

In the above example, we have used the bytearray() function to create a


bytearray object using the list of integers - 78, 79, 80, 81, and 82
respectively. We have then used the memoryview() function to convert
the bytearray object into the memoryview object. We then printed the
value of the object and its type. As a result, we can observe that the value
of object is printed as <memory at 0x7ebcf57bf640>, belonging to the
'memoryview' class.

None Data Type (NoneType)


Python also offers a special data type, known as NoneType. This data type
consists of only one value - None. It is used to represent the missing
values, function return values, and placeholders in Python.

In order to create an object of NoneType class, we can simply initialize a


variable with None as the value.

Let us consider the following example showing the object of the


'NoneType' class.

Example
1. # simple python program to show the creation of NoneType object
2.
3. # initializing a variable with None
4. var_1 = None
5.
6. # printing results
7. print("Value of var_1:", var_1)
8. print("Data Type of var_1:", type(var_1))
Execute Now

Output:

Value of var_1: None


Data Type of var_1: <class 'NoneType'>
Explanation:

In the above example, we have initialized a variable var_1 with None as its
value. We have then printed it for reference and used the type() function
to return its type. As a result, we can observe that the variable var_1 has
a value of None, and it belongs to the 'NoneType' class.

25
Type Casting in Python
Python is a dynamically typed language, allowing us not to explicitly define the data types
of the variables. However, Python offers us accessibility to convert one data type into
another.

The process of converting one data type into another is known as Type Casting. Python
offers two ways to type cast the variables:

1. Implicit Type Casting (Automatic): Python converts smaller data types to larger
ones automatically.

Example
1. # python program to show implicit type casting

# initializing some variables


p=6 # int
print(p, "=>", type(p))
q = 3.7 # float
print(q, "=>", type(q))

# adding variable p and q and storing their results


10.r = p + q # int + float = float
11.
12.# printing results
[Link](p, '+', q, '=', r)
[Link](r, "=>", type(r))
Execute Now

Output:

6 => <class 'int'>


3.7 => <class 'float'>
6 + 3.7 = 9.7
9.7 => <class 'float'>
Explanation:

In the above example, we have initialized two variables, p and q, of different types (int and
float). We then added them and stored their sum in another variable, r. We then printed
their data types. As a result, we can observe that r is implicitly converted into 'float'.

2. Explicit Type Casting (Manual): Programmers use Python's built-in functions to


convert one data type into another.

Example
1. # python program to show explicit type casting

# converting int to float


p = float(14)
print(p)

# converting float to int


q = int(7.52)
print(q)

26
10.
11.# converting string to int
12.r = int("7295")
[Link](r)
14.
15.# converting list to tuple
16.list_1 = [4, 7, 10]
17.tuple_1 = tuple(list_1)
18.
[Link](type(list_1))
[Link](type(tuple_1))
Execute Now

Output:

14.0
7
7295
<class 'list'>
<class 'tuple'>
Explanation:

In the above example, we have used some built-in functions like float(), int(), tuple() in
order to convert the data type of the passed variable into the required data type.

To learn more about Type Casting, visit: Python - Type Casting.

Conclusion
Understanding Python data types is important for writing efficient code. These built-in data
types allow developers for storing and manipulating various kinds of data effectively and
efficiently. Mastering them will enable better programming practices and problem-solving
skills.

Python Data Types - MCQs


1. What will be the output of the following code?

q=7
print(type(q))

a. <class 'float'>
b. <class 'str'>
c. <class 'int'>
d. <class 'list'>

Show AnswerWorkspace

2. What is the data type of the following variable?

p = 62.5

27
a. int
b. float
c. complex
d. bool

Show AnswerWorkspace

3. Which of the following is a mutable data type in Python?

a. tuple
b. str
c. list
d. frozenset

Show AnswerWorkspace

4. What will be the output of the following code?

x = 3 + 4j
print(type(x))

a. <class 'float'>
b. <class 'int'>
c. <class 'complex'>
d. <class 'tuple'>

Show AnswerWorkspace

5. What is the correct syntax to create a set in Python?

a. {5, 4, 3}
b. [5, 4, 3]
c. (5, 4, 3)
d. set[5, 4, 3]

Show AnswerWorkspace

Next TopicPython Numbers

← prevnext →

28
Related Posts

Type Casting in Python

Imagine you have got a container of toys categorised "wood blocks," however

you need to put them in a container classified "building substances" instead.

That's basically what type casting, or type conversion, does in Python. Think of

Python as an extraordinary bendy assistant. You don't have...

12 min read

Python Numbers

The number data types are used to store the numeric values inside the

variables. Number objects are created when some value is assigned to a

variable. For example, a = 5 will create a number object a with value 5. Python

also allows us to delete...

3 min read

29

Python Boolean

&nbsp; Python includes a built-in data type called Boolean, which can be either

True or False. This type is commonly used to represent the outcome of logical

comparisons or conditions. Examples: Input: 19 == 19 Output: True Input: 24 &lt;

19 Output: False Type A Boolean type...

8 min read

Python Variables

In Python, variables are fundamental building blocks that allow developers to

store, manage, and manipulate data efficiently. A variable in Python is

essentially a symbolic name assigned to a memory location where data is

stored. Unlike statically typed languages such as C or Java, Python...

30

You might also like