Python Unit 1
Python Unit 1
Introduction to python:
Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991.
It is used for:
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets for
this purpose.
Example:
print("Hello, World!")
There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a
popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided
to select naming Python after the "Monty Python's Flying Circus" for their newly created
programming language.
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting Python is also versatile and widely used in every
technical field, such as Machine Learning, Artificial Intelligence, Web Development, Mobile
Application, Desktop Application, Scientific Calculation, etc. A list of Python versions with its
released date is given below
Python develops new versions with changes periodically and releases them according to version
numbers. Python is currently at version 3.11.3.
Python is much simpler to learn and programme in. Any plain text editor, such as notepad or
notepad++, may be used to create Python programs. To make it easier to create these routines,
one may also utilise an online IDE for Python or even install one on their machine. IDEs offer a
variety of tools including a user-friendly code editor, the debugger, compiler, etc.
One has to have Python installed on their system in order to start creating Python code and
carrying out many fascinating and helpful procedures. The first step in learning how to
programming in Python is to install or update Python on your computer. There are several ways
to install Python: you may use a package manager, get official versions from [Link], or
install specialized versions for embedded devices, scientific computing, and the Internet of
Things.t
Installation on Windows
Visit the link [Link] to download the latest release of Python. In this process,
we will install Python 3.11.3 on our Windows operating system. When we click on the above
link, it will bring us the following page.
If in case you want to download the specific version of Python. Then, you can scroll down
further below to see different versions from 2 and 3 respectively. Click on download button right
next to the version number you want to download.
ADVERTISEMENT
The following window will open. Click on the Add Path check box, it will set the Python path
automatically.
Now, Select Customize installation and proceed. We can also click on the customize installation
to choose desired location and features. Other important thing is install launcher for the all user
must be checked.
Here, under the advanced options, click on the checkboxes of " Install Python 3.11 for all users ",
which is previously not checked in. This will checks the other option " Precompile standard
library " automatically. And the location of the installation will also be changed. We can change
it later, so we leave the install location default. Then, click on the install button to finally install.
The set up is in progress. All the python libraries, packages, and other python default files will be
installed in our system. Once the installation is successful, the following page will appear saying
" Setup was successful ".
Python Interpreter:
Let’s now discuss the differences between a Python interpreter and a Python compiler.
Computer programs are generally written in a high-level language also called source code. Since
machines don’t understand this type of language, the language needs to be transformed into
binary or machine code, which machines understand.
Compilers and interpreters make this transformation possible. However, while they both have the
primary function of changing source code into machine code, there are differences between
them.
These two remarkable tools significantly differ in how they translate the source code.
Interpreters translate source code one statement at a time. On the other hand, the compiler first
scans the entire program and then translates the whole program into machine code.
These two methods of translating code present unique opportunities and challenges. Let’s
consider these.
Interpreters translate programs one statement at a time, unlike compilers that do “batch
translation.” Therefore, interpreters usually take less time to analyze the source code. However,
while they analyze code faster, compilers execute the code faster than interpreters.
Secondly, because interpreters don’t generate any Object code, they are more memory efficient
than compilers.
It depends on what you want. Programs with interpreters can run right away and be started faster.
Furthermore, interpreters make debugging your code easier since they identify line-by-line
errors.
Any changes made to the code written via a compiler will require it to be converted. Compilers
no longer use computing power, making them more efficient.
The Python interpreter is CPython and is written in the C programming language. So how does
CPython work? Let’s see.
First, the interpreter checks or analyzes the source code. By now, we assume you know what the
source code means. It’s the high-level language you write programs in.
So, CPython receives the source code and initializes several commands to do some vital things.
First, the interpreter ensures you follow Python’s syntax for writing code.
It also checks for incorrect lines of code. If it encounters any error in a line, it stops the program
from running and produces an error message.
This analysis divides the source code files into a list of tokens.
After lexical analysis, which is the process described in the section above, the interpreter moves
to the second stage, byte code generation.
After receiving the tokens, the interpreter generates the Abstract Syntax Tree or AST. This tree is
converted to machine language (i.e., 1s and 0s). Because this is a Python interpreter, the code can
be saved in a file with the .pyc extension.
Next, the interpreter initializes a PVM.
The interpreter initializes the Python Virtual Machine (PVM) in the next step. PVM is crucial
because it’s what converts the byte code into binary code.
After conversion, the results are then printed. Python prints out the correct result if there are no
high-level language errors. Otherwise, it prints out an error message.
Now that we have a high-level view of how the compiler works, let’s now show you how to set
up and use a Python interpreter.
requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyter Notebook
itself.
Installation
Install Python and Jupyter using the Anaconda Distribution, which includes Python, the
Jupyter Notebook, and other commonly used packages for scientific computing and data
science. You can download Anaconda’s latest Python3 version. Now, install the downloaded
version of Anaconda. Installing Jupyter Notebook using pip:
python3 -m pip install --upgrade pip
python3 -m pip install jupyter
Starting Jupyter Notebook
To start the jupyter notebook, type the below command in the terminal.
jupyter notebook
This will print some information about the notebook server in your terminal, including the
URL of the web application (by default, [Link] and then open your default web
browser to this URL.
After the notebook is opened, you’ll see the Notebook Dashboard, which will show a list of the
notebooks, files, and subdirectories in the directory where the notebook server was started.
Most of the time, you will wish to start a notebook server in the highest level directory
containing notebooks. Often this will be your home directory.
Creating a Notebook
To create a new notebook, click on the new button at the top right corner. Click it to open a
drop-down list and then if you’ll click on Python3, it will open a new notebook.
print("Hello World")
To run a cell either click the run button or press shift ⇧ + enter ⏎ after selecting the cell you
want to execute. After writing the above code in the jupyter notebook, the output was:
Note: When a cell has executed the label on the left i.e. ln[] changes to ln[1]. If the cell is still
under execution the label remains ln[*].
This is where the code is typed and when executed the code will display the output below the
cell. The type of code depends on the type of the notebook you have created. For example, if
the notebook of Python3 is created then the code of Python3 can be added. Consider the below
example, where a simple code of the Fibonacci series is created and this code also takes input
The tex bar in the above code is prompted for taking input from the user. The output of the
above code is as follows: Output:
Markdown
Markdown is a popular markup language that is the superset of the HTML. Jupyter Notebook
also supports markdown. The cell type can be changed to markdown using the cell menu.
Adding Headers: Heading can be added by prefixing any line by single or multiple ‘#’
followed by space. Example:
Output:
Adding List: Adding List is really simple in Jupyter Notebook. The list can be added by using
‘*’ sign. And the Nested list can be created by using indentation. Example:
Output:
Adding Latex Equations: Latex expressions can be added by surrounding the latex code by
‘$’ and for writing the expressions in the middle, surrounds the latex code by ‘$$’. Example:
Output:
Adding Table: A table can be added by writing the content in the following format.
Output:
Note: The text can be made bold or italic by enclosing the text in ‘**’ and ‘*’ respectively.
Raw NBConverter
Raw cells are provided to write the output directly. This cell is not evaluated by Jupyter
notebook. After passing through nbconvert the raw cells arrives in the destination folder
without any modification. For example, one can write full Python into a raw cell that can only
be rendered by Python only after conversion by nb convert.
Kernel
A kernel runs behind every notebook. Whenever a cell is executed, the code inside the cell is
executed within the kernel and the output is returned back to the cell to be displayed. The
kernel continues to exist to the document as a whole and not for individual cells. For example,
if a module is imported in one cell then, that module will be available for the whole document.
Note: The order of execution of each cell is stated to the left of the cell. In the above example,
the cell with In[1] is executed first then the cell with In[2] is executed. Options for
kernels: Jupyter Notebook provides various options for kernels. This can be useful if you want
to reset things. The options are:
Restart: This will restart the kernels i.e. clearing all the variables that were defined,
clearing the modules that were imported, etc.
Restart and Clear Output: This will do the same as above but will also clear all the
output that was displayed below the cell.
Restart and Run All: This is also the same as above but will also run all the cells in the
top-down order.
Interrupt: This option will interrupt the kernel execution. It can be useful in the case
where the programs continue for execution or the kernel is stuck over some computation.
Notebook Extensions
New functionality can be added to Jupyter through extensions. Extensions are javascript
module. You can even write your own extension that can access the page’s DOM and the
Jupyter Javascript API. Jupyter supports four types of extensions.
Kernel
IPyhton Kernel
Notebook
Notebook server
Installing Extensions
Most of the extensions can be installed using Python’s pip tool. If an extension can not be
installed using pip, then install the extension using the below command.
jupyter nbextension install extension_name
The above only installs the extension but does not enables it. To enable it type the below
command in the terminal.
jupyter nbextension enable extension_name
Python has been at the forefront of Machine learning, Data Science, and Artificial Intelligence
innovation. Further, Python applications offers provide ease in building a plethora of apps, web
development processes, and a lot more. In this blog, we will discuss the top 10 Python
applications in the real world in a detailed manner. So let’s get started:
1. Web Development
It is one of the most astonishing applications of Python. This is because Python comes up with
a wide range of frameworks like Django, Flask, Bottle, and a lot more that provide ease to
developers. Furthermore, Python has inbuilt libraries and tools which make the web
development process completely effortless. The use of Python for web development also
offers:
Amazing visualization
Convenience in development
Enhanced security
Fast development process
2. Machine Learning and Artificial Intelligence
Machine Learning and Artificial Intelligence are the hottest subjects right now. Python along
with its inbuilt libraries and tools facilitate the development of AI and ML algorithms. Further,
it offers simple, concise, and readable code which makes it easier for developers to write
complex algorithms and provide a versatile flow. Some of the inbuilt libraries and tools that
enhance AI and ML processes are:
Numpy for complex data analysis
Keras for Machine learning
SciPy for technical computing
Seaborn for data visualization
3. Data Science
Data science involves data collection, data sorting, data analysis, and data visualization.
Python provides amazing functionality to tackle statistics and complex mathematical
calculations. The presence of in-built libraries provides convenience to data science
professionals. Some of the popular libraries that provide ease in the data science process are
TensorFlow, Pandas, and Socket Learning. These libraries provide an ecosystem for fine-
tuning data models, data preprocessing, and performing complex data analysis.
4. Game Development
With the rapidly growing gaming industry, Python has proved to be an exceptional option for
game development. Popular games like Pirates of the Caribbean, Bridge Commander, and
Battlefield 2 use Python programming for a wide range of functionalities and add-ons. The
presence of popular 2D and 3D gaming libraries like pygame, panda3D, and Cocos2D makes
the game development process completely effortless.
5. Audio and Visual Applications:
Audio and video applications are undoubtedly the most amazing feature of Python. Python is
equipped with a lot of tools and libraries to accomplish your task flawlessly. Applications that
are coded in Python include popular ones like Netflix, Spotify, and YouTube. This can be
handled by libraries like
Dejavu
Pyo
Mingus
SciPy
OpenCV
6. Software Development
Python is just the perfect option for software development. Popular applications like Google,
Netflix, and Reddit all use Python. This language offers amazing features like:
Professor Mudita Dave Nagar Page 21
Python Programming [CA3EL06] Unit#1
Platform independence
Inbuilt libraries and frameworks to provide ease of development.
Enhanced code reusability and readability
High compatibility
Apart from these Python offers enhanced features to work with rapidly growing technologies
like Machine learning and Artificial intelligence. All these embedded features make it a
popular choice for software development.
7. CAD Applications
CAD refers to computer-aided design; it is the process of creating 3D and 2D models digitally.
This application has replaced manual drift and is used by architects, product designers, and
construction managers to design products with extremely high consistency. Python is
embedded with amazing applications like Blender, Free CAD, open cascade, and a lot more to
efficiently design products. These provide enhanced features like technical drawing, dynamic
system development, recordings, file export, and import.
8. Business Applications
Python offers excellent security and scalability features that make it perfect for delivering
high-performance business applications. It has inbuilt libraries and tools like:
Odoo is business management software that provides you with an automated solution for
your business process.
Tryton is easy-to-use open-source business software. It has fully integrated features like
financial accounting, sales, CRM, purchasing, shipping, and the list goes on.
All these distinguishing features make it fit for creating business applications.
9. Desktop GUI
Python is an interactive programming language that helps developers to create GUIs easily and
efficiently. It has a huge list of inbuilt tools for Python usage are PyQT, kivy, wxWidgets, and
many other libraries like them to build a fully functional GUI in an extremely secure and
efficient manner.
10. Web Scraping Application
Web scraping is an automated process used to extract information from websites in an easier
and faster way. The information is used by researchers, organizations, and analysts for a wide
variety of tasks. Python has a wide range of features that make it suitable for web scraping
some of them are:
A concise syntax enhances readability and saves you time.
A wide range of libraries and tools like pandas, matplotlib, and Selenium makes the web
scraping process easy and efficient.
Easy to use and understand
Some other real-world applications of Python are:
Robotics and automation by the use of inbuilt libraries and tools like PyDy, Dart, PyRobot,
and Pyro.
Image processing: some of the amazing libraries and tools for image processing are
Blender, OpenCV, Houdini, and PIL.
Scientific applications are facilitated by popular libraries like Pandas, Matplotlib, SciPy,
and many more
Now that we know the differences between Python 2 and Python 3, let’s see examples of
code in both versions
Python 2:
# Python 2
Python 3:
# Python 3
Example 2: Division
Python 2:
# Python 2
result = 5 / 2
print(result) # Outputs 2
Python 3:
# Python 3
result = 5 / 2
Python 3:
# Python 3
user_input = input("Enter something: ")
print("You entered: " + user_input)
In Python 3, raw_input() is merged into the input() function.
These examples showcase some fundamental differences, and adapting code accordingly is
crucial when transitioning from Python 2 to Python 3.
Example 4: Unicode Handling
Python 2:
# Python 2
unicode_string = u"Hello, Unicode!"
print(unicode_string)
Python 3:
Professor Mudita Dave Nagar Page 24
Python Programming [CA3EL06] Unit#1
# Python 3
unicode_string = "Hello, Unicode!"
print(unicode_string)
In Python 2, Unicode strings require the u prefix, while in Python 3, strings are Unicode by
default.
Example 5: Range Function
Python 2:
# Python 2
for i in range(5):
print(i)
Python 3:
# Python 3
for i in range(5):
print(i)
In Python 3, range() behaves like xrange() in Python 2, providing an iterator instead of a
list.
[Link] 6: Error Handling Syntax
Python 2:
# Python 2
try:
# Some code that might raise an exception
result = 10 / 0
except Exception, e:
print("Error: " + str(e))
Python 3:
# Python 3
try:
# Some code that might raise an exception
result = 10 / 0
except Exception as e:
print("Error: " + str(e))
In Python 3, the syntax for handling exceptions has changed from except Exception, e: to
except Exception as e:.
Code Blocks Representation: Python takes a detour from the typical practice seen in languages
like C or Java that use curly braces { } to define code blocks. Instead, Python opts for
indentation, rendering a unique clarity to its code structure. This distinction makes it imperative
to manage indentation errors in Python, as they directly affect the code's logic and flow.
Code Readability Enforcer: One of Python's standout traits is its emphasis on code readability.
Indentation plays a crucial role here. By ensuring consistent indentation, Python mandates that
code remains clean, organized, and easily understandable. This readability not only aids in better
programming practices but also facilitates smoother collaboration among teams.
Types of Indentation
Space: In Python, spaces are the preferred indentation method. A standard convention and also
recommended by the official Python style guide (PEP 8) is the use of 4 spaces for each
indentation level.
Tab: While tabs can technically be used for indentation, they aren't as universally accepted. The
main issue arises when code is shared or viewed in different editors, leading to inconsistent code
appearance. Thus, using tabs can inadvertently cause an indentation error in Python, especially in
collaborative environments.
ESSENTIAL INDENTATION RULES FOR PYTHON
Here are some basic indentation rules for Python:
Use Spaces for Indentation: Python conventionally uses four spaces for each level of
indentation. While you can technically use tabs, it's recommended to use spaces for consistency
and to avoid issues with different editors and environments.
Consistent Indentation: Maintain consistent indentation throughout your code. Mixing spaces
and tabs or using different numbers of spaces for indentation can lead to indentation errors.
Indentation for Blocks: Indentation is used to define blocks of code, such as loops,
conditionals, and function bodies. All lines within the same block should have the same level of
indentation.
Colon After Statements: In Python, a colon (:) is used to indicate the start of an indented block,
such as in if, for, while, and function definitions.
Here's an example of correctly indented Python code:
def print_numbers():
for i in range(5):
if i % 2 == 0:
print("Even:", i)
else:
print("Odd:", i)
print("Done")
print_numbers()
Mismatched Indentation Mixing spaces and tabs A code block that begins with
inconsistently causes issues. spaces but has lines indented
with tabs.
Incorrect Indent Levels Using the wrong number of Following if True: with a line
spaces/tabs results in errors. indented with 6 spaces instead
of the recommended 4.
Inconsistent Indentation: Ensure that all lines within the same block have the same level of
indentation. If you mix spaces and tabs, convert them to spaces.
Mismatched Indentation: If you encounter an error that mentions "indentation error" but you
can't see any obvious issues, check for invisible characters like trailing spaces or tabs at the
beginning of lines.
Missing Colon: If you forget to include a colon after a statement that should introduce an
indented block (e.g., after if, for, while, or a function definition), Python will raise an indentation
error.
Here's an example of an indentation error and how to fix it:
print_numbers()
To fix this error, we need to simply add the required indentation before the for statement:
Code:
def print_numbers():
for i in range(5): # Correct indentation
print(i)
print_numbers()
1. Enhanced Readability: Python’s indentation style makes the structure of the code immediately
visible. By using indentation to demarcate code blocks, the language ensures that the hierarchy
and logic of the code stand out clearly. This inherent readability is vital, especially in
collaborative settings where multiple developers may interact with the same codebase.
2. Reduction in Errors: The absence of curly braces, commonly used in many programming
languages, means fewer chances of misplacing or mismatching them. This trait significantly
reduces certain syntax errors, ensuring smoother code execution.
3. Promotion of Best Practices: Indentation, by design, pushes developers towards writing well-
structured code. It's a silent enforcer, subtly ensuring that programmers think about code
hierarchy and organization as they write, leading to an intuitive flow in the code.
4. Code Length: By eschewing the need for additional characters like braces or end statements (as
seen in languages like Ruby), Python code tends to be concise. This brevity not only makes the
code look clean but also minimizes the time taken for code reviews and debugging.
2. Misreading Risks: Even a minor inconsistency, such as unintentionally mixing spaces with tabs,
can throw off the entire code logic. This sensitivity often leads to indentation error in Python
messages, which can be perplexing, especially for novices.
3. Portability Issues: Moving a Python script from one environment or editor to another can
sometimes introduce indentation issues. Different editors might interpret tabs differently or
might have varied default tab settings, leading to potential execution errors.
4. Perceived Rigidity: Some developers feel that the enforced indentation limits their coding style
freedom. They might prefer a more flexible approach where the code's structure isn't strictly tied
to whitespace.
5. Troubleshooting Challenges: In cases where indentation errors do creep in, they can be
notoriously tricky to debug. Since the errors might not always be evident at a cursory glance, it
demands a meticulous review to identify and rectify them.
CONCLUSION:
Indentation, while being a distinctive feature of Python, plays a pivotal role in reinforcing code
clarity and structure. While it does bring its set of challenges, especially for newcomers, the
advantages it offers are undeniable. As you continue your journey in Python, consider leveraging
platforms like upGrad to further sharpen your skills and embrace Python’s elegant philosophy.
FAQS
1. What is the role of indentation in Python class 11?
Indentation plays a foundational role in teaching Python to class 11 students. It introduces them to
the importance of structured coding in Python.
2. Is Python interpreted or compiled?
Python is an interpreted language. It means the Python interpreter reads and executes the code line-
by-line, instead of compiling it first.
3. What is the importance of being consistent with the indentation level in Python?
Maintaining a consistent indentation level ensures the logical structure of the code remains intact,
and it minimizes the risk of unexpected errors.
4. What is an indentation error in Python example?
Consider an if statement followed by a line with 3 spaces instead of 4. This would throw an
indentation error.
5. Indentation is not mandatory in Python true or false?
False. Indentation is a cornerstone of Python's syntax and is used to define code blocks.
continue the comment. Python’s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions. See the following code
snippet demonstrating single line comment:
Example 1:
Python allows comments at the start of lines, and Python will ignore the whole line.
Python3
# This is a comment
print("WelcometoMedicaps")
Output
WelcometoMedicaps
Example 2:
Python also allows comments at the end of lines, ignoring the previous text.
Python3
Output
4
Multiline comment in Python
Use a hash (#) for each extra line to create a multiline comment. In fact, Python multiline
comments are not supported by Python’s syntax. Additionally, we can use Python multi-line
comments by using multiline strings. It is a piece of text enclosed in a delimiter (“””) on each
end of the comment. Again there should be no white space between delimiter (“””). They are
useful when the comment text does not fit into one line; therefore need to span across lines.
Python Multi-line comments or paragraphs serve as documentation for others reading your
code. See the following code snippet demonstrating a multi-line comment:
Example 1:
In this example, we are using an extra # for each extra line to create a Python multiline
comment.
Python3
# This is a comment
print("WelcometoMedicaps ")
Output
WelcometoMedicaps
Example 2:
In this example, we are using three double quotes (“) at the start and end of the string without
any space to create a Python multiline comment.
Python3
"""
"""
print("Medicaps")
Output
Medicaps
Example 3:
In this example, we are using three single quotes (‘) at the start and end of the string without
any space to create a Python multiline comment.
Python3
perfect example of
multi-line comments'''
print("Medicaps ")
Output
Medicaps
Docstring in Python
Python Docstrings are a type of comment that is used to show how the program works.
Docstrings in Python are surrounded by Triple Quotes in Python (“”” “””). Docstrings are also
neglected by the interpreter.
Python3
def helloWorld():
print("Hello World")
helloWorld()
Output
Hello World
Docstrings and Multi-line comments may look the same but they aren’t.
Docstrings are written in the functions and classes to show how to use the program.
Multi-line comments are used to show how a block of code works.
Python Variables
Python Variable is containers that store values. Python is not “statically typed”. We do not
need to declare variables before using them or declare their type. A variable is created the
moment we first assign a value to it. A Python variable is a name given to a memory location.
It is the basic unit of storage in a program. In this article, we will see how to define a variable
in Python.
Example of Variable in Python
An Example of a Variable in Python is a representational name that serves as a pointer to an
object. Once an object is assigned to a variable, it can be referred to by that name. In layman’s
terms, we can say that Variable in Python is containers that store values.
Here we have stored “Medicaps” in a variable var, and when we call its name the stored
information will get printed.
Var = "Medicaps"
print(Var)
Output:
Medicaps
Example:
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Python Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data. Since everything is an
object in Python programming, Python data types are classes and variables are instances
(objects) of these classes. The following are the standard or built-in data types in Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Binary Types( memoryview , bytearray , bytes )
x = "Hello World"
x = 50
x = 60.5
x = 3j
x = ["geeks", "for", "geeks"]
x = ("geeks", "for", "geeks")
x = range(10)
x = {"name": "Suraj", "age": 24}
x = {"geeks", "for", "geeks"}
x = frozenset({"geeks", "for", "geeks"})
x = True
x = b"Geeks"
x = bytearray(4)
x = memoryview(bytes(6))
x = None
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
2. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or different Python data
types. Sequences allow storing of multiple values in an organized and efficient fashion. There are
several sequence data types of Python:
Python String
Python List
Python Tuple
String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of
one or more characters put in a single quote, double-quote, or triple-quote. In Python, there is no
character data type Python, a character is a string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes, double quotes, or even triple quotes.
Example: This Python code showcases various string creation methods. It uses single quotes,
double quotes, and triple quotes to create strings with different content and includes a multiline
string. The code also demonstrates printing the strings and checking their data types.
Python
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
<class 'str'>
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
<class 'str'>
Creating a multiline String:
Geeks
For
Life
Accessing elements of String
In Python programming, individual characters of a String can be accessed by using the method of
Indexing. Negative Indexing allows negative address references to access characters from the
back of the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so
on.
Example: This Python code demonstrates how to work with a string named ‘ String1′ . It
initializes the string with “GeeksForGeeks” and prints it. It then showcases how to access the
first character ( “G” ) using an index of 0 and the last character ( “s” ) using a negative index of
-1.
Python
String1 = "GeeksForGeeks"
Professor Mudita Dave Nagar Page 37
Python Programming [CA3EL06] Unit#1
List = []
print("Initial blank List: ")
print(List)
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)
Output:
Initial blank List:
[]
List with the use of String:
['GeeksForGeeks']
List containing multiple values:
Geeks
Geeks
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
5
Third last element of tuple
3
Note – To know more about tuples, refer to Python Tuples .
3. Boolean Data Type in Python
Python Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false). However non-Boolean
objects can be evaluated in a Boolean context as well and determined to be true or false. It is
denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an
error.
Example: The first two lines will print the type of the boolean values True and False, which
is <class ‘bool’>. The third line will cause an error, because true is not a valid keyword in
Python. Python is case-sensitive, which means it distinguishes between uppercase and lowercase
letters. You need to capitalize the first letter of true to make it a boolean value.
Python
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/[Link]", line 8, in
print(type(true))
NameError: name 'true' is not defined
4. Set Data Type in Python
In Python Data Types, a Set is an unordered collection of data types that is iterable, mutable, and
has no duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a set
need not be the same, various mixed-up data type values can also be passed to the set.
Example: The code is an example of how to create sets using different types of values, such
as strings , lists , and mixed values
Python
set1 = set()
print("Initial blank Set: ")
print(set1)
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)
set1 = set(["Geeks", "For", "Geeks"])
Output:
Initial blank Set:
set()
Set with the use of String:
{'F', 'o', 'G', 's', 'r', 'k', 'e'}
Set with the use of List:
{'Geeks', 'For'}
Set with the use of Mixed Values
{1, 2, 4, 6, 'Geeks', 'For'}
Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For
True
Note – To know more about sets, refer to Python Sets.
5. Dictionary Data Type in Python
A dictionary in Python is an unordered collection of data values, used to store data values like a
map, unlike other Python Data Types that hold only a single value as an element, a Dictionary
holds a key: value pair. Key-value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon : , whereas each key is separated by a
‘comma’.
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
Accessing Key-value in Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets. There is also a method called get() that will also help in accessing the element from a
dictionary.
Example: The code in Python is used to access elements in a dictionary. Here’s what it does, It
creates a dictionary Dict with keys and values as { 1: ‘Geeks’, ‘name’: ‘For’, 3: ‘Geeks’} . It
prints the value of the element with the key ‘name’ , which is ‘For’ . It prints the value of the
element with the key 3, which is ‘Geeks’ .
Python
coordinates = (3, 5)
print(coordinates)
print("X-coordinate:", coordinates[0])
print("Y-coordinate:", coordinates[1])
Output
(3, 5)
X-coordinate: 3
Y-coordinate: 5
Logical operators
Professor Mudita Dave Nagar Page 44
Python Programming [CA3EL06] Unit#1
In Python, Logical operators are used on conditional statements (either True or False). They
perform Logical AND, Logical OR and Logical NOT operations.
and Logical AND: True if both the operands are true x and y
Example #1:
a = 10
b = 10
c = -10
else:
Output
The numbers are greater than 0
Atleast one number is not greater than 0
Example #2:
a = 10
b = 12
c=0
if a and b and c:
else:
output:
Logical OR operator
Logical or operator returns True if either of the operands is True.
a = 10
b = -10
c=0
if a > 0 or b > 0:
print("Either of the number is greater than 0")
else:
print("No number is greater than 0")
if b > 0 or c > 0:
print("Either of the number is greater than 0")
else:
print("No number is greater than 0")
Output
Either of the number is greater than 0
No number is greater than 0
Example #2:
# Python program to demonstrate logical or operator
a = 10
b = 12
c=0
if a or b or c:
print("Atleast one number has boolean value as True")
else:
print("All the numbers have boolean value as False")
Output
Atleast one number has boolean value as True
a = 10
if not a:
else:
Output
10 is divisible by either 3 or 5
def order(x):
a = order
b = order
c = order
Output
Method called for value: -1
Method called for value: 5
Atleast one of the number is positive
a | b = 1010
|
0100
= 1110
= 14 (Decimal)
thus ~a = -11
Bitwise xor operator: Returns 1 if one of the bits is 1 and the other is 0 else returns false.
Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a ^ b = 1010
^
0100
= 1110
= 14 (Decimal)
The following table lists all operators from highest precedence to lowest.
Operator Description
~+- Complement, unary plus and minus (method names for the
last two are +@ and -@)
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
When you execute the above program, it produces the following result −
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
print(student)
OUTPUT
Geeks
2. Tuple assignment:
x, y = 50, 100
print('x = ', x)
print('y = ', y)
OUTPUT
x = 50
y = 100
When we code a tuple on the left side of the =, Python pairs objects on the right side with
targets on the left by position and assigns them from left to right. Therefore, the values of x
and y are 50 and 100 respectively.
3. List assignment:
This works in the same way as the tuple assignment.
[x, y] = [2, 4]
print('x = ', x)
print('y = ', y)
OUTPUT
x=2
y=4
4. Sequence assignment:
In recent version of Python, tuple and list assignment have been generalized into instances of
what we now call sequence assignment – any sequence of names can be assigned to any
sequence of values, and Python assigns the items one at a time by position.
a, b, c = 'HEY'
print('a = ', a)
print('b = ', b)
print('c = ', c)
OUTPUT
a=H
b=E
c=Y
print('p = ', p)
print('q = ', q)
Here, p is matched with the first character in the string on the right and q with the rest. The
starred name (*q) is assigned a list, which collects all items in the sequence not assigned to
other names.
OUTPUT
p=H
q = ['e', 'l', 'l', 'o']
This is especially handy for a common coding pattern such as splitting a sequence and
accessing its front and rest part.
OUTPUT
Winner: A
Runner ups: B, C, D
x = y = 75
print(x, y)
In this form, Python assigns a reference to the same object (the object which is rightmost) to
the entire target on the left.
OUTPUT
75 75
7. Augmented assignment:
The augmented assignment is a shorthand assignment that combines an expression and an
assignment.
x=2
# equivalent to: x = x + 1
x += 1
print(x)
OUTPUT
3
1. One-Liner If-Else
Sometimes when an if-else expression is simple enough, it might actually be cleaner to write it as
a one-liner:
2. One-Liner Functions
As with the previous example, sometimes you also might want to give the function definition in
one line:
This is a classic interview question: How can you swap two variables without using a third helper
4. Chain Comparisons
You can write it down just like you would do in a math’s class:
0 < x < 200
5. One-Liner For-Loops
You can use what is called a list comprehension to loop through a list neatly with one line of
Using comprehensions is not restricted to lists only. You can use a similar syntax
with dictionaries, sets, and generators too. For instance, let’s use dictionary comprehension to
6. Lambda Expressions
In Python, a lambda function is just a nameless function. It can take any number of arguments but
can only have a single expression. For instance, here is a lambda that multiplies a number by
three:
>>> lambda x : x * 3
Lambdas are useful when you need the functionality for a short period of time. A practical
example is filtering a list. Python’s built-in filter method takes two parameters:
A list to be filtered
As an example, let’s filter even numbers from a list by passing a lambda function into
You can simply multiply a string by an integer to repeat it as many times as you prefer:
>>> "word" * 4
wordwordwordword
8. Reverse a String
Would you agree that this looks pretty bad, even though there’s nothing wrong with it?
>>> if n == 0 or n == 1 or n == 2 or n == 3 or n == 4 or n == 5:
Instead of this mess, you can make it look better by doing this:
>>> if n in [0, 1, 2, 3, 4, 5]
You can easily destructure list elements into separate variables. For example:
>>> arr = [1, 2, 3]
>>> a, b, c = arr
>>> print(a, b, c)
123
12. F-Strings
With Python 3.6 and later, you can use F-Strings to embed expressions inside strings. As an
example:
You can use the choice() method of the random module to pick random elements from a list.
>>> import random
>>> [Link](['Head',"Tail"])
Head
You can neatly join a list of strings together using the join() method of a string.
>>> words = ["This", "is", "a", "Test"]
>>> " ".join(words)
This is a Test
Often times it is bad practice to write hard-coded strings. For instance, here the direction is
Example:
Output:
2.718281828459045
Pi
You all must be familiar with pi. The pi is depicted as either 22/7 or 3.14. [Link] provides a
more precise value for the pi.
Syntax:
[Link]
Example:
Output:
3.141592653589793
Example 2:
import math
r=4
# value of pie
pie = [Link]
print(pie * r * r)
Output:
50.26548245743669
Tau
Syntax:
[Link]
import math
print ([Link])
Output:
6.283185307179586
Infinity
Infinity basically means something which is never-ending or boundless from both directions
i.e. negative and positive. It cannot be depicted by a number. The [Link] constant returns of
positive infinity. For negative infinity, use -[Link].
Syntax:
[Link]
import math
print ([Link])
Professor Mudita Dave Nagar Page 63
Python Programming [CA3EL06] Unit#1
print (-[Link])
Output:
inf
-inf
Example 2: Comparing the values of infinity with the maximum floating point value
import math
Output:
True
True
NaN
The [Link] constant returns a floating-point nan (Not a Number) value. This value is not a
legal number. The nan constant is equivalent to float(“nan”).
Example:
import math
print ([Link])
Output:
nan
Import Random:
Python Random module is an in-built module of Python which is used to generate random
numbers. These are pseudo-random numbers means these are not truly random. This module
can be used to perform random actions such as generating random numbers, print random a
value for a list or string, etc.
Example 1:
import random
print([Link]())
Example 2:
# import random
import random
list1 = [1, 2, 3, 4, 5, 6]
print([Link](list1))
As stated above random module creates pseudo-random numbers. Random numbers depend on
the seeding value. For example, if the seeding value is 5 then the output of the below program
will always be the same.
import random
[Link](5)
print([Link]())
print([Link]())
Output:
0.6229016948897019
0.7417869892607294
The output of the above code will always be the same. Therefore, it must not be used for
encryption.
In Python, the assert statement is used to continue the execute if the given condition evaluates
to True. If the assert condition evaluates to False, then it raises the AssertionError exception
with the specified error message.
Syntax
assert condition [, Error Message]
Example: assert
x = 10
assert x > 0
print('x is a positive number.')
Output
x is a positive number.
In the above example, the assert condition, x > 0 evalutes to be True, so it will continue to
execute the next statement without any error.
The assert statement can optionally include an error message string, which gets displayed
along with the AssertionError. Consider the following assert statement with the error message.
x=0
assert x > 0, 'Only positive numbers are allowed'
print('x is a positive number.')
Output
Traceback (most recent call last):
assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed
Above, x=0, so the assert condition x > 0 becomes False, and so it will raise
the AssertionError with the specified message 'Only positive numbers are allowed'. It does not
execute print('x is a positive number.') statement.
Example: assert
def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x
n = square(2) # returns 4
n = square(-2) # raise an AssertionError
Output
Above, square(2) will return 4, whereas square(-2) will raise an AssertionError because we
passed -2.
The AssertionError is also a built-in exception that can be handled using try-except construct
as shown below:
Example: AssertionError
Copy
def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x
try:
square(-2)
except AssertionError as msg:
print(msg)
Output
Above, calling square(-2) will raise an AssertionError, which will be handled by the except
block. The error message in the assert statement will be passed as an argument to the
exception argument msg, using as keyword.
Print() Function:
Example 1: Print a string onto the screen:
print("ITM is the Largest Data Science Community over whole world")
Output:
type( ) function:
Output:
<class 'tuple'>
input( ) function
The input() function allows taking the input from the user.
Example: Use the prompt parameter to write the complete message after giving the input:
a = input('Enter your name:')
print('Hello, ' + a + ' to ITM University')
Output:
abs( ) function
The abs() function returns the absolute value of the specified number.
Output:
676
pow( ) function
The pow() function returns the calculated value of x to the power of y i.e, xy.
If a third parameter is present in this function, then it returns x to the power of y, modulus z.
Output:
81
---------------------------End Unit#1---------------------------