python_mat_unit1
python_mat_unit1
Python Introduction
Python is developed by Guido van Rossum. Guido van Rossum started implementing Python in
1989. Python is a very simple programming language so even if you are new to programming,
you can learn python without facing any issues.
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 provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential
features.
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java
or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh,
etc. So, we can say that Python is a portable language. It enables programmers to develop the
software for several competing platforms by writing a program only once.
. It has a large community across the world that is dedicatedly working towards make new
python modules and functions. Anyone can contribute to the Python community. The open-
source means, "Anyone can download its source code without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our Python code. It converts the program into byte code, and any platform
can use that byte code.
It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as
Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular
framework for Python web development.
9) GUI Programming Support
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by
line like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language
into our code.
Python programming language is being updated regularly with new features and supports.
There are lots of update in Python versions, started from 1994 to current release.
Python Applications
Python is known for its general-purpose nature that makes it applicable in almost every domain
of software development. Python makes its presence in every emerging field. It is the fastest-
growing programming language and can develop any application.
We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser,
etc. One of Python web-framework named Django is used on Instagram. Python provides many
useful frameworks, and these are given below:
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tkinter or Tk GUI library to develop a user interface.
3) Console-based Application
Console-based applications run from the command-line or shell. These applications are
computer program which are used commands to execute. This kind of application was more
popular in the old generation of computers. Python can develop this kind of application very
effectively.
4) Software Development
Python is useful for the software development process. It works as a support language and can
be used to build control and management, testing, etc.
This is the era of Artificial intelligence where the machine can perform the task the same as the
human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.
6) Business Applications
Business Applications differ from standard applications. E-commerce and ERP are an example of
a business application. This kind of application requires extensively, scalability and readability,
and Python provides all these features.
Oddo is an example of the all-in-one Python-based application which offers a range of business
applications.
7) Audio or Video-based Applications
Python is flexible to perform multiple tasks and can be used to create multimedia applications.
Some multimedia applications which are made by using Python are TimPlayer, cplay, etc.
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used
to develop the 3D representation of a part of a system.
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an
Organization.
Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements.
Python Virtual Machine (PVM) is a program which provides programming environment. The role of PVM
is to convert the byte code instructions into machine code so the computer can execute those machine
code instructions and display the output.
Interpreter converts the byte code into machine code and sends that machine code to the computer
processor for execution.
Python Memory Management
Memory management is very important for software developers to work efficiently with any
programming language.
In Python, memory is managed by the Python manager which determines where to put the
application data in the memory. So, we must have the knowledge of Python memory manager
to write efficient code and maintainable code.
Let's assume memory looks like an empty book and we want to write anything on the book's
page. Then, we write data any data the manager find the free space in the book and provide it
to the application. The procedure of providing memory to objects is called allocation.
On the other side, when data is no longer use, it can be deleted by the Python memory
manager. But the question is, how? And where did this memory come from?
Memory allocation is an essential part of the memory management for a developer. This
process basically allots free space in the computer's virtual memory, and there are two types of
virtual memory works while executing programs.
Static memory allocation happens at the compile time. For example - In C/C++, we declare a
static array with the fixed sizes. Memory is allocated at the time of compilation. However, we
cannot use the memory again in the further program.
Stack Allocation
The Stack data structure is used to store the static memory. It is only needed inside the
particular function or method call. The function is added in program's call stack whenever we
call it. Variable assignment inside the function is temporarily stored in the function call stack;
the function returns the value, and the call stack moves to the text task. The compiler handles
all these processes, so we don't need to worry about it.
Call stack (stack data structure) holds the program's operational data such as subroutines or
function call in the order they are to be called. These functions are popped up from the stack
when we called.
Unlike static memory allocation, Dynamic memory allocates the memory at the runtime to the
program. For example - In C/C++, there is a predefined size of the integer of float data type but
there is no predefine size of the data types. Memory is allocated to the objects at the run time.
We use the Heap for implement dynamic memory management. We can use the memory
throughout the program.
everything in Python is an object means dynamic memory allocation inspires the Python
memory management. Python memory manager automatically vanishes when the object is no
longer in use.
Heap data structure is used for dynamic memory which is not related to naming counterparts. It
is type of memory that uses outside the program at the global space. One of the best
advantages of heap memory is to it freed up the memory space if the object is no longer in use
or the node is deleted.
Garbage Collection
Garbage collection is a process in which the interpreter frees up the memory when not in use
to make it available for other objects.
Assume a case where no reference is pointing to an object in memory i.e. it is not in use so,
the virtual machine has a garbage collector that automatically deletes that object from the
heap memory
Provide both single and Provide partial multiple Provide both single and
multiple inheritance inheritance using multiple inheritance
interfaces
Has limited number of Has library support for Has a huge set of libraries that
library support many concepts like UI make it fit for AI, datascience,
etc.
Code length is a bit lesser, Java has quite huge code. Smaller code length, 3-4 times
1.5 times less that java. less than java.
Functions and variables Every bit of code is inside Functions and variables can be
are used outside the class a class. declared and used outside the
class also.
C++ program is a fast Java Program compiler a Due to the use of interpreter
compiling programming bit slower than C++ execution is slower.
language.
Python Syntax
Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:
Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Creating a Comment
Example
#This is a comment
print("Hello, World!")
Example
Comments spanning multiple lines have " " " or ' ' ' on either end. This is the same as a
multiline string, but they can be used as comments:
"""
This type of comment spans multiple lines.
These are mostly used for documentation of functions, classes and modules.
"""
Implicitly, Python encourages the use of a single statement per line which makes code more
readable.
If you want to specify more than one logical line on a single physical line, then you have to
explicitly specify this using a semicolon (;) which indicates the end of a logical line/statement.
For example,
i=5
print i
is effectively same as
i = 5; print i;
or even
i = 5; print i
However, I strongly recommend that you stick to writing a single logical line in a single
physical line only. Use more than one physical line for a single logical line only if the logical line
is really long.
Indentation
Whitespace is important in Python. Actually, whitespace at the beginning of the line is
important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of
the logical line is used to determine the indentation level of the logical line, which in turn is
used to determine the grouping of statements.
This means that statements which go together must have the same indentation. Each such set
of statements is called a block.
One thing you should remember is how wrong indentation can give rise to errors.
For example:
i=5
print 'Value is', i # Error! Notice a single space at the start of the line
print 'I repeat, the value is', i
When you run this, you get the following error:
File "whitespace.py", line 4
print 'Value is', i # Error! Notice a single space at the start of the line
^
SyntaxError: invalid syntax
Notice that there is a single space at the beginning of the second line. The error indicated by
Python tells us that the syntax of the program is invalid i.e. the program was not properly
written. What this means to you is that you cannot arbitrarily start new blocks of statements
(except for the main block which you have been using all along, of course).
How to indent
Do not use a mixture of tabs and spaces for the indentation as it does not work across different
platforms properly. I strongly recommend that you use a single tab or two or four spaces for
each indentation level.
Python Variables
Variables are containers for storing data values.
Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.
We don't need to declare explicitly variable in Python. When we assign any value to the
variable, that variable is declared automatically.
Example
x=5
y = "John"
print(x)
print(y)
A variable name must start with a letter or the underscore character (_)
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
Variable name must not contain any white-space
Variable name must not be similar to any keyword defined in the language.
Examples of valid variable: a123, _n, n_9, etc.
Examples of invalid variable: 1a, n%4, n 9, etc.
Python Variables - Assign Multiple Values
Example
Python enables us to check the type of the variable used in the program. Python provides us
the type() function, which returns the type of the variable passed.
You can get the data type of a variable with the type() function.
Example 1
x=5
y = "John"
print(type(x))
print(type(y))
output
<class 'int'>
<class 'str'>
Example 2
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Python has the following data types built-in by default, in these categories:
In Python, the data type is set when you assign a value to a variable:
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor functions:
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = range(6) range
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Numeric Types
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 4+1j # complex
To verify the type of any object in Python, use the type() function:
Python Casting (Explicit conversion of data type)
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.
int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (providing the string represents a whole number)
float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals
Example-1
x = int(1)
y = int(2.8)
z = int("3")
print(x)
print(y)
print(z)
output
1
2
3
Example-2
x = float(1)
y = float(2.8)
z = float("3")
w = float("4.2")
print(x)
print(y)
print(z)
print(w)
output
1.0
2.8
3.0
4.2
Example-3
x = str("s1")
y = str(2)
z = str(3.0)
print(x)
print(y)
print(z)
output
s1
2
3.0
String
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.
Example - 1
Slicing Strings
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
Example
b = "Hello, World!"
print(b[2:5])
output
llo
By leaving out the start index, the range will start at the first character:
Example
b = "Hello, World!"
print(b[:5])
output
Hello
Slice To the End
By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
output
llo, World!
Example - 2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the
strings.
List is a collection which is ordered and changeable. Allows duplicate members.
The list is changeable, meaning that we can change, add, and remove items in a list after
it has been created.
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
Output:
To add an item to the end of the list, use the append() method:
Example
Insert Items
Example
Example
Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Example
List objects have a sort() method that will sort the list alphanumerically, ascending, by default:
Example
Sort Descending
Example
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example
You can loop through the list items by using a for loop:
Example
You can also loop through the list items by referring to their index number.
Example
You can loop through the list items by using a while loop.
Use the len() function to determine the length of the list, then start at 0 and loop your way
through the list items by referring to their indexes.
Example
Print all items, using a while loop to go through all the index numbers
List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the
name.
Without list comprehension you will have to write a for statement with a conditional test
inside:
Example
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
output
[‘apple’,’banana’,’mango’]
With list comprehension you can do all that with only one line of code:
Example
print(newlist)
output
[‘apple’,’banana’,’mango’]
The Syntax
The return value is a new list, leaving the old list unchanged.
Condition
The condition is like a filter that only accepts the items that valuate to True.
Example
List Comprehension offers the shortest syntax for looping through lists:
Example
A short hand for loop that will print all items in a list:
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
output
apple
banana
cherry
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a
tuple.
You can access tuple items by referring to the index number, inside square brackets:
Example
Negative Indexing
-1 refers to the last item, -2 refers to the second last item etc.
Example
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Update Tuples
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the
list back into a tuple.
Example
print(x)
Add Items
Since tuples are immutable, they do not have a build-in append() method, but there are other
ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a
list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
2. Add tuple to a tuple. You are allowed to add tuples to tuples, so if you want to add one item,
(or many), create a new tuple with the item(s), and add it to the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:
print(thistuple)
Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can use the same
workaround as we used for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Example
Example
Example
# Tuple slicing
print (tup[1:])
print (tup[0:1])
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
You can loop through the tuple items by using a for loop.
Example
output
apple
banana
cherry
Range
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and stops before a specified number.
Syntax
Parameter Values
Parameter Description
stop Required. An integer number specifying at which position to stop (not included).
Example
Create a sequence of numbers from 3 to 5, and print each item in the sequence:
x = range(3, 6)
for n in x:
print(n)
output
3
4
5
Example
x = range(3, 20, 2)
for n in x:
print(n)
Mapping Types
Dictionary
Dictionary is an unordered set (in python 3.6 and earlier version) of a key-value pair of items. It
is like an associative array or a hash table where each key stores a specific value. Key can hold
any primitive data type, whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces
{}.
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
# Printing dictionary
print (d)
print (d.keys())
print (d.values())
Output:
Example:
print(key,' - ',value)
output
1 - 45
2 - Alex
3 - john
4 - mike
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'. Consider the following
example.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Sets are used to store multiple items in a single variable.
Note: Set items are unchangeable, but you can remove items and add new items.
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
The set is created by using a built-in function set(), or a sequence of elements is passed in the
curly braces and separated by the comma. It can contain various types of values. Consider the
following example.
set2.add(10)
print(set2)
Add Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method.
Example
Add an item to a set, using the add() method:
output
{'apple', 'banana', 'orange', 'cherry'}
Remove Item
To remove an item in a set, use the remove()
Example
Remove "banana" by using the remove() method:
output
{'cherry', 'apple'}
FrozenSets
The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set
cannot be changed and therefore it can be used as a key in the dictionary.
The elements of the frozen set cannot be changed after the creation. We cannot change or
append the content of the frozen sets by using the methods like add() or remove().
The frozenset() method is used to create the frozenset object. The iterable sequence is passed
into this method which is converted into the frozen set as a return type of the method.
Consider the following example to create the frozen set.
Frozenset = frozenset([1,2,3,4,5])
print(type(Frozenset))
print("\nprinting the content of frozen set...")
for i in Frozenset:
print(i);
Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after creatio
n
Output:
<class 'frozenset'>
Binary Types:
bytes and bytearray are used for manipulating binary data. The memoryview uses the buffer
protocol to access the memory of other binary objects without needing to make a copy.
Bytes objects are unchallengeable sequences of single bytes. We should use them only when
working with ASCII compatible data.
The syntax for bytes literals is same as string literals, except that a 'b' prefix is added.
bytearray objects are always created by calling the constructor bytearray(). These are mutable
(changeable) objects.
Example
bArray1 = b"XYZ"
bArray2 = bArray1.replace(b"X", b"P")
print(bArray2)
byteArray1 = b'ABBABCACBBACA'
print(byteArray1.count(b'AC'))
OUTPUT
b'\xa2\xf7E\t'
a2f74509
b'PYZ'
2
5
83
b'trin'
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
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:
-= 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
Python Comparison Operators
Example
x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10
Python Identity Operators
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:
Example
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
# returns False because x is not the same object as y, even if they have the same content
Python Membership Operators
Example
x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list
Python Bitwise Operators