Python Unit 1 Notes
Python Unit 1 Notes
UNIT - I
Today, Python is one of the most popular programming languages. Although it is a general-
purpose language, it is used in various areas of applications such as Machine Learning, Artificial
Intelligence, web development, IoT, and more.
What is Python?
Characteristics of Python
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 which 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.
Python leaves you free to choose to program in an object-oriented, procedural, functional, aspect-
oriented, or even logic-oriented way. These freedoms make Python a great language to write clean
and beautiful code.
Pythonic Code Style is actually more of a design philosophy and suggests to write a code which is
:
• Clean
• Simple
• Beautiful
• Explicit
• Readable
The Zen of Python
The Zen of Python is about code that not only works, but is Pythonic. Pythonic code is readable,
concise, and maintainable.
Python - History
Guido Van Rossum, a Dutch programmer, created Python programming language. In the late
80's, he had been working on the development of ABC language in a computer science research
institute named Centrum Wiskunde & Informatica (CWI) in the Netherlands. In 1991, Van
Rossum conceived and published Python as a successor of ABC language.
For many uninitiated people, the word Python is related to a species of snake. Rossum though
attributes the choice of the name Python to a popular comedy series Monty Python's Flying
Circus on BBC.
Being the principal architect of Python, the developer community conferred upon him the title
of Benevolent Dictator for Life (BDFL). However, in 2018, Rossum relinquished the title.
Thereafter, the development and distribution of the reference implementation of Python is handled
by a nonprofit organization Python Software Foundation.
This tutorial will teach you how to write a simple Hello World program using Python
Programming language. This program will make use of Python built-in print() function to print
the string Hello, world! on our screen.
The Hello World program is a basic computer code written in a general purpose programming
language, used as a test program. It doesn't ask for any input and displays a Hello World message
on the output console. It is used to test if the software needed to compile and run the program has
been installed correctly.
It is very easy to display the Hello World message using the Python interpreter. Launch the Python
interpreter from a command terminal of your Windows Operating System and issue the print
statement from the Python prompt as follows −
PS C:\> python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
o Data Science: Data Science is a vast field, and Python is an important language for this
field because of its simplicity, ease of use, and availability of powerful data analysis and
visualization libraries like NumPy, Pandas, and Matplotlib.
o Desktop Applications: PyQt and Tkinter are useful libraries that can be used in GUI -
Graphical User Interface-based Desktop Applications. There are better languages for this
field, but it can be used with other languages for making Applications.
o Console-based Applications: Python is also commonly used to create command-line or
console-based applications because of its ease of use and support for advanced features
such as input/output redirection and piping.
o Mobile Applications: While Python is not commonly used for creating mobile
applications, it can still be combined with frameworks like Kivy or BeeWare to create
cross-platform mobile applications.
o Software Development: Python is considered one of the best software-making languages.
Python is easily compatible with both from Small Scale to Large Scale software.
o Artificial Intelligence: AI is an emerging Technology, and Python is a perfect language
for artificial intelligence and machine learning because of the availability of powerful
libraries such as TensorFlow, Keras, and PyTorch.
o Web Applications: Python is commonly used in web development on the backend with
frameworks like Django and Flask and on the front end with tools like JavaScript and
HTML.
o Enterprise Applications: Python can be used to develop large-scale enterprise
applications with features such as distributed computing, networking, and parallel
processing.
o 3D CAD Applications: Python can be used for 3D computer-aided design (CAD)
applications through libraries such as Blender.
o Machine Learning: Python is widely used for machine learning due to its simplicity, ease
of use, and availability of powerful machine learning libraries.
o Computer Vision or Image Processing Applications: Python can be used for computer
vision and image processing applications through powerful libraries such as OpenCV and
Scikit-image.
o Speech Recognition: Python can be used for speech recognition applications through
libraries such as SpeechRecognition and PyAudio.
o Scientific computing: Libraries like NumPy, SciPy, and Pandas provide advanced
numerical computing capabilities for tasks like data analysis, machine learning, and more.
o Education: Python's easy-to-learn syntax and availability of many resources make it an
ideal language for teaching programming to beginners.
o Testing: Python is used for writing automated tests, providing frameworks like unit tests
and pytest that help write test cases and generate reports.
o Gaming: Python has libraries like Pygame, which provide a platform for developing
games using Python.
o IoT: Python is used in IoT for developing scripts and applications for devices like
Raspberry Pi, Arduino, and others.
o Networking: Python is used in networking for developing scripts and applications for
network automation, monitoring, and management.
o DevOps: Python is widely used in DevOps for automation and scripting of infrastructure
management, configuration management, and deployment processes.
o Finance: Python has libraries like Pandas, Scikit-learn, and Statsmodels for financial
modeling and analysis.
o Audio and Music: Python has libraries like Pyaudio, which is used for audio processing,
synthesis, and analysis, and Music21, which is used for music analysis and generation.
o Writing scripts: Python is used for writing utility scripts to automate tasks like file
operations, web scraping, and data processing.
Numeric
Sequence Type
Boolean
Set
Dictionary
Binary Types
This code assigns variable ‘x’ different values of various data types in Python. It covers string,
integer, float, complex, list, tuple, range, dictionary, set, frozenset, boolean, bytes, bytearray,
memoryview, and the special value ‘None’ successively. Each assignment replaces the previous
value, making ‘x’ take on the data type and value of the most recent assignment.
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, 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.
Difference between List, Tuple, Set, and Dictionary
The following table shows the difference between various Python built-in
data structures.
List Tuple Set Dictionary
A list is a non-
A Tuple is a non-
homogeneous The set data A dictionary is
homogeneous data
data structure structure is non- also a non-
structure that
that stores the homogeneous homogeneous
stores elements in
elements in but stores the data structure
columns of a single
columns of a elements in a that stores key-
row or multiple
single row or single row. value pairs.
rows.
multiple rows.
A set is mutable
A tuple is
A list is mutable i.e we can make A dictionary is
immutable i.e we
i.e we can make any changes in mutable, its Keys
can not make any
any changes in the set, its are not
changes in the
the list. elements are not duplicated.
tuple.
duplicated.
List is ordered
A Python variable is a reserved memory location to store values. In other words, a variable in a
Python program gives data to the computer for processing. Every value in Python has a datatype.
Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Variables can
be declared by any name or even alphabets like a, aa, abc, etc Variable Naming Rules in Python
1. Variable names should start with a letter(a-zA-Z) or underscore (_). Valid: age , _age , Age
Invalid : 1age
2. In variable names, no special characters are allowed other than underscore (_). Valid : age_ ,
_age Invalid : age_*
3. Variables are case-sensitive. age and Age are different since variable names are case-
sensitive.
4. Variable names can have numbers but not at the beginning. Example: Age1
5. The variable name should not be a Python keyword. Keywords are also called as reserved
words. Example pass, break, continue. etc are reserved for special meaning in Python. So, we
should not declare keyword as a variable name.
mutable and immutable objects:
As a Python developer, you’ll have to deal with mutable and immutable objects sooner or later.
Mutable objects are those that allow you to change their value or data in place without affecting
the object’s identity. In contrast, immutable objects don’t allow this kind of operation. You’ll
just have the option of creating new objects of the same type with different values.
In Python, mutability is a characteristic that may profoundly influence your decision when
choosing which data type to use in solving a given programming problem. Therefore, you need
to know how mutable and immutable objects work in Python.
In Python, variables don’t have an associated type or size, as they’re labels attached to objects in
memory. They point to the memory position where concrete objects live. In other words, a
Python variable is a name that refers to or holds a reference to a concrete object. In contrast,
Python objects are concrete pieces of information that live in specific memory positions on your
computer.
The main takeaway here is that variables and objects are two different animals in Python:
Both concepts are independent of each other. However, they’re closely related. Once you’ve
created a variable with an assignment statement, then you can access the referenced object
throughout your code by using the variable name. If the referenced object is mutable, then you
can also perform mutations on it through the variable. Mutability or immutability is intrinsic to
objects rather than to variables.
However, if the referenced object is immutable, then you won’t be able to change its internal
state or contained data. You’ll just be able to make your variable reference a different object that,
in Python, may or may not be of the same type as your original object.
If you don’t have a reference (variable) to an object, then you can’t access that object in your
code. If you lose or remove all the references to a given object, then Python will garbage-
collect that object, freeing the memory for later use.
Now that you know that there are differences between variables and objects, you need to learn
that all Python objects have three core properties: identity, type, and value.
1. Value
2. Identity
3. Type
Arguably, the value is probably the most familiar object characteristic that you’ve dealt with. An
object’s value consists of the concrete piece or pieces of data contained in the object itself. A
classic example is a numeric value like an integer or floating-point number:
Python
>>> 42
42
>>> isinstance(42, int)
True
>>> 3.14
3.14
>>> isinstance(3.14, float)
True
These numeric values, 42 and 3.14, are both objects. The first number is an instance of the built-
in int class, while the second is an instance of float. In both examples, you confirm the object’s
type using the built-in isinstance() function.
• Using sys.argv
• Using getopt module
• Using argparse module
Using sys.argv
The sys module provides functions and variables used to manipulate different parts of the Python
runtime environment. This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
One such variable is sys.argv which is a simple list structure. It’s main purpose are:
Example: Let’s suppose there is a Python script for adding two numbers and the numbers are
passed as command-line arguments.
# Python program to demonstrate
# command line arguments
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", sys.argv[0])
# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)
Return Type: Returns value consisting of two elements: the first is a list of (option, value) pairs.
The second is the list of program arguments left after the option list was stripped.
Using argparse module:
Using the argparse module is a better option than the above two options as it provides a lot of
options such as positional arguments, the default value for arguments, help message, specifying
the data type of argument, etc.
Note: As a default optional argument, it includes -h, along with its long version –help.
Python Operators:
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Operators
In the example below, we use the + operator to add together two values:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true
Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:
is not Returns True if both variables are not the same x is not y
object
not in Returns True if a sequence with the specified value is not x not in y
present in the object
<< Zero fill left Shift left by pushing zeros in from the right and let the x << 2
shift leftmost bits fall off
>> Signed right Shift right by pushing copies of the leftmost bit in from x >> 2
shift the left, and let the rightmost bits fall off