Python Complete Notes
Python Complete Notes
PYTHON CYCLE:
What is Python?
Python is a popular programming language. It was created by Guido
van Rossum, and released in 1991.
It is used for:
Good to know
The most recent major version of Python is Python 3, which we
shall be using in this tutorial. However, Python 2, although not
being updated with anything other than security updates, is still
quite popular.
In this tutorial Python will be written in a text editor. It is
possible to write Python in an Integrated Development
Environment, such as Thonny, Pycharm, Netbeans or Eclipse
which are particularly useful when managing larger collections
of Python files.
Example
if 5 > 2:
print("Five is greater than two!")
Example
The number of spaces is up to you as a programmer, but it has to be
at least one.
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Python Variables
In Python variables are created the moment you assign a value to it:
Example
Variables in Python:
x = 5
y = "Hello, World!"
ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 4
Python has no command for declaring a variable.
Comments
Python has commenting capability for the purpose of in-code
documentation.
Comments start with a #, and Python will render the rest of the line
as a comment:
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Creating Variables
Variables are containers for storing data values.
Example
x = 5
y = "John"
Python Numbers
There are three numeric types in Python:
int
float
complex
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
Python Casting
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example
Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Example
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Example
print("Hello")
print('Hello')
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Python Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
+= 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
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
== Equal x == y
!= Not equal x != y
not Returns true if both variables are not the same x is not y
object
not in Returns True if a sequence with the specified value is not x not in y
present in the object
<< Zero fill left Shift left by pushing zeros in from the right and let the leftm
shift off
UNIT 2
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Indentation
Elif
The elif keyword is pythons way of saying "if the previous conditions
were not true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
The else keyword catches anything which isn't caught by the preceding
conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Python Loops
Python has two primitive loop commands:
while loops
for loops
Example
Print i as long as i is less than 6:
Example
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1
2
3
Example
Continue to the next iteration if i is 3:
Example
Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
With the for loop we can execute a set of statements, once for each
item in a list, tuple, set etc.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
b
a
n
a
n
a
Example
Exit the loop when x is "banana":
Example
Do not print banana:
Example
Using the range() function:
for x in range(6):
print(x)
0…………………………………..5
Example
Using the start parameter:
Example
Print all numbers from 0 to 5, and print a message when the loop
has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Python Functions
Creating a Function
Example
def my_function():
print("Hello from a function")
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function()
Parameters are specified after the function name, inside the parentheses. You can add
as many parameters as you want, just separate them with a comma.
The following example has a function with one parameter (fname). When the function
is called, we pass along a first name, which is used inside the function to print the full
name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
Example
ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 24
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Python Scope
A variable is only available from inside the region it is
created. This is called scope.
Local Scope
A variable created inside a function belongs to the local scope of that
function, and can only be used inside that function.
Example
A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)
myfunc()
Example
The local variable can be accessed from a function within the function:
def myfunc():
x = 300
def myinnerfunc():
myfunc()
Global Scope
A variable created in the main body of the Python code is a global
variable and belongs to the global scope.
Global variables are available from within any scope, global and local.
Example
A variable created outside of a function is global and can be used by
anyone:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Python Strings
String Literals
String literals in python are surrounded by either single quotation marks, or double
quotation marks.
Example
print("Hello")
print('Hello')
Example
a = "Hello"
print(a)
Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
However, Python does not have a character data type, a single character is simply a
string with a length of 1.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
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])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 27
Get the characters from position 5 to position 1, starting the count from the end of the
string:
b = "Hello, World!"
print(b[-5:-2])
String Length
Example
a = "Hello, World!"
print(len(a))
String Concatenation
Example
a = "Hello"
b = "World"
c=a+b
print(c)
Python Classes and Objects
Python Classes/Objects
Create a Class
Example
class MyClass:
x=5
Create Object
Example
p1 = MyClass()
print(p1.x)
Python Lambda
A lambda function can take any number of arguments, but can only have one
expression.
Syntax
Example
A lambda function that adds 10 to the number passed in as an argument, and print the
result:
x = lambda a : a + 10
print(x(5))
Example
A lambda function that multiplies argument a with argument b and print the result:
List
A list is a collection which is ordered and changeable. In Python lists are
written with square brackets.
Example
Create a List:
Example
Print the second item of the list:
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second last item etc.
Example
Print the last item of the list:
Range of Indexes
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 list with the
specified items.
Example
Return the third, fourth, and fifth item:
Example
This example returns the items from index -4 (included) to index -1
(excluded)
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango
"]
print(thislist[-4:-1]
Example
Change the second item:
Example
ER.VIPIN RAWAT DEPARTMENT OF COMPUTER SCIENCE Page 32
Print all items in the list, one by one:
List Length
To determine how many items a list has, use the len() method:
Example
Print the number of items in the list:
Add Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
Remove Item
There are several methods to remove items from a list:
Example
The remove() method removes the specified item:
Example
Join two list:
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
Example
Example
Print the second item in the tuple:
OUTPUT: banana
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item etc.
Example
Print the last item of the tuple:
OUTPUT: cherry
Range of Indexes
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
Return the third, fourth, and fifth item:
OUTPUT:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
Python Sets
Set
A set is a collection which is unordered and unindexed. In Python sets are written
with curly brackets.
Example
Create a Set:
But you can loop through the set items using a for loop, or ask if a specified value
is present in a set, by using the in keyword.
Example
Loop through the set, and print the values:
for x in thisset:
print(x)
OUTPUT:
banana
apple
cherry
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
Example
Add an item to a set, using the add() method:
thisset.add("orange")
print(thisset)
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
thisset.remove("banana")
print(thisset)
You can use the union() method that returns a new set containing all items from
both sets, or the update() method that inserts all the items from one set into
another:
Example
The union() method returns a new set with all items from both sets:
set3 = set1.union(set2)
print(set3)
Python Dictionaries
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
Example
Create and print a dictionary:
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square
brackets:
x = thisdict["model"]
Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
thisdict["year"] = 2018
print(thisdict)
SIEVE OF ERATOSTHENES
The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n
when n is smaller than 10 million or so…
Following is the algorithm to find all the prime numbers less than or equal to a given
integer n by Eratosthenes’ method:
According to the algorithm we will mark all the numbers which are divisible by 2
and are greater than or equal to the square of it.
We move to our next unmarked number 5 and mark all multiples of 5 and are greater
than or equal to the square of it.
We continue this process and our final table will look like below:
So the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47.
# Python program to print all primes smaller than or equal to # n using Sieve of
Eratosthenes
defSieveOfEratosthenes(n):
# Create a boolean array "prime[0..n]" and initialize # all entries it as true. A
value in prime[i] will # finally be false if i is Not a prime, else true. prime =
[Truefori inrange(n+1)]
p =2
while(p *p <=n):
# If prime[p] is not changed, then it is a prime if(prime[p] ==True):
# Update all multiples of p
fori inrange(p *p, n+1, p): prime[i] =False
p +=1
# Print all prime numbers forp in
range(2, n):
ifprime[p]:
printp, #
driver program
if name ==' main ': n =30
print"Following are the prime numbers smaller", print "than or equal to", n
SieveOfEratosthenes(n)
Output:
Following are the prime numbers below 30
2 3 5 7 11 13 17 19 23 29
1)Input Operation
Python provides us with two inbuilt functions to read the input from the keyboard.
raw_input()
input()
raw_input(): This function reads only one line from the standard input and returns it as a
String.
Example:
Output:
input(): The input() function first takes the input from the user and then evaluates the
expression, which means python automatically identifies whether we entered a string or a
number or list.
But in Python 3 the raw_input() function was removed and renamed to input().
Output:
Output Operation
In order to print the output, python provides us with a built-in function called print().
Example:
1 Print(“Hello Python”)
Output:
Hello Python
Output:
Assertion :
Parameter types for a private function (ex. the power has to be an integer in
exponential function)
Corner cases that are hard to occur but possible (depends on the application)
Automated unit testing (will provide an example later). What about exceptions.
If the assertion fails, Python uses ArgumentExpression as the argument for the
AssertionError. AssertionError exceptions can be caught and handled like any other
exception using the try- except statement, but if not handled, they will terminate the
program and produce a traceback.
Exception :
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
Handling an exception
If you have some suspicious code that may raise an exception, you can defend your program
by placing the suspicious code in a try: block. After the try: block, include
an except: statement, followed by a block of code which handles the problem as elegantly as
possible.
Syntax
try:
......................
except ExceptionI:
......................
else:
A single try statement can have multiple except statements. This is useful when the
try block contains statements that may throw different types of exceptions.
After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's protection.
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions. Here is an example related to RuntimeError. Here, a class is created that
is subclassed from RuntimeError.
class Networkerror(RuntimeError):
def init (self, arg):
self.args = arg
So once you defined above class, you can raise the exception as follows −
an except: statement, followed by a block of code which handles the problem as elegantly as
possible.
Syntax
try:
......................
except ExceptionI:
......................
else:
A single try statement can have multiple except statements. This is useful when the
try block contains statements that may throw different types of exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's protection.
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions. Here is an example related to RuntimeError. Here, a class is created that
is subclassed from RuntimeError.
class Networkerror(RuntimeError):
def init (self, arg):
self.args = arg
So once you defined above class, you can raise the exception as follows −
try:
print e.args
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and referenceSimply, a module is a file
consisting of Python code. A module can define functions, classes and variables. A module
can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named aname.py.
Here's an example of a simple module, support.py
You can use any Python source file as a module by executing an import statement in some
other Python source file. The import has the following syntax −
It is also possible to import all names from a module into the current namespace by using the
following import statement −
This provides an easy way to import all the items from a module into the current namespace;
however, this statement should be used sparingly.
It is also possible to import all names from a module into the current namespace by using the
following import statement −
This provides an easy way to import all the items from a module into the current namespace;
however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following
sequences −
If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default path is normally
/usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The sys.path
variable contains the current directory, PYTHONPATH, and the installation- dependent default
Abstract Data type: Abstract Data type (ADT) is a type (or class) for objects whose
behaviour is defined by a set of value and a set of operations.
The definition of ADT only mentions what operations are to be performed but not how these
operations will be implemented. It does not specify how data will be organized in memory
and what algorithms will be used for implementing the operations. It is called “abstract”
because it gives an implementation-independent view. The process of providing only the
essentials and hiding the details is known as abstraction.
Example: Stack
A stack is a lifo (last in first out ) list with the following operation : Push , Pop,
Create(init),Top, IsEmpty, Size . ( Suchb a list is called a signature or thr interface to the
ADT.)
Stack ADT
A Queue is a FIFO(first in first out) list with the following operations: Enqueue
, Dequeue , Size, Font
Definition : In object oriented programming classes and objects are the main features. A class
creates a new data type and objects are instances of a class which follows the definition given
inside the class. Here is a simple form of class definition.
class Student:
Statement-1
Statement-1
....
....
Statement-n
A class definition started with the keyword 'class' followed by the name of the class and a
colon.
The statements within a class definition may be function definitions, data members or other
statements.
When a class definition is entered, a new namespace is created, and used as the local scope.
Creating a Class:
Here we create a simple class using class keyword followed by the class name (Student) which
follows an indented block
stu_name = "Davi
#studentdetails1.p
y class Student:
stu_class = 'V'
stu_roll_no = 12
stu_name = "David"
def messg(self):
Special methods
A collection of special methods, with two leading and trailing underscores in the method
names, offers special syntax in Python programs.
The table below provides an overview of the most important special methods
a. div (self, b) a/
b
a. radd (self, b) b+a
a. rdiv (self, b) b/
a
a. pow (self, p) a**p
a. lt (self, b) a<b
a. gt (self, b) a>b
a. le (self, b) a <= b
a. ge (self, b) a => b
a. eq (self, b) a == b
a. neself, b) a != b
objecta. abs
init (self)(self[, ...]) abs(a)
Called after the instance has been created (by new ()), but before it is returned to
Called by str(object) and the built-in functions format() and print() to compute the
“informal” or nicely printable string representation of an object. The return value must
be a string object.
The default implementation defined by the built-in type object calls object. repr ().
Comparison Methods :
The comparison methods were first introduced in Python 2.1 and they are also called
‘rich comparison methods’ or ‘comparison magic methods’
ne () if eq () was defined.
Arithmetic Method :
a + b : a. add (b)
a - b : a. sub (b)
a*b : a. mul (b)
a/b : a. div (b)
a**b : a. pow (b)
1. Create Object
print(p1.x)
Example
p1.age = 40
Example
del p1.age
Example
del p1
Example
class Person:
pass
Inheritance is the capability of one class to derive or inherit the properties from some
another class. The benefits of inheritance are:
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Any class can be a parent class, so the syntax is the same as creating any other class:
Example
Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
#Use the Person class to create an object, and then execute the printname
method:
x = Person("John", "Doe")
x.printname()
To create a class that inherits the functionality from another class, send the parent
class as a parameter when creating the child class:
Example
Create a class named Student, which will inherit the properties and methods
from the Person class:
class Student(Person):
attributes
behavior
Parrot is an object,
The concept of OOP in Python focuses on creating reusable code. This concept is also
known as DRY (Don't Repeat Yourself).
Penguin is
ready
Penguin
Swim
faster
Run
faster
Fibonacci sequence:
A Fibonacci sequence is a sequence of integers which first two terms are 0 and 1
and all other terms of the sequence are obtained by adding their preceding two
numbers.
1. def recur_fibo(n):
2. if n <= 1:
3. return n
4. else:
5. return(recur_fibo(n-1) + recur_fibo(n-2))
6. # take input from the user
7. nterms = int(input("How many terms? "))
8. # check if the number of terms is valid
9. if nterms <= 0:
10. print("Plese enter a positive integer")
11. else:
12. print("Fibonacci sequence:")
13. for i in range(nterms):
14. print(recur_fibo(i))
output:-0, 1, 1, 2, 3, 5, 8, 13
# Driver code
n=4
TowerOfHanoi(n, \'A\', \'C\', \'B\')
Output:
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
def moveDisk(fp,tp):
print("moving disk from",fp,"to",tp)
moveTower(3,"A","B","C")
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The algorithm
maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the
unsorted subarray is picked and moved to the sorted subarray.
# Python program for implementation of Selection
# Sort
import sys
A = [64, 25, 12, 22, 11]
mergeSort(arr,0,n-1)
print ("\n\nSorted array is")
for i in range(n):
print ("%d" %arr[i]),
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Factorial: Factorial of a number specifies a product of all integers from 1 to that number. It
is defined by the symbol explanation mark (!).
1. def recur_factorial(n):
2. if n == 1:
3. return n
4. else:
5. return n*recur_factorial(n-1)
6. # take input from the user
7. num = int(input("Enter a number: "))
8. # check is the number is negative