Professional Documents
Culture Documents
CHIEF PATRON
Shri B L Morodia, Deputy Commissioner, KVS (RO), Jaipur
PATRON
Shri D R Meena, Assistant Commissioner, KVS (RO), Jaipur
CONTENT COORDINATOR
Shri Manoj Kumar Pandey, Principal - KV Itarana Alwar
CONTENT COMPILATION
Shri Sandeep Sharma (PGT CS), KV 1 Kota
Shri Pankaj Singh (PGT CS), KV Bharatpur
Shri Navneet Sadh (PGT CS), KV Churu
CONTENT PREPARATION
ALL PGT CS OF JAIPUR REGION
Python Revision: Part 1
OR
Python Fundamentals Apart from above standard Python. We have
various Python IDEs and Code Editors. Some of
1. What is Python: them are as under:
(i) Anaconda Distribution: free and open-source
Python is a general-purpose, high level distribution of the Python, having various inbuilt
programming language. It was created by libraries and tools like Jupyter Notebook, Spyder
Guido van Rossum, and released in 1991. etc
In order to communicate with a computer (ii) PyCharm (iii) Canopy
system, we need a computer programming (iv) Thonny (v) Visual Studio Code
language. This language may be C, C++, Java, (vi) Eclipse + PyDev (vii) Sublime Text
Python or any other computer language. (viii) Atom (ix) GNU Emacs
Here we will discuss Python. (x) Vim (xi) Spyder and many more . .
Python is inspired by two languages – (i)
ABC language which was an optional 5. Python Interpreter - Interactive And Script
language of BASIC language. (ii) Modula-3 Mode:
We can work in Python in Two Ways:
2. Why Python: (i) Interactive Mode: it works like a command
interpreter as shell prompt works in DOS
Platform Independent (Cross-Platform) Prompt or Linux. On each (>>>) symbol we
Free and Open Source can execute one by one command.
Simple syntax similar to the English (ii) Script Mode: it used to execute the multiple
language. instruction (complete program) at once.
Fewer lines than some other programming
languages 6. Python Character Set:
Interpreted Language. Character Set is a group of letters or signs which
Python can be treated in a procedural way, are specific to a language. Character set includes
an object-orientated way. (OOL and POL.) letter, sign, number and symbol.
break Statement
The jump- break statement enables to skip over a
part of code that used in loop even if the loop
condition remains true. It terminates to that loop
These operators are mainly used along with if 2. Example of allowed double quotes with escape
condition to compare two strings where the sequence operator:
decision is to be taken based on string comparison. Code:
string = "Hello world I am from \"India\""
String formatting operator is used to format a (A) String Traversal Using for Loop:
string as per requirement. To insert another type >>> str1 = 'Hello World!'
of variable along with string, the “%” operator is >>> for ch in str1:
used along with python string. “%” is prefixed to print(ch,end = '')
another character indicating the type of value we Hello World! #output of for loop
want to insert along with the python string. Please In the above code, the loop starts from the first
refer to the below table for some of the commonly character of the string str1 and automatically ends
used different string formatting specifiers: when the last character is accessed.
Code:
name = "india" (B) String Traversal Using while Loop:
age = 19 >>> str1 = 'Hello World!'
marks = 20.56 >>> index = 0
string1 = 'Hey %s' %(name) #len(): a function to get length of string
print(string1) >>> while index < len(str1):
string2 = 'my age is %d' % (age) print(str1[index],end = '')
print(string2) index += 1
string3= 'Hey %s, my age is %d' % (name, age) Hello World! #output of while loop
print(string3) Here while loop runs till the condition index <
string3= 'Hey %s, my subject mark is %f' % (name, len(str) is True, where index varies from 0 to
marks) len(str1) -1
print(string)
LIST Output
Definition: Enter a set of numbers 4,7,5,6,9,2
A List is a collection of comma separated Tuple is= (4,7,5,6,9,2)
values within a square bracket. Items in a list need List is=[4,7,5,6,9,2]
not to be the same.
List Indexing
Features of list
• A List is used to store sequence of values / Here,
items. List1 = [12, 3, 43, 23, 33, 65]
• All Elements of a list are enclosed in [ ]
square bracket.
• Items / values are separated by comma.
• Lists are mutable (changeable) in python.
print(List1[2:]) ['I', 'T', ' ', 'J', 'A', 'I', 'N'] ListD[2] # 56
ListD[2] = 1000 # 56
print(List1[:6]) ['A', 'M', 'I', 'T', ' ', 'J']
ListD[2] # 1000
print(List1[0:4]) ['A', 'M', 'I', 'T'] ListD # [36, 46, 1000, 66, 76]
print(List1[3:6]) ['T', ' ', 'J'] ListD[2:3]= 400,500 # [36, 46, 400, 500, 66, 76]
DELETION OF ELEMENTS FROM LIST
print(List1[-2:-5]) []
Using del command O/P
print(List1[-5:-2]) [' ', 'J', 'A'] List1=[44,55,66,77,88]
del List1[2]
print(List1[1:7:2]) ['M', 'T', 'J']
print(List1) [44,55,77,88]
del List1[1:3]
print(List1) [44,88]
E.g. L1=[23,12,43,23,5,34]
L2=[‘K’, ‘V’, ‘S’]
1 index(item) L1.index(43) 2
To display index of an item
4 len(List) len(L1) 6
Returns length of list
8 max(list) max(L1) 43
Returns maximum value
9 min(list) min(L1) 5
Returns minimum value
Reference Videos:-
List (Part-1) https://youtu.be/J8NQuV4CEfw
List (Part-2) https://youtu.be/pheM8nHPNG4
List (Part-3) https://youtu.be/GYptLReCqaw
# KeyError
print(my_dict['address'])
Output: -
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
Changing and Adding Dictionary # Changing and adding Dictionary Elements
elements my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
print(my_dict)
Output: -
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}
Output: -
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
len() – dict={'Name':'Aman','Age':37}
Finding number of items in print("Length: - ", len(dict))
dictionary OUTPUT
Length:- 2
keys() - x=dict(name=“Aman",age=37,country=“India")
returns all the available keys print(x.keys())
OUTPUT
dict_keys(['country', 'age', 'name'])
items()- x=dict(name="Aman",age=37,country="India")
return the list with all dictionary print(x.items())
keys with values. OUTPUT-
dict_items([('country','India'),('age',37),('name','Aman')])
copy()- x=dict(name="Aman",age=37,country="India")
returns a shallow copy of the y=x.copy()
dictionary. print(y)
OUTPUT->{'country':'India','age':37,'name':'Aman'}
Output -
True
True
False
4 Which of the following will delete key-value pair for key=’red’ form a dictionary D1
i. Delete D1(“red”) ii. del. D1(“red”) iii. del D1[“red”] iv. del D1
Files are collection of bytes stored on storage Operations related to Text files
devices such as hard-disks. Files help in
storing information permanently on a I. File Opening: Files can be opened in
computer. Data files are files that store data python by using the open( ) method as
pertaining to a specific application. Data files follows:
can be stored in following ways:
<file_obj>=open(‘<file_path>’,’access_mode’)
· Text files: These files store information in the
form of a stream of ASCII or UNICODE Here <file_obj> is the file handle which
characters. Each line is terminated by an EOL provides the access to the physical file stored
character. on a computer. The file object is also called the
file pointer. It accesses the contents of the file
· CSV (Comma Separated Values) files: These in a sequential manner. All the operations can
files use a specific character to separate the be performed on the file only through the file
values. pointer. The open( ) method accepts one
required argument which is the path of the file
· Binary files: These files store information in to opened. The second argument
the form of a stream of bytes. No EOL ‘access_mode’ is optional and defines the
character is used and binary files hold operations that can be performed on the file
information in the same format in which it is once it is opened. The default access mode is
held in the memory. ‘read mode’.
Absolute and Relative Paths Note: While specifying the path of the file, one
must either use ‘\’ to escape all the special
Path of a file is a sequence of the directories to characters in the path or make it a raw string
access that file on a computer. by adding ‘r’ in front of the path string.
Different access modes are described in Table
Absolute Path is the full path starting from the
1. For example, in order to open a text file
root directory to locate a particular file in a
named ‘myfile.txt’, the following syntax will be
computer system. Example of an absolute
used:
path is:
f = open(r’D:\MyFolder\myfile.txt’, ‘r’)
‘E:\ClassXII\SectionA\test.py’
‘.\test.py’
Delete Folder
To delete an entire folder, use the os.rmdir()
method:
import os
os.rmdir("myfolder")
Note: Only empty folders can be removed.
writer( ) Object Methods – To access each row, we have to iterate over this
· w_obj . writerow( <Sequence> ) : Object.
Write a Single Line for i in r_obj:
· w_obj . writerows ( <Nested Sequence> ) : print(i)
Write Multiple Lines
Example:-
Example:- import csv
# writerow() f=open("myfile.csv",'r')
import csv r_obj = csv.reader(f)
row=['Nikhil', 'CEO', '2', '9.0'] for data in r_obj:
f=open("myfile.csv", 'w') print(data)
w_obj = csv.writer(f) f.close()
w_obj.writerow(row)
f.close() If we consider the sample.csv file given above in
the CSV file structure the output of the above
code will be:
# writerows() ## OUTPUT
import csv
rows = [['Nikhil','CEO','2','9.0'], ['Name', 'DOB', 'City']
['Sanchit','CEO','2','9.1']] ['Ram', '12-Jul-2001', 'Delhi']
f=open("myfile.csv",'w') ['Mohan', '23-Jan-2005', 'Delhi']
w_obj = csv.writer(f) ['Suraj', '17-Dec-2002', 'Kolkata']
w_obj.writerows(rows)
f.close()