Python Notes
Python Notes
messages.pdf_cover_qr_code_label
messages.downloaded_
messages.studocu_not_sponsored_or_endorsed_by_college
messages.downloaded_
UNIT 1
1. INTRODUCTION
What is Python
Python Features
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.
2) Expressive Language
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.
messages.downloaded_
5) Free and Open Source
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.
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.
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.
In Python, we don't need to specify the data-type of the variable. When we assign some
value to the variable, it automatically allocates the memory to the variable at run time.
messages.downloaded_
o The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version
0.9.0) to [Link].
o In 1994, Python 1.0 was released with new features like lambda, map,
filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage
collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python
language, which was capable of Exception Handling and interfacing with the
Amoeba Operating System.
Python Applications:
1) Web Applications
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.
messages.downloaded_
2) Desktop GUI Applications
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a 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.
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.
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. The few multimedia libraries are given below.
o Gstreamer
o Pyglet
o QT Phonon
(8)Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
messages.downloaded_
2. Numbers in python
o The number data types are used to store the numeric values inside the variables.
Number objects are created when some value is assigned to a variable. For example,
a = 5 will create a number object a with value 5.
o Int (signed Integer object) : they are the negative or non-negative numbers with no
decimal point. There is no limit on an integer in python.
1. float(floatingpointnumbers) :
The float type is used to store the decimal point (floating point) numbers. In
python, float may also be written in scientific notation representing the power of
10. for example, 2.5e2 represents the value 250.0.
• Complex(complexnumbers)
Complex numbers are of the form a+bj where a is the real part of the number and bj
is the imaginary part of the number. The imaginary i is nothing but the square root of
-1. It is not as much used in the programming.
The various types of numbers like int, float, complex are also as the functions in python. It is
similar to the wrapper classes of Java which is mostly used for typecasting.
There are the following functions which are used to perform type conversion.
Example
i="123456"
print(type(i))
num = int(i)
print(num)
print(type(num))
j = 190.98
print(int(j));
Output:
messages.downloaded_
<class 'str'>
123456
<class 'int'>
190
There are various in-built functions which can be directly used to perform various
calculations on the numbers defined in the program.
Function Description
abs(x) The (positive) distance between x and 0.
ciel(x) The ceiling value of x, i.e., the smallest integer that is not less than x.
cmp(x,y) Compares x and y. It returns 0 if x == y, -1 if x<y, 1 if x > y.
exp(x) The exponent of x that is ex.
fabs(x) The absolute value of x.
floor(x) The floor value of x, i.e., the greatest integer that is less than x.
log(x) The natural log value of x.
log10(x) The base 10 log of x is returned.
max(x1,x2 The maximum of the sequence is returned.
,......)
min(x1,x2, The minimum of the sequence is returned.
.. . .)
modf(x1,x A tuple is returned containing the fractional and integer parts of a floating point
2,........) number. The integer part is also returned as a float.
pow(x,y) Returns x ** y.
round(x[, The value of x is rounded to n digits.
n])
sqrt(x) The square root of x is retuned.
3. Python String
➢ Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes.
➢ The computer does not understand the characters; internally, it stores manipulated
character as the combination of the 0's and 1's.
➢ Each character is encoded in the ASCII or Unicode character. So we can say that
Python strings are also called the collection of Unicode characters.
messages.downloaded_
Syntax:
Output:
Hello Python
Hello Python
Triple quotes are generally used for
represent the multiline or
docstring
Like other languages, the indexing of the Python strings starts from 0. For example, The
string "HELLO" is indexed as given in the below figure.
messages.downloaded_
Consider the following example:
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
splitting
• the slice operator [] is used to access the individual characters of the string.
• However, we can use the : (colon) operator in Python to access the substring from
the given string. Consider the following example.
messages.downloaded_
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if
str = 'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing
else.
= "JAVATPOINT"
print(str[0:])
print(str[1:5])
print(str[2:4])
print(str[:3])
print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
it starts from the rightmost character, which is indicated as -1. The second rightmost index
indicates -2, and so on. Consider the following image.
messages.downloaded_
Consider the following example
1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
7. # Reversing the given string
8. print(str[::-1])
9. print(str[-12])
Output:
T
I
NT
OIN
ATPOI
TNIOPTAVAJ
IndexError: string index out of range
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string
object doesn't support item assignment i.e., A string can only be replaced with new string
since its content cannot be partially replaced. Strings are immutable in Python.
Example
1. str = "HELLO"
messages.downloaded_
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
As we know that strings are immutable. We cannot delete or remove the characters from the
string. But we can delete the entire string using the del keyword.
1. str = "JAVATPOINT"
2. del str[1]
Output:
str1 = "JAVATPOINT"
del str1
print(str1)
format() method
• The format() method is the most flexible and useful method in formatting strings.
• The curly braces {} are used as the placeholder in the string and replaced by
the format() method argument. Let's have a look at the given an example:
messages.downloaded_
8. print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))
Output:
STRING METHODS
• Python String capitalize()
This method returns a copy of the original string and converts the first character of the string to
a capital (uppercase) letter, while making all other characters in the string lowercase letters.
Eg
print([Link]())
output:
• String count()
This function is an inbuilt function in Python programming language that returns the number of
occurrences of a substring in the given string. In this article, we will explore the details of
the count() method
Eg
output 4
Python String islower()
messages.downloaded_
print("geeks".islower())
output:
True
This method returns whether all characters in a string are uppercase or not.
Eg
print(("GEEKS").isupper())
output:
True
Python join()
This is an inbuilt string function in Python used to join elements of the sequence separated
by a string separator. This function joins elements of a sequence and makes it a string.
Example:
str = '-'.join('hello')
print(str)
Output:
h-e-l-l-o
Eg
print("Original String:")
print(text)
messages.downloaded_
print("\nConverted String:")
print([Link]())
Output:
Original String:
GeEks FOR geeKS
Converted string:
geeks for geeks
This method converts all uppercase characters to lowercase and vice versa of the given
string and returns it.
Eg
string = "gEEksFORgeeks"
print([Link]())
string = "geeksforgeeks"
print([Link]())
string = "GEEKSFORGEEKS"
print([Link]())
Output:
GeeKSforGEEKS
GEEKSFORGEEKS
This method converts all lowercase characters in a string into uppercase characters and
returns it. In this article, we’ll explore Python’s upper() method in-depth
Eg
uppercase_text = original_text.upper()
print(uppercase_text)
output:
messages.downloaded_
4. Python Variables
• A Python variable name must start with a letter or the underscore character.
• A Python variable name cannot start with a number.
• A Python variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ ).
• Variable in Python names are case-sensitive (name, Name, and NAME are three
different variables).
• The reserved words(keywords) in Python cannot be used to name the variable in
Python.
• Here, we have assigned a number, a floating point number, and a string to a variable
such as age, salary, and name.
age = 45
salary = 1456.8
name = "John"
print(age)
print(salary)
print(name)
Output:
45
1456.8
John
✓ Local variables in Python are the ones that are defined and declared inside a
function.
We can not call this variable outside the function.
messages.downloaded_
def f():
s = "Welcome geeks"
print(s)
f()
Output:
Welcome geeks
✓ Global variables in Python are the ones that are defined and declared outside a
function, and we need to use them inside a function.
# Global scope
s = "I love Geeksforgeeks"
f()
Output:
I love Geeksforgeeks
5. Python List:
✓ A list is a collection of items separated by commas and denoted by the symbol [].
A list is a collection of different kinds of values or items.
✓ Since Python lists are mutable, we can change their elements after forming.
✓ The comma (,) and the square brackets [enclose the List's items] serve as separators.
List Declaration
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
print(list1)
print(list2)
print(type(list1))
print(type(list2))
messages.downloaded_
Output:
Characteristics of Lists
Output:
False
✓ The indexing procedure is carried out similarly to string processing. The slice
operator [] can be used to get to the List's components.
✓ The index ranges from 0 to length -1. The 0th index is where the List's first element is
stored; the 1st index is where the second element is stored, and so on.
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
o The beginning indicates the beginning record position of the rundown.
o The stop signifies the last record position of the rundown.
messages.downloaded_
o Within a start, the step is used to skip the nth element: stop.
The start parameter is the initial index, the step is the ending index, and the value of the end
parameter is the number of elements that are "stepped" through. The default value for the
step is one without a specific value. Inside the resultant Sub List, the same with record start
would be available, yet the one with the file finish will not. The first element in a list appears
to have an index of zero.
list = [1,2,3,4,5,6,7]
1. print(list[0])
2. print(list[1])
3. print(list[2])
4. print(list[3])
5. print(list[0:6])
6. print(list[:])
7. print(list[2:5])
8. print(list[1:6:2])
Output:
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
1. list = [1,2,3,4,5]
2. print(list[-1])
3. print(list[-3:])
4. print(list[:-1])
5. print(list[-3:-1])
messages.downloaded_
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
Negative indexing allows us to obtain an element, as previously mentioned. The rightmost item
in the List was returned by the first print statement in the code above. The second print
statement returned the sub-list, and so on.
Due to their mutability and the slice and assignment operator's ability to update their values,
lists are Python's most adaptable data structure. Python's append() and insert() methods
can also add values to a list.
Consider the following example to update the values inside the List.
Code
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The list elements can also be deleted by using the del keyword. Python also provides us the
remove() method if we do not know which element is to be deleted from the list.
messages.downloaded_
Consider the following example to delete the list elements.
Code
1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to second index
4. list[2] = 10
5. print(list)
6. # Adding multiple element
7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the list
10. list[-1] = 25
11. print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
1. Repetition
messages.downloaded_
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation
Code
Output:
3. Length
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
len(list1)
Output:
4. Iteration
Code
messages.downloaded_
4. # iterating
5. for i in list1:
6. print(i)
Output:
12
14
16
39
40
5. Membership
Code
Output:
False
False
False
True
True
True
messages.downloaded_
Python provides the following built-in functions, which can be used with the lists.
1. len()
2. max()
3. min()
len( )
Output:
Max( )
Output:
782
Min( )
Output:
103
6. Tuple
messages.downloaded_
Tuple is one of 4 built-in data types in Python used to store collections of dataA tuple is a
collection which is ordered and unchangeable.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Example
tuple = ("apple", "banana", "cherry")
print(tuple)
Tuples in Python provide two ways by which we can access the elements of a tuple.
Using square brackets we can get the values from tuples in Python.
Output:
messages.downloaded_
Access Tuple using Negative Index
In the above methods, we use the positive index to access the value in Python, and here we
will use the negative index within [].
var = (1, 2, 3)
Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1
• Concatenation
• Nesting
• Repetition
• Slicing
• Deleting
• Tuples in a Loop
messages.downloaded_
Eg
tuple1 = (0, 1, 2, 3)
tuple2 = ('python',
'geek') print(tuple1 +
tuple2)
Output:
We can create a tuple of multiple same elements from a single element in that tuple.
Eg
tuple3 =
Output:
('python',)*3
('python', 'python', 'python')
print(tuple3)
Dictionary
Eg:
Tuples in Python provide two ways by which we can access the elements of a tuple.
messages.downloaded_
Python Access Tuple using a Positive Index
Using square brackets we can get the values from tuples in Python. var =
Output:
In the above methods, we use the positive index to access the value in Python, and here we will
use the negative index within [].
var = (1, 2, 3)
Output:
Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] = 1
• Concatenation
messages.downloaded_
• Nesting
• Repetition
• Slicing
• Deleting
7. Dictionary
Example
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
There is also a method called get() that will give you the same result:
messages.downloaded_
Eg
print(type(Employee))
print(Employee)
Employee["Company"] = input("Company:");
print(Employee)
Output
<class 'dict'>
printing Employee data ....
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"} Enter the
details of the new employee....
Name: Sunny Age:
38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}
messages.downloaded_
The items of the dictionary can be deleted by using the del keyword as given below.
Output
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary:
Employee Lets try to print it again
NameError: name 'Employee' is not defined.
8. Python Set
A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable, and the sets remove the duplicate elements. Sets are mutable which
means we can modify it after its creation.
Creating a set
A set is created by using the set() function or placing all the elements within a pair of curly
braces.
Example
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
messages.downloaded_
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)
Output
When the above code is executed, it produces the following result. Please note how the
order of the elements has changed in the result.
We cannot access individual values in a set. We can only access all the elements together as
shown above. But we can also get a list of individual elements by looping through the set.
Example
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
for d in Days:
print(d)
Output
Wed
Sun
Fri
Tue
Mon
Thu
Sat
We can add elements to a set by using add() method. Again as discussed there is no specific
index attached to the newly added element.
Example
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
messages.downloaded_
[Link]("Sun")
print(Days)
Output
We can remove elements from a set by using discard() method. Again as discussed there is
no specific index attached to the newly added element.
Example
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
[Link]("Sun")
print(Days)
Output
Union of Sets
The union operation on two sets produces a new set containing all the distinct elements
from both the sets. In the below example the element “Wed” is present in both the sets.
Example
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA|DaysB
print(AllDays)
Output
When the above code is executed, it produces the following result. Please note the result
has only one “wed”.
messages.downloaded_
set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])
Intersection of Sets
The intersection operation on two sets produces a new set containing only the common
elements from both the sets. In the below example the element “Wed” is present in both
the sets.
Example
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB
print(AllDays)
Output
When the above code is executed, it produces the following result. Please note the result
has only one “wed”.
set(['Wed'])
Difference of Sets
The difference operation on two sets produces a new set containing only the elements from
the first set and none from the second set. In the below example the element “Wed” is
present in both the sets so it will not be found in the result set.
Example
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA - DaysB
print(AllDays)
Output
When the above code is executed, it produces the following result. Please note the result
has only one “wed”.
set(['Mon', 'Tue'])
9. set comparisons:
messages.downloaded_
In set we can check if the element exist in the set or not.
Example:
set_1 = {1,2,3,4,5}
print(1 in set_1)
print(5 not in set_1)
Output:
True
False
We use this operation to check whether two sets are equivalent to each other or not.
Example:
set_1 = {1,2,3,4,5}
set_2 = {1,2,3,4,5}
print(set_1 == set_2)
print(set_1 != set_2)
Output:
True
True
3. Subset Check
A subset is a set that entirely exists within another. We use this operator to check whether
S1 is the subset of S2 or not.
Example:
set_1 = {1,2,3,4}
set_2 = {3,4,5,6}
print(set_1.issubset(set_2))
Output: False
4. Superset Check
A superset is the opposite of a subset. A set is declared as a superset if all elements of the
another set exist within it.
messages.downloaded_
Example:
set_1 = {1,2,3,4}
set_2 = {3,4}
print(set_1.issuperset(set_2))
Output: True
messages.downloaded_