XI Python Basics Notes
XI Python Basics Notes
All objects in Python has its own unique id. Object means any String, Number, List, Class
etc.
The id is the object's memory address, and will be different for each time you run the
program. (except for some object that has a constant unique id, like integers from -5 to
256).
Ex:- x=10
# Use in Lists
list1 = ["aakash", "priya", "abdul"]
print(id(list1[0]))
print(id(list1[2]))
is keyword
This keyword is used to test object identity. The “is keyword” is used to test whether two variables belong to
the same object. The test will return True if the two objects are the same else it will return False even if the
two objects are 100% equal.
Note: The == operator is used to test if two objects are the same.
Syntax: a is b
# Using if statement
if a is b:
statement(s)
Example 1:
Conditional Statements:-
Types of If Statements
1) 2)
If <condition>: If <condition>:
Statements….. Statements…..
……………………. …………………….
else:
Ex: Statements…..
…………………….
if a>b: Ex:
print(“a is greater”)
if a>b:
print(“a is greater”)
else:
print(“b is greater”)
3) Ex:-
if <condition1>: if a>b:
Statements….. print(“a is greater”)
……………………. elif b>a:
elif <condition2>: print(“b is greater”)
else:
Statements…..
print(“both are equal”)
…………………….
elif <condition3>:
Statements…..
…………………….
else:
Statements…..
…………………….
LOOPS:-
for i in range(1,11,2):
print i
for i in range(10,0,-2):
print i
The loop else part thus will not be executed when the
loop is infinite or the loop is prematurely exited due
to break statement.
Nested Loops
When a loop contains another loop in its body, it is
called nested loop.
For Ex:-
for i in range(1,6): i=1
for j in range(1,i+1): while i<=5:
print(“*”,end=’ ’) j=1
print() while j<i:
print('*',end=' ')
output:- j=j+1
* print()
** i=i+1
*** output:-
**** *
***** **
***
****
Document
Ex:-
PSEUDOCODE:-It is an informal way of describing the
steps of a program’s solution without using any strict
programming language syntax.
Ex:-
If students marks is greater than or equal to 33
Display “passed”
else
Display “failed”
DECISION TREES
These are the ways of presenting rules in a hierarchical
and sequential structure where based on the hierarchy
of rules, certain outcomes are predicted.
LISTS FUNCTIONS IN PYTHON
If L1= ['1','2',3,'4',5] L2=[8,’z’]
Accessing List Elements:- L1[0]=’1’…… L1[4]=5
L2[0]=8…… L2[1]=’z’
List Function Example Output
list.append(item)
L1.append(16) ['1', '2', 3, '4', 5, 16]
list.extend(list)
L1.extend(L2) ['1', '2', 3, '4', 5, 8,
'z']
list.insert(pos,elt)
L1.insert(3,’k’) ['1', '2', 3, 'k', '4', 5]
list.remove(value)
L1.remove(3) L1= ['1','2',’4’,5]
del list[index]
Or
del L1[3] L1= ['1','2',3,5]
del list[start:stop] or del L1[1:3] L1=['1', '4', 5]
or
del <list name> or del L1 No list named L1
list.clear()
L1.clear() []-Make list empty
list.pop(index)
OR
L1.pop(2) ['1', '2', '4', 5]
Or Or
List.pop() Deletes last elt. [1,2,3,4]
list.index(value)
L1.index(‘4’) 3-Gives index of specified
elt.
list.sort()
L1=[3,81,12,1] [1, 3, 12, 81]
L1.sort()
list.sort(reverse=True) L1.sort(reverse=True) [81, 12, 3, 1]
list.reverse()
L1.reverse() [ 81, 12, 3,1]
len(list) L1.Len() or len(L1) 5
max(list)
max(L1) 81
min(list)
min(L1) 1
list(seq)
l1=list(input("Ent ['1', '2', '3', '4', '5']
er List Elements"))
if input is 12345
Making copy of List
L1=[1,2,3,4,5] L2=[1,2,3,4,5]
L2=L1 L2 is alias of L1
(Both L2 and L1 shares same
memory location. Any change
in L1will also reflected in L2
and vice versa.)
Making copy of List
(independent)
L2=list(L1) L2=[1,2,3,4,5]
L1.count(value)
L1=[1,2,1,3,1,4] L1.count(1) - 3
L1.count(5) - 0
NESTED LIST
When a list contains another list as a member element.
Ex:-lst=[4,5,6,[1,2],8]
Accessing Nested List Elements:-
lst[0]=4, lst[1]=5,lst[2]=6,
lst[3]=[1,2], lst[3][0]=1, lst[3][1]=2, lst[4]=8
SLICING A LIST/TUPLE
forward indexing 0 1 2 3 4 5 6
Elements(L1) 23 46 12 5 67 8 29
Backward Indexing -7 -6 -5 -4 -3 -2 -1
String Slicing
Same as have done in Lists and Tuples
Traversing a String
It means iterations through elements of a string, one character at
a time.
name=”pawan”name
for i in name:
print(i)
Operators used in Strings
If str=”123” True
True
If str=”comp123” True
Str1.isalpha() If str="comp 123" False
Returns true if all characters in a string
are alphabets and have minimum 1
If str=”comp” True
character otherwise returns False If str=”123” False
If str=”comp123” False
Str1.isdigit() If str="comp 123" False
Returns true if all characters in a string
are digits and have minimum 1 digit
If str=”comp” False
otherwise return False If str=”123” True
If str=”comp123” False
str.islower() If str="comp 123" True
Returns True if all the characters are
lowercase. There should be at least one
If str=”123” False
alphabet else would return False If str="CO123" False
str.isupper() If str="comp 123" False
Returns True if all the characters are False
uppercase. There should be at least
If str=”123”
one alphabet else would return False If str="CO123" True
str.isupper() If str="comp 123" False
Returns True if all the characters are False
white spaces. There should be at least
If str=” ”
one character. If str=”” False
Str1.lower() If str=”Comp” comp
Returns a copy of string converted to comp
lowercase
If str=”COMP”
If str=”comp” comp
Str1.upper() If str=”Comp” COMP
Returns a copy of string converted to COMP
uppercase
If str=”COMP”
If str=”comp” COMP
str.lstrip([chars]) If str=”There”
Returns string with leading
characters(as specified) removed from
str2=” There”
left. If no argument is mention then str.lstrip(‘The’) re
remove whitespaces.
Checks from left…all possible str.lstrip(‘Te’) here
combination of the characters of the
string passed and if found any of it’s
str.lstrip(‘the’) There
combination then remove it from left. str2.lstrip() There
str.rstrip([chars]) If str=”There”
Returns string with leading
characters(as specified) removed from
str2=”There ”
right. If no argument is mention then str.rstrip(‘ere’) Th
remove whitespaces.
Checks from left…all possible str.rstrip(‘Te’) Ther
combination of the characters of the
string passed and if found any of it’s
str.rstrip(‘the’) Ther
combination then remove it from left. str2.rstrip() There
str.rstrip(“er”) Th (Removes all possible
combinatns of er)
str.rstrip(“care”) Th (Removes all possible
combinatns of re)
('I eat', 'bananas', ' all
Str.partition(str2) Ex:- day')
txt="I eat banana all
It always returns a tuple with three elts: day"
1 - everything before the "match" x=txt.partition("banana"
2 - the "match"
3 - everything after the "match"
)
print(x)
Debugging:- It refers to the process of locating the place of error,
cause of error and correcting the code accordingly.
Errors:- Error is a bug in the code which causes irregular output or
stops a program from executing.
Exception:- It is an irregular unexpected situation occurring during
execution on which programmer has no control.
Types of Error:-
Exception,SystemExit,OverflowError,
FloatingPointError,ZeroDivisonError, EOFError,
KeyboardInterrupt, IndexError,IOError, ,IndentationError,
SystemExit, ValueError,TypeError, RuntimeError.
Debugging a program using Spyder IDE
Debugging of Programs using coding
import pdb
i=1
while i<=5:
pdb.set_trace() #Tracing of code starts from here
j=1
while j<i:
print('*',end=' ')
j=j+1
print()
i=i+1
Basic pdb commands
Python Function Types:
Built In Functions(Ex:-len, input())
Functions defined in In Built modules(Ex:- pow(),
sqrt())
User Defined functions
Python Modules
A module in general is independent grouping of code and
data i.e grouping of variables, definitions, statements and
functions which can be reused in other programs and may
also depend upon other modules.
EXAMPLE 1:-
def label(str1):
print("----------------------------------------------")
print(str1)
print("----------------------------------------------")
def RectArea(l,b):
print("Area of Rectangle is:-",l*b)
import ModMain2
m=int(input("enter length of rectangle"))
n=int(input("enter breadth of rectangle"))
ModMain2.RectArea(m,n)
Output:-
DICTIONARY FUNCTIONS
dict= {'Subject': 'Informatics Practices', 'Class': 11}
dict2={22:'RollNo',67:'Marks'}
m=dict2.get(22) To get the value of RollNo
or required dictionary item.
m=dict2[22]
k=len(dict) It is equal to the 2
number of items in the
dictionary.
m=type(dict) If variable is <class 'dict'>
dictionary,then it would
return a dictionary type.
p=dict.copy() Returns a copy of {'Subject': 'Informatics
dictionary dict Practices', 'Class': 11}
q=dict.items() dict_items([('Subject',
Returns a list of 'Informatics Practices'),
dict's(key,value) tuple ('Class', 11)])
pairs
r=dict.keys() Returns list of dictionary dict_keys(['Subject',
dict's keys 'Class'])
s=dict.values() Returns list of dictionary dict_values(['Informatics
dict's values Practices', 11])
Adds dictionary dict2's {'Subject': 'Informatics
dict.update(dict2 key-values pairs to dict Practices', 'Class': 11, 22:
) 'RollNo', 67: 'Marks'}
To delete a dictionary {67: 'Marks'}
del dict2[<key>] element for the specified
del dict2[22] key.
or Or Not found.(As dictionary
del dict2 To delete the whole is deleted).
dictionary.
Delete the particular {67: 'Marks'}
dict2.pop(<Key>) element from the
dict2.pop(22) Dictionary whose key is
mention.
It will deletes all the {}
elements of the Dictionary
dict.clear() and left only empty
Dictionary.
str=kv 1 adampur Splits the string into words Wrd
['kv', '1', 'adampur']
wrd=str.split()
Dictionary:-
It is an unordered collection of items where each item consist of a
key and a value.
Binary to Decimal
For Integer Portion:-
Multiply by 2n and add(Moving from right to left starting with 20)
For Decimal Portion:-
Multiply by 2-n and add(Moving from right to left starting with 2-1)
SoC(System on a Chip)
Major components of a mobile system are integrated on a single chip called SoC.
It includes CPU, GPU, Modem, etc. It consumes less power as compare to other
alternatives.
Display Subsytem
It is responsible for providing display facilities and touch sensitive interface.
Camera Subsystem
It is responsible for providing all image related processings like image capture,
high resolution support and other image enhancements.
Storage:-
The external storage of a Mobile phone is called expandable storage. It is provided
by means of SD Cards. You can store your files in it.
SOFTWARES
It is a set of programs that governs operations of a computer system and makes
the hardware Run.
System Software:- A software that controls the internal operations of a computer and is
necessary to make a computer run is called system software.
Ex:- Operating system, Language processors
Operating System:- It is a system software which acts as an interface between a user and
the computer system.
Ex:- Windows, DoS, Linux, Unix etc.
Language Processors:- These are the system softwares which are used to convert a
source code program into machine code.
a) Assembler:-It converts an assembly language program into machine language. Ex:-
Program written in Assembly language or Low language.
b) Compiler:-It converts a high level language into machine language in one single step.
Ex:- Program written in C++ or VB or Java etc. language.
c) Interpreter:- It converts a high level language into machine language through line by
line compilation. Ex:- Program written in Python language.
Application Software:-
It is a set of programs necessary to carry out operations for a specified application.
a)Packages:-These are the general purpose software used to fulfill general requirements
of many people.For Ex:-MsWord, MsExcel, DBMS, MsPowerpoint.
b)Utilities:-These are the application programs that assist the computer by performing
housekeeping functions like scanning, cleaning virus, backing up disks etc.
For Ex:- Compression tools, Disk defragmentor, Text Editor, Backup utility, Antivirus etc.
c)Business Software:- These are the specially created software applications according to
a particular business environment. These are customized ot tailor made softwares. For
Ex:- Accounting software made for a company.
Software Libraries
It is a predefined and available to use data and programming code in the form of
functions/scripts etc. that can be used in the development of new software programs and
applications. For Ex:- Panda library in python used for Data base applications.
Unicode:-
Unicode provides a unique number for every character, no matter what the platform, no
matter what the program, no matter what the language.
It has been adopted by all modern software providers and now allows data to be
transported through many different platforms, devices and applications without
corruption.
It is a superset of all other character sets and encode majority of known languages. Most
importantly it encodes different characters of different languages with the same
encoding scheme unlike previous encodings in which no single encoding is capable of
representing all languages.
Unicode Encoding Schemes
Unicode represents characters with multiple encoding systems like UTF-8, UTF-16 and
UTF-32.
UTF-8(Unicode Transformation Format)-8
It uses code Unit of 8 bits called an octet. It can use 1 to maximum 6 octets to represents
code points depending on their size. Although it uses 4 octets till date to represent any
character.
How would one know that whether 16 bits or 2 octets are representing single two byte
character or two one byte characters?
1 1 0 1 0
110 in the Leftmost 3 bits of first byte and 10 in the Leftmost 2 bits of second byte
indicate 2 Byte encoding.
Value storage starts from right most bit and left most bits will carry 0 if doesn’t
have any value. For Ex:- to store value 130 (Binary 10000010).We can
1 1 0 0 0 0 1 0 1 0 0 0 0 0 1 0
1 1 1 0 1 0 1 0
1 1 1 1 0 1 0 1 0 1 0
1 1 1 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0
UTF-8 is the most popular encoding scheme and more than 90% websites are using it.
UTF-32
It is a fixed length encoding scheme that uses exactly 4bytes to represent all Unicode
code points. E.g. to store value 36(Binary Code:-00100100)
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0
PROGRAM EXECUTION
This topic explains the process of converting Program code into computer
understandable code i.e machine code.
Source code:- It refers to the original code written in a programming language by the
programmer. Ex:-.cpp file in C++, .py file in python etc.
Machine code:- It refers to the code converted into computer understandable form
that a computer can understand and can directly execute.
Translators or Translation Softwares:- Compiler, Interpreter.
2. Compilation:-
i) Analysis(Front End phase):-It identifies all the tokens in the source code
and creates a symbol table with it.
ii) Synthesis Phase(Back End Phase):-It parses the source code and
generates syntax tree out of it i.e the order of execution of the expression.
These steps are repeated until all the errors (Syntax and Semantics) are
removed from the source code. Once the errors are removed, the compiler
converts the source code into intermediate code which are Assembly
language instructions.
5. Loader:-It loads the .exe file created above into memory for execution.
B. INTERPRETATION PROCESS:-
It translates a single line at a time, makes it executable and runs immediately. It
means that interpreter follows the process of compiler for each line of code and
then moves to process the next line.
It requires less amount of memory then compiler as only a single line of code is
executed at a time. However unlike compilerit is required always in memory to
run the code.
Also, a compiler generates intermediate object code of the whole program
whereas interpreter does not generate any intermediate object code.
Once a compiler compiles the program successfully, it is not required for running
the code again and again(if no changes are made to the code), however
interpreter is required always.
OS as a Resource Manager
As a computer may have multiple processes to run upon, so management of
resources including RAM, secondary memory devices, Input/Output devices etc. is
required so that they can be used efficiently. This work is performed by the
Operating System.
Performance of a CPU
It is measured through “Throughput”which is calculated as
Throughput=No. of Jobs completed/Time Taken
1. PROCESS MANAGEMENT:-
A program have different states. These are:-
Start State:-Initial state of a program when a program is first loaded into the
memory to make it a process.
Waiting State:-If during execution, the has to wait for some resource like waiting
for user input, or waiting for any resource(printer etc.) to be available, then the CPU
takes up the next process and the current process state becomes waiting state.
3. MEMORY MANAGEMENT
The OS needs to check how much memory is to be allocated to processes and
how it is to be allocated. Keep track of and keep updating freed or unallocated
memory etc.
The memory manager part of OS allocate memory to different processes using
different techniques such as:-
a) Single memory allocation:-In it the available free memory is allocated to
single application at a time.
b) Partitioned Allocation:-In this technique, primary memory is divided into
contiguous are of memory called partitions. A running application is allocated
one or more partitions depending upon its requirement.
c) Paged Memory management:-In it, primary memory is divided into fixed size
units called pages. A running application is allocated one or more pages
depending upon its requirement.
d) Segment memory management:-In it, memory is divided into logical units
called segment. Segments may not be contiguous in physical memory but
logically different chunks of memory may belong to one segment.A running
application is allocated some segments depending upon its requirement.
4. I/O MANAGEMENT
Whenever a process requires some I/O, the OS sends I/O request to the physical
device and passes the received response back to the process.
PARALLEL COMPUTING
It refers to the simultaneous working of multiple processors to solve a
computational problem.
A parallel computing may be achieved through :-
a) A single computer with multiple processors
b) Multiple computers connected by a network.
Advantages of parallel computing
1. It saves time and cost too.
2. Provides efficient use of hardware.
3. May utilize remotely available resources.
4. It may solve large and complex problems easily.
Non relational databases are the unstructured databases where arrangements of the records in the
database can be in any undefined manner.These are termed as NoSQL databases.
Non relation databases are more suitable to manage huge or big data for business organizations.One such
non-relational DBMS is MongoDB.
MongoDB
JSON(JavaScript Object Notation) :-It is an open, human and machine readable standard that facilitates
data interchange on the web.
MongoDB uses JSON documents in order to store documents like table uses rows to store records in
RDBMS.
Features of MongoDB
Document Oriented storage:- Data is stored in the form of JSON style documents.
High Speed & Performance:- It is so because it uses internal memory for storing the working data set, thus
fast access.
Auto Sharing:-
MongoDB Components:-
Database:-It is a physical container for collections(like tables). A single MongoDB server has multiple
databases.
Document:-It is a set of key-value pairs. Documents have dynamic scheme i.e different documents in a
collection may have different set of fields, structure and also common fields in a collection’s documents
may hold different types of data.
RDBMS MongoDB
Database Database
Table Collection
Tuple/Row Document
Column Field
Table Join Embedded Documents
Primary Key Primary Key(Provided by default in
MongoDB)
Database schema
It is the structure that represents the logical view of the entire database.It defines how the data is
organized and how the relation among them are associated. It defines table ,views and integrity constraints
in RDBMS.
Advantages of MongoDB
1. It is schema less, so it is flexible enough as number of fields content and size of the document may
differ from one to another.
2. Unlike SQL, no complex Joins are there.
3. It is very easy to scale.
4. It is easy to use.
5. It uses internal memory for storing working sets;so it accesses data very fast.
6. It is lightweight so occupies less memory.
7. It is much faster than RDBMS.
Some common problems that comes during MongoDB installation on windows 7 32 bit.
Solution Type the following command in the MongoDB path upto bin as
mongod.exe --storageEngine=mmapv1
COMMANDS IN MongoDB
To create database
To Create Table
db.createCollection(‘tablename’) Ex:-db.createCollection(‘student’)
*Note:-Although you need not to create collection explicitly as MongoDB creates collection
automatically when you insert the data using insert or insert many command.
To Insert Record
db.student.insert({“RollNo”:1,”class”:”8A”,”Marks”:90})
db.student.insert({“RollNo”:7,”class”:”11A”,”Marks”:94,”Age”:11})
You can also have different no. of columns in different insert query.For Ex:-
To Display Record
db.student.find():- To list all records of the student table.
Ex:-
To Update Records:-
db.student.update({‘RollNo’:1},{$set:{“CLASS”:”9C”}})
db.student.remove({“class”:”11A”})
Install mongoDB 3.2 and either install complete variant (Path will be C:\Program Files\Server\
3.2\bin\)
or
Select custom variant and you can select easy accessible path C:\MongoDB\
Now go to command prompt by cmd-> now depending upon your python path go to that path
through cd C:\MongoDB\bin\
mongod.exe --storageEngine=mmapv1
Now without closing this window open another cmd window and once again goto MongoDB path as
cd C:\MongoDB\bin\
and type command as cd C:\MongoDB\bin\mongod
and then as cd C:\MongoDB\bin\mongo
you will get prompt as >
and now you can start typing your commands.
STATE:- A state is one of the internal configuration of a hardware/software which is caused by some
external inputs or some internal actions.
Transition:- A Transition is a marked change from one state to another in response to some external
input or actions.
Mutability means that you can store new value at the same memory address i.e
overwriting contents.
For immutable data type you are unable to overwrite contents but instead every
time you assign new value to an immutable data type, it simply refer to a
different memory location.
IMMUTABLE DATA TYPES MUTABLE DATA TYPES
Integers List
Boolean Dictionary
Floating Point Numbers Set
Strings
Tuples
For Ex:- As string is immutable data type, So
If name=”welcome”
Str=”PYTHON”
Forward
0 1 2 3 4 5 6
indexing
P Y T H O N \0
Backwar
d -6 -5 -4 -3 -2 -1 0
indexing
Dictionary In Python
It is an unordered set of comma separated
Key:Value pairs, within { } with the condition
that within a dictionary, no two keys can be
the same.