PythonNotes Original
PythonNotes Original
S.NO TOPIC
1. Definition
Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-level
programming language. Python is dynamically-typed and garbage-collected programming language.
It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also
available under the GNU General Public License (GPL).
2. Characteristics of Python
Following are important characteristics of Python Programming −
3. Applications 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.
PYTHON NOTES 2
Scalable − Python provides a better structure and support for large programs than shell
scripting.
Interactive Mode
$ python
Python 3.6.8 (default, Sep 10 2021, 09:13:53)
[GCC 8.5.0 20210514 (Red Hat 8.5.0-3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> print ("Hello, World!")
Hello, World!
Script Mode
Create a file demo.py and type the program and execute by hitting F5 key.
o All the characters except the first character may be an alphabet of lower-case(a-z),
upper-case (A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,
*).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
6. Variable assigning methods
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
o/p : 50 50 50
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
o/p: 5 10 15
7. Local Variable
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
10. add()
o/p
101
Welcome to Javatpoint
9. Python String data type
o/p
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists are the most versatile compound data types. A Python list contains items separated by
commas and enclosed within square brackets ([]). To some extent, Python lists are similar to arrays
in C. One difference between them is that all the items belonging to a Python list can be of different
data type where as C array can store elements related to a particular data type.
Python tuple is another sequence data type that is similar to a list. A Python tuple consists of
a number of values separated by commas. Unlike lists, however, tuples are enclosed within
parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
Python range() is an in-built function in Python which returns a sequence of numbers starting
from 0 and increments to 1 until it reaches a specified number.
We use range() function with for and while loop to generate a sequence of numbers
Syntax:
range (start,stop,step)
PYTHON NOTES 6
example
for i in range(5):
print(i)
o/p : 0 1 2 3 4
example
o/p : 1 3
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
o/p
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
14. Python boolean type is one of built-in data types which represents one of the two values
either True or False. Python bool() function allows you to evaluate the value of any expression and
returns either True or False based on the expression
a = True
# display the value of a
print(a)
o/p:
true
<class 'bool'>
1. Conversion to int
a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3") # c will be 3
print (a)
print (b)
print (c)
o/p : 1 2 3
2. Conversion to float
print (a)
print (b)
print (c)
o/p: 1.0
2.2
3.3
3. Conversion to string
print (a)
print (b)
print (c)
o/p: 1
2.2
3.3
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
PYTHON NOTES 8
% Modulus 22 % 10 = 2
** Exponent 4**2 = 16
= Assignment Operator a = 10
<< Binary Shift left by pushing zeros in from the right and
Left let the leftmost bits fall off
Shift
>> Binary Shift right by pushing copies of the leftmost bit in from the left,
Right and let the rightmost bits fall off
Shift
20. Python Logical Operators
and Logical AND If both the operands are true then condition (a and b) is true.
becomes true.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false.
21. Python Membership Operators
Statement Description
If - else Statement The if-else statement is similar to if statement except the fact
that, it also provides the block of the code for the false case of
the condition to be checked. If the condition provided in the
if statement is false, then the else statement will be executed.
Nested if Statement Nested if statements enable us to use if? else statement inside
an outer if statement.
23. If statement
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")
25. If…else….statement
age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
and-----------------------
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")
The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.
2 Continue statement This command skips the current iteration of the loop.
The statements following the continue statement are
not executed once the Python interpreter reaches the
continue statement.
PYTHON NOTES 12
3 Pass statement The pass statement is used when a statement is syntactically neces
be executed.
29. The for loop statement
1. # Python program to show how the for loop works
2. # Creating a sequence which is a tuple of numbers
3. numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
4. # variable to store the square of the number
5. square = 0
6. # Creating an empty list
7. squares = []
8. # Creating a for loop
9. for value in numbers:
square = value ** 2
squares.append(square)
10. print("The list of squares is", squares)
o/p
The list of squares is: [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
1. # Python program to show how to use else statement with for loop
2.
3. # Creating a sequence
4. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
5.
6. # Initiating the loop
7. for value in tuple_:
8. if value % 2 != 0:
9. print(value)
10. # giving an else statement
11. else:
12. print("These are the odd numbers present in the tuple")
39397
These are the odd numbers present in the tuple
3. print(range(15))
4. print(list(range(15)))
5. print(list(range(4, 9)))
6. print(list(range(5, 25, 4)))
o/p
range (0.15)
[0, 1,2,3,4,5,6,7,8,9,10,11,12,13,14]
[4,5,6,7,8]
[5,9,13,17,21]
31. 1. # Python program to iterate over a sequence with the help of indexing
2.
3. tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")
4.
5. # iterating over tuple_ using range() function
6. for iterator in range(len(tuple_)):
7. print(tuple_[iterator].upper())
o/p
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
o/p
Python Loops
Python Loops
Python Loops
Python Loops
1. # Code to find the sum of squares of each element of the list using for loop
2. # creating the list of numbers
3. numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
4. # initializing a variable that will store the sum
5. sum_ = 0
6. # using for loop to iterate over the list
7. for num in numbers:
8. sum_ = sum_ + num ** 2
9. print("The sum of squares is: ", sum_)
o/p
The sum of squares is: 774
o/p
[3,5,6,8,4,5,7,8,10,6]
1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);
o/p
p
y
t
h
o/p
PYTHON NOTES 15
var1[0]: H
var2[1:5]: ytho
o/p
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]
O/p
Value available at index 2 :
1997
New value available at index 2 :
2001
Len()
1. # size of the list
2. # declaring the list
3. list1 = [12, 16, 18, 20, 39, 40]
4. # finding length of the list
5. len(list1)
o/p
6
Max()
1. # maximum of the list
2. list1 = [103, 675, 321, 782, 200]
3. # large element in the list
4. print(max(list1))
o/p
782
Min()
1. # minimum of the list
2. list1 = [103, 675, 321, 782, 200]
3. # smallest element in the list
4. print(min(list1))
o/p
103
40. Tuples
A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists.
The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.
PYTHON NOTES 18
o/p
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
o/p
(12, 34.56, 'abc', 'xyz')
o/p
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
O/P
b. Slicing
# Python program to show how slicing works in Python tuples
# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Using slicing to access elements of the tuple
print("Elements between indices 1 and 3: ", tuple_[1:3])
# Using negative indexing in slicing
PYTHON NOTES 20
O/P
Elements between indices 1 and 3: ('Tuple', 'Ordered')
Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable',
'Collection', 'Objects')
c. Repetition
# Python program to show repetition in tuples
tuple_ = ('Python',"Tuples")
print("Original tuple is: ", tuple_)
# Repeting the tuple elements
tuple_ = tuple_ * 3
print("New tuple is: ", tuple_)
O/p
Original tuple is: ('Python', 'Tuples')
New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python',
'Tuples')
Tuple Methods
a. Count()
b. Index()
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.
O/P
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday',
'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
O/p
printing the original set ...
{'February', 'June', 'April', 'May', 'January', 'March'}
O/p
dict['Name']: Zara
dict['Age']: 7
Updating a Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
O/p
dict['Age']: 8
dict['School']: DPS School
O/p
<class 'dict'>
printing Employee data ....
Name : David
Age : 30
Salary : 55000
Company : GOOGLE
O/p
Empty Dictionary:
{}
Example2
O/p
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'GOOGLE'}
Enter the details of the new employee....
Name: Rahul
Age: 28
Salary: 36000
Company: Microsoft
printing the new data
{'Name': 'Rahul', 'Age': 28, 'salary': 36000, 'Company': 'Microsoft'}
O/P
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'GOOGLE'}
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
PYTHON NOTES 26
O/P
{1: 'JavaTpoint', 3: 'Website'}
Iterating Dictionary
Example1
1. # for loop to print all the keys of a dictionary
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
3. for x in Employee:
4. print(x)
O/P
Name
Age
salary
Company
Example2
1. #for loop to print all the values of the dictionary
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"} for x in Emplo
yee:
3. print(Employee[x])
O/P
John
29
25000
GOOGLE
O/P
False
1. 4. dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}
2. sorted(dict)
O/P
[1,5,7,8]
o/p
{}
1. 6. # dictionary methods
2. dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # copy() method
4. dict_demo = dict.copy()
5. print(dict_demo)
O/p
{1: 'Microsoft', 2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: {1:
'Microsoft', 2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
O/p
{2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
O/p
dict_keys([1, 2, 3, 4, 5])
o/p
dict_items([(1, 'Microsoft'), (2, 'Google'), (3, 'Facebook'), (4,
'Amazon'), (5, 'Flipkart')])
User-defined and built-in functions are the two main categories of functions in Python.
It helps maintain the programme concise, unique, and well-structured.
o By including functions, we can prevent repeating the same code block repeatedly in a program.
o Python functions, once defined, can be called many times and from anywhere in a program.
o If our Python program is large, it can be separated into numerous functions which is simple to
track.
PYTHON NOTES 29
o The key accomplishment of Python functions is we can return as many outputs as we want with
different arguments.
Syntax:
1. # An example Python Function
2. def function_name( parameters ):
3. # code block
Rules
Example
Output:
2. # Defining a function
3. def a_function( string ):
4. "This prints the value of length of string"
5. return len(string)
6.
7. # Calling the function we defined
8. print( "Length of the string Functions is: ", a_function( "Functions" ) )
9. print( "Length of the string Python is: ", a_function( "Python" ) )
Output:
Output
Squares of the list are: [289, 2704, 64]
Output:
Output:
Without using keyword
number 1 is: 50
number 2 is: 30
PYTHON NOTES 32
Output:
We can use special characters in Python functions to pass as many arguments as we want in a
function. There are two types of characters that we can use for this purpose:
# defining a function
def function( **kargs_list ):
ans = []
for key, value in kargs_list.items():
ans.append([key, value])
return ans
# Paasing kwargs arguments
object = function(First = "Python", Second = "Functions", Third = "Tutorial")
print(object)
Output:
7. print( square( 52 ) )
8. # Defining a function without return statement
9. def square( num ):
10. num**2
11. # Calling function and passing arguments.
12. print( "Without return statement" )
13. print( square( 52 ) )
Output:
1. x = 10
2. y = bin(x)
3. print (y)
0b1010
Bytes()
1. string = "Hello World."
2. array = bytes(string, 'utf-8')
3. print(array)
Compile()
1. # compile string source to code
2. code_str = 'x=5\ny=10\nprint("sum =",x+y)'
3. code = compile(code_str, 'sum.py', 'exec')
4. print(type(code))
5. exec(code)
6. exec(x)
<class 'code'>
sum = 15
exec()
1. x = 8
2. exec('print(x==8)')
3. exec('print(x+4)')
True
12
Sum()
1. s = sum([1, 2,4 ])
2. print(s)
3.
4. s = sum([1, 2, 4], 10)
5. print(s)
7
17
Bytearray()
PYTHON NOTES 36
eval()
1. x = 8
2. print(eval('x + 1'))
Float()
1. # for integers
2. print(float(9))
3. # for floats
4. print(float(8.19))
9.0
8.19
Format()
1. # d, f and b are a type
2. # integer
3. print(format(123, "d"))
4. # float arguments
5. print(format(123.4567898, "f"))
6. # binary format
7. print(format(12, "b"))
123
123.456790
1100
Getattr()
1. class Details:
2. age = 22
3. name = "Phill"
4. details = Details()
PYTHON NOTES 37
Globals()
1. age = 22
2. globals()['age'] = 22
3. print('The age is:', age)
Open()
1. # opens python.text file of the current directory
2. f = open("python.txt")
3. # specifying full path
4. f = open("C:/Python33/README.txt")
delattr()
1. class Student:
2. id = 101
3. name = "Pranshu"
4. email = "pranshu@abc.com"
5. # Declaring function
6. def getinfo(self):
7. print(self.id, self.name, self.email)
8. s = Student()
9. s.getinfo()
delattr(Student,'course') # Removing attribute which is not available
s.getinfo() # error: throws an error
Divmod()
1. # Python divmod() function example
2. # Calling function
3. result = divmod(10,2)
4. # Displaying result
5. print(result)
PYTHON NOTES 38
(5, 0)
Enumerate function()
1. # Calling function
2. result = enumerate([1,2,3])
3. # Displaying result
4. print(result)
5. print(list(result))
Filter()
1. # Python filter() function example
2. def filterdata(x):
3. if x>5:
4. return x
5. # Calling function
6. result = filter(filterdata,(1,2,6))
7. # Displaying result
8. print(list(result))
[6]
Packing - As its name suggests, it wraps all the arguments into a single variable, and this
function call gets into a tuple called args. We can use any other name in place of args.
Unpacking - Unpacking is the term which refers to an operation list or tuple assigned to a
single variable.
Packing
The * operator is the tuple (or iterables) unpacking operator. It allows packing multiple values into a
single variable. We pack a tuple of values into a single variable using the * operators in the following
example.
1. a, b, *c= 1, 2, 'x', 'y', 'z'
PYTHON NOTES 39
2. print(a)
3. print(b)
4. print(c)
1
2
['x', 'y', 'z']
Example2
1. *a, b, c = 1, 2, 3
2. print(a)
3. print(b)
4. print(c)
[1]
2
3
unpacking
1. (a, b, c, d, e, f) = (1, 2, 3, 4, 5, 6)
2. print(a)
3. print(b)
4. print(c)
5. print(d)
6. print(e)
7. print(f)
The zip() function returns a zip object, which is an iterator of tuples where the first
item in each passed iterator is paired together, and then the second item in each
passed iterator are paired together etc.
If the passed iterators have different lengths, the iterator with the least items
decides the length of the new iterator.
x = zip(a, b)
print(tuple(x))
Output
frozenset Object is : frozenset({'Geeks', 'for'})
def permutation(lst):
l.append([m] + p)
return l
Output:
['1', '2', '3']
['1', '3', '2']
['2', '1', '3']
['2', '3', '1']
['3', '1', '2']
['3', '2', '1']
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except:
print ("An error occurred")
Example2
# Program to handle multiple errors with one
# except statement
# Python 3
def fun(a):
if a < 4:
try:
fun(3)
fun(5)
O/p
ZeroDivisionError Occurred and Handled
The arguments that are given after the name of the program in the command line shell of
the operating system are known as Command Line Arguments. Python provides various
ways of dealing with these types of arguments. The three most common are:
Using sys.argv
Using getopt module
Using argparse module
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:
It is a list of command line arguments.
len(sys.argv) provides the number of command line arguments.
sys.argv[0] is the name of the current Python script.
Example: Let’s suppose there is a Python script for adding two numbers and the
numbers are passed as 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)
PYTHON NOTES 46
cars.sort(reverse=True)
print(cars)
o/p
['Volvo', 'Ford', 'BMW']
import collections
print('Keys = {}'.format(list(res.keys())))
print('Values = {}'.format(list(res.values())))
print()
elements:
day1 = Mon
day3 = Wed
day2 = Tue
Output
True
False