Python Unit 1 Notes
Python Unit 1 Notes
1. INTRODUCTION
What is Python
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
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX,
and Macintosh, etc.
5) Free and Open Source
6) Object-Oriented Language
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.
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 Applications:
1) Web 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
4) Software Development
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
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.
[Link] 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(nu
m)) j = 190.98
print(int(j));
Output:
<class
'str'>
12345
6
<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,x The maximum of the sequence is returned.
2
,.....)
min(x1,x The minimum of the sequence is returned.
2,
....)
modf(x1, A tuple is returned containing the fractional and integer parts of a floating
x 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
Syntax:
Creating String in
Python
#Using double
quotes str2 =
"Hello Python"
print(str2)
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.
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.
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.
example: str =
"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
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"
2. print(str)
3. str = "hello"
4. print(st
r)
Output
HELLO
hello
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:
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
name = "geeks FOR
geeks"
print([Link]())
output:
Geeks for geeks
• String count()
my_string = "GeeksForGeeks"
char_count = my_string.count('e')
print(char_count)
outpu
t4
Python String islower()
This method checks if all characters in the string are
lowercase. Eg
print("geeks".islower())
output:
True
Python join()
Example:
str = '-'.join('hello')
print(str)
Output:
h-e-l-l-o
Eg
print("Original String:")
print(text)
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:
GeeKSforGE
EKS
GEEKSFORG
EEKS
• 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.
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
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
[Link] List:
List Declaration
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
print(list1)
print(list2)
print(type(list
1))
print(type(list
2))
Output:
Characteristics of Lists
Output:
False
✓ 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.
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]
.
# negative indexing example
1. list = [1,2,3,4,5]
2. print(list[-1])
3. print(list[-3:])
4. print(list[:-1])
5. print(list[-3:-1])
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
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
st)
Outpu:
[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.
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(li
st)
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
[Link]
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
[Link]
Code
Output:
[Link]
list Eg
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
len(list1)
Output:
[Link]
Code
Output:
12
14
16
39
40
[Link]
Code
Output:
False
False
False
True
True
True
1. len()
2. max()
3. min()
len( )
Output:
Max( )
1)) Output:
782
Min( )
It returns the minimum element of the list
1)) Output:
103
[Link]
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.
Output:
Value in Var[0] =
Geeks Value in
Var[1] = for Value in
Var[2] = Geeks
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)
print("Value in Var[-1] = ", var[-1])
print("Value in Var[-2] = ", var[-2])
print("Value in Var[-3] = ", var[-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
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
Tuples in Python provide two ways by which we can access the elements of a tuple.
Output:
Value in Var[0] =
Geeks Value in
Var[1] = for Value in
Var[2] = Geeks
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
[Link]
Example
thisdict = { "brand": "Ford", "model":"Mustang", "year":1964 }
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:
"salary":45000,"Company":"WIPRO"} print(type(Employee))
print(Employee)
")); Employee["Company"] =
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'}
<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.
[Link] 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"}
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
result − Wed
Sun
Fri
Tue
Mo
n
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"])
[Link]("Su
n")
print(Days)
Output
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”.
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'])
[Link] comparisons:
Set Membership Check
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:
Tru
e
Fals
e
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
Output: True