Python Notes Complete UNIT - I
Python Notes Complete UNIT - I
INTRODUCTION OF PYTHON
➢ Python is an object-oriented, high level language, interpreted, dynamic and
multipurpose programming language.
➢ Python is easy to learn yet powerful and versatile scripting language which makes
it attractive for Application Development.
➢ Python's syntax and dynamic typing with its interpreted nature, make it an ideal
language for scripting and rapid application development in many areas.
➢ Python supports multiple programming pattern, including object-oriented
programming, imperative and functional programming or procedural styles.
➢ Python is not intended to work on special area such as web programming. That
is why it is known as multipurpose because it can be used with web, enterprise,
3D CAD etc.
➢ We don't need to use data types to declare variable because it is dynamically
typed so we can write a=10 to declare an integer value in a variable.
➢ Python makes the development and debugging fast because there is no
compilation step included in python development and edit-test-debug cycle is
very fast.
➢ It is used for GUI and database programming, client- and server-side web
programming, and application testing.
➢ It is used by scientists writing applications for the world's fastest supercomputers
and by children first learning to program.
COMPILER vs INTERPRETER
• An interpreter is a program that reads and executes code. This includes source
code, pre-compiled code, and scripts. Common interpreters include Perl, Python,
and Ruby interpreters, which execute Perl, Python, and Ruby code respectively.
• Interpreters and compilers are similar, since they both recognize and process
source code.
• However, a compiler does not execute the code like and interpreter does. Instead,
a compiler simply converts the source code into machine code, which can be run
directly by the operating system as an executable program.
• Interpreters bypass the compilation process and execute the code directly.
• Interpreters are commonly installed on Web servers, which allows developers to
run executable scripts within their webpages. These scripts can be easily edited
and saved without the need to recompile the code. Without an interpreter, the
source code serves as a plain text file rather than an executable program.
• Python 1.0
• Python 2.0
• Python 3.0
Python converts the source code into byte code. Byte code represents the fixed
set of instructions created by Python developers representing all types of operations.
The size of each byte code instruction is 1 byte.
Python Shell
1. Interactive Mode.
2. Script Mode.
In Script mode, Python Interpreter runs a program from the source file.
APPLICATIONS OF PYTHON
✓ Machine Learning
✓ GUI Applications (like Kivy, Tkinter, PyQt etc. )
✓ Web frameworks like Django (used by YouTube, Instagram, Dropbox)
✓ Image processing (like OpenCV, Pillow)
✓ Web scraping (like Scrapy, BeautifulSoup, Selenium)
✓ Test frameworks
✓ Multimedia
✓ Scientific computing
✓ Text processing
Python Statements
In general, the interpreter reads and executes the statements line by line i.e.
sequentially. Though, there are some statements that can alter this behavior like
conditional statements. Mostly, python statements are written in such a format that
one statement is only written in a single line. The interpreter considers the ‘new line
character’ as the terminator of one instruction.
Example 1:
print('Welcome to Geeks for Geeks')
Instructions that a Python interpreter can execute are called statements. For example,
a = 1 is an assignment statement.
if statement,
for statement,
while statement etc.
Multi-line statement
For example:
a=1+2+3+\
4+5+6+\
7+8+9
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the
case with [ ] and { }.
For example:
colors = ['red',
'blue',
'green']
We could also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define
a block of code. Python uses indentation.
A code block (body of a function, loop etc.) starts with indentation and ends
with the first unindented line. The amount of indentation is up to you, but it must be
consistent throughout that block.
Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean.
This results into Python programs that look similar and consistent.
Indentation can be ignored in line continuation. But it's a good idea to always
indent. It makes the code more readable.
For example:
if True:
print('Hello')
a=5
and
if True: print('Hello'); a = 5
Both are valid and do the same thing. But the former style is clearer. Incorrect
indentation will result into IndentationError.
Python Comments
Comments are very important while writing a program. It describes what's
going on inside a program so that a person looking at the source code does not have
a hard time figuring it out. You might forget the key details of the program you just
wrote in a month's time. So taking time to explain these concepts in form of
comments is always fruitful.
#This is a comment
#print out Hello
print('Hello')
Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use
hash (#) in the beginning of each line.
For example:
These triple quotes are generally used for multi-line strings. But they can be
used as multi-line comment as well. Unless they are not docstrings, they do not
generate any extra code.
"""This is also a
perfect example of
multi-line comments"""
Input Statement:
Input means the data entered by the user of the program. In python, we have
input() and raw_input ( ) function available for Input.
1) input () function
Syntax:
input (expression)
P R E P A R E D B Y : M R A
Syntax:
print (expression/constant/variable)
The print a line of text, and then the cursor moves down to the next line so any future
printing appears on the next line.
The print statement accepts an additional argument that allows the cursor to remain
on the same line as the printed text:
The expression end=' ' is the keyword that cause the cursor to remain on the same
line as the printed text. Without this keyword argument, the cursor moves down to
the next line after printing the text.
The statement print ('enter an integer value:', end='\n') that is, the default ending for
a line of printed text is the string '\n', the newline control code. Similarly,
Print uses
keyword arguments named sep to specify the string to use insert between
items. The name sep stands for separator. The default value of sep is the string ' ',
containing single space.
The program sep.py shows the sep keyword customizes print’s behavior.
Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning different
data types to variables, you can store integers, decimals or characters in these
variables.
➢ Variable names are case-sensitive (age, Age and AGE are three different
variables)
The operand to the left of the = operator is the name of the variable and the operand
to the right of the = operator is the value stored in the variable.
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.
Let see an example. We will declare variable "a" and print it.
a=100
print a
For example:-
a= 100 # An integer assignment
b = 1000.0 # A floating point
c = "John" # A string
print (a)
print (b)
print (c)
This produces the following result −
100
1000.0
John
Multiple Assignment:
For example:-01
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned
to the same memory location. You can also assign multiple objects to multiple
variables.
For example :-02
a, b, c = 1,2,"madhu “
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable
c.
Output Variables:
Output: madhu
To combine both text and a variable, Python uses the “+” character:
Example: -01
x = "awesome"
print("Python is " + x)
Output
Python is awesome
You can also use the + character to add a variable to another variable:
Example: -02
x = "Python is "
y = "awesome"
z=x+y
print(z)
Output:
Python is awesome
Non-technically, you can think of constant as a bag to store some books and those
books cannot be replaced once place inside the bag.
In Python, constants are usually declared and assigned on a module. Here, the
module means a new file containing variables, functions etc which is imported to
main file. Inside the module, constants are written in all capital letters and
underscores separating the words.
A data type represents the type of data stored into a variable or memory.
There are 5 different data types are:
1) None type
2) Numeric type
3) Sequences
4) Sets
5) Dictionary
The none data type represents an object that does not contain any value. In java
language it is called “NULL” object. But in Python it is called as “none”. In Python
maximum of only one ‘none’ object is provided. If no value is passed to the function,
then the default value will be taken as ‘none’.
✓ int
✓ float
✓ complex
The int data type represents integer number (Whole number). An integer number
is number without fraction. Integers can be of any length, it is only limited by the
memory available.
E.g. a = 10
b = -29
The float data type represents floating point number. A floating-point number is
a number with fraction. Floating point numbers can also be written in scientific
notation using exponentiation format.
E.g. c = 2.0
d = -29.45
x = 2.5E4
E.g. a= 5 +6j
b= 2.5 + 6.2J
We can use the type() function to know which class a variable or a value
belongs to and the isinstance() function to check if an object belongs to a particular
class.
3) Sequences:
A sequence represents a group of items or elements. There are six types of
sequences in Python. Important sequences as follows,
✓ Str
✓ list
✓ tuple
Triple double quote or triple single quotes are used to embed a string in a
another string (Nested string).
e.g
str= “madhu gfgcr”
print(str) # it display - madhu gfgcr
print(str[0]) # it display - m
print(str[4]) # it display –u
print(str[2:4]) # it display 2nd to 4th character – dh
print(str[-1]) # it display first character from end – r
The main difference between a list and an array is that a list can store different
data type elements, but an array can store only one type of elements. List can also
grow dynamically in memory but the size of array is fixed and they cannot grow
dynamically.
e.g.
list=[10,3.5,-20, “madhu”,”sudhan”] # create a list
print(list) # it display all elements in the list : 10,3.5,-20,”madhu”,’sudhan’
print(list[0]) # it display : 10
print(list[1:3]) # it display : 3.5, -20.
print(list[-1]) # it display : ‘sudhan’
P R E P A R E D B Y : M R A
The only difference is that tuples are immutable. Tuples once created cannot be
modified. The tuple cannot change dynamically. That means a tuple can be treated
as read-only list.
e.g.
tpl=(10,3.5,-20, “madhu”,”sudhan”) # create a tuple
print(tpl) # it display all elements in the tuple : 10,3.5,-20,”madhu”,’sudhan’
print(tpl[0]) # it display : 10
print(tpl[1:3]) # it display : 3.5, -20
print(tpl[-1]) # it display : ‘sudhan’
tpl[1]=1.5 # replace 1st location element by 1.5
4) Sets:
e.g.
s = {10,30,5, 30,50}
print(s) # it display : {10,5,30,50}
The remove() method used to remove a particular element from the set as
s.remove(30)
print(s) # it display: {5, 6, 10, 15, 50}
5) Dictionary:
A dictionary is an unordered collection, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values. That
means dictionary contains pair of elements such that first element represents the key
and the next one becomes its value.
The key and value should be separated by a colon(:) and every pair should be
separated by comma. All the elements should be enclosed inside curly brackets.
e.g.
d = {3: ‘madhu’, 4:’rohini’, 5:’laxmi’, 6: ‘sreenika}
Here, d is the name of dictionary. 3 is the key and its associated value is
‘madhu’.
The next is 4 and its value is ‘rohini’ and so on.
print(d) # {3: ‘madhu’, 4:’rohini’, 5:’laxmi’, 6: ‘sreenika}
print(d[5]) # laxmi
print (d.keys()) # dict_keys([3, 4, 5, 6])
print(d.values()) # dict_values(['madhu', 'rohini', 'laxmi', 'srneeika'])
d[2]=’raichur’ # add ‘raichur’ to key value 2
print(d) # {3: 'madhu', 4: 'rohini', 5: 'laxmi', 6: 'srneeika', 2:
'raichur'}
del d[4] # del key 4 and associated value.
print(d) # {3: 'madhu', 5: 'laxmi', 6: 'srneeika', 2: 'raichur'} v
Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.
Operators are used to perform operations on variables and values.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
➢ Identity operators
➢ Membership operators
P R E P A R E D B Y : M R A
Ans: 10
Examples:
>>> x=10 >>> x=10
>>> z=x+20 >>> y=20
>>> z >>> c=x+y
30 >>> c Result: 30
Operators: In Python you can implement the following operations using the
corresponding tokens.
Conditional expression:
String: -
In Python (and almost all other common computer languages), a tab character
can be specified by the escape sequence \t:
>>> print("a\tb")
a b
Create a List:
list = ["aaa", "bbb", "ccc"]
Access Items
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index.
List Index
my_list = ['p','r','o','b','e']
print(my_list[0]) # Output: p
print(my_list[2]) # Output: o
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to
the last item, -2 to the second last item and so on.
my_list = ['p','r','o','b','e']
print(my_list[-1]) # Output: e
print(my_list[-5]) # Output: p
my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[2:5]) # elements 3rd to 5th
print(my_list[:-5]) # elements beginning to 4th
print(my_list[5:]) # elements 6th to end
print (my_list [:]) # elements beginning to end
List Manipulations
Methods that are available with list object in Python programming are:
append()
To add an item to the end of the list, use the append() method.
The syntax of the append() method is:
list.append(item)
Example
list = ["aaa", "bbb", "ccc"]
list.append("madhu")
print(list)
['aaa', 'bbb', 'ccc', 'madhu']
P R E P A R E D B Y : M R A 41
BSC -VI Python_Programming (GUG)
insert()
The insert() method inserts an element to the list at a given index.
The syntax of insert() method is
list.insert(index, element)
Example
fruits = ['aaa', 'bbb', 'ccc']
fruits.insert(1,"sree")
print(fruits)
['aaa', 'sree', 'bbb', 'ccc']
copy()
The copy() method returns a shallow copy of the list.
The syntax of copy() method is:
new_list = list.copy()
Example
fruits = ['aaa', 'bbb', 'ccc']
x=fruits.copy()
x
['aaa', 'bbb', 'ccc']
extend()
The extend() method adds the specified list elements (or any iterable) to the end of
the current list.
The syntax for extend() method
list.extend(seq)
Example
b1=['b','c','c++']
b2=['java','python','R']
b1.extend(b2)
Alternatively, you can also use Python's in-built function sorted() for the same purpose.
sorted(list, key=..., reverse=...)
Example2
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']
print(L[2])
print(L[2][2])
['eee', 'fff']
print(L[2][2][0])
eee
Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples
are written with round brackets.
• Supports all operations for sequences.
• Immutable, but member objects may be mutable.
• If the contents of a list shouldn’t change, use a tuple to prevent items from
accidently being added, changed, or deleted.
• Tuples are more efficient than list due to python’s implementation.
We can construct tuple in many ways:
X=() #no item tuple
X=(1,2,3)
X=tuple(list1)
X=1,2,3,4
Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)
-----------------------
>>> x=()
>>> x
()
----------------------------
Access tuple items: Access tuple items by referring to the index number, inside square
brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items: Once a tuple is created, you cannot change its values. Tuples
are unchangeable.
P R E P A R E D B Y : M R A
BSC -VI Python_Programming (GUG) 47
Above error we can solve by doing typecasting method:
PREPARED BY:MRA
Loop through a tuple: We can loop the values of tuple using for loop
>>> x=(4,5,6,7,2,”madhu”)
>>> for i in x:
print(i)
4
5
6
7
2
Madhu
Count ():
Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2)
4
Index ():
Searches the tuple for a specified value and returns the position of where it was
found.
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> dict1.values()
dict_values(['BSc VI', 'college', 2023])
>>> dict1.items()
dict_items([('brand', 'BSc VI'), ('GFGCR', 'college'), ('year', 2023)])
24 24
39 39
4 16 4 16
5 25 5 25
➢ Example for Immutable data types are: Strings, tuple, int, float,
bool,Unicode.