Python Programming Langauge
Python Programming Langauge
Features of Python
Process of Programming
Types of Operators
NOTE : Select the text you want to comment and press Ctrl +/ to
comment multiple lines together. ‘#’ is used to comment single line.
For multi line comment use “ “ “ “ “ “
Output:
Enter a number : 14
Input number : 14
TYPES OF ERRORS
1. Syntax error
Arise when python parser is unable to understand a line of
code. Ex – typos(spelling mistake ), incorrect indentation, or
incorrect arguments
2. Logical Error
It occurs when there is fault in logic of problem. They do not
usually cause a program to crash. However, they can cause a
program to produce unexpected result.
KEYWORDS
IDENTIFIERS
Ex : a=10
String Function
5.find() : To find the index of the word in string i.e. it will tell
str.upper()
print(str)
# initializing list
lis1 = [ 3, 4, 1, 4, 5 ]
# initializing tuple
tup1 = (3, 4, 1, 4, 5)
Output:
The list before conversion is : [3, 4, 1, 4, 5]
The tuple before conversion is : (3, 4, 1, 4, 5)
The list after conversion is : {1, 3, 4, 5}
The tuple after conversion is : {1, 3, 4, 5}
Lists
b.reverse()
Tuples
It is also a collection of data sets but you cannot
change(i.e. cannot use remove or append function)
Declaration of Tuples : use parenthesis ( )
Ex : a= (1,5.5 , 6,7, 8, “A”)
They are also called as Immutable(cannot change).
Length of tuple :
Ex : a= (3,1,6,4,8,’A’,65.2)
print(a) -> (3,1,6,4,8,’A’,65.2)
print(len(a)) -> 7
Slicing : if we start from left than indexing starts
from 0 and if we start from right indexing starts from
-1 : [start : end : step] (by default step is 1 )
Ex : a= (3,1,6,4,8,’A’,65.2)
print(a) -> (3,1,6,4,8,’A’,65.2)
print(a[0:3]) -> (3,1,6)
print(a[ :-2]) -> (3,1,6,4,8)
print(a[4:6]) -> (8,’A’)
print(a[0:3:2]) -> (3, 6)
print(a[-2:1:-1]) -> ('A', 8, 4, 6)
print(a[-2:-7:-1]) -> ('A', 8, 4, 6, 1)
DICTIONARIES
To initialize we use curly braces { }
They are mutable
Can use multiple data type
A={“Meena” : “Maggi”} -> always left side term(here
Meena) termed as key and right side(here Maggi ) is
termed as value/element.
Dictionary inside Dictionary example
dic1={"One":"Monday","Two":"Tuesday","Three":
{"A":"Wednesday","B":"Thrusday"},"Four":"Friday"}
print(dic1)
print(dic1["Two"]) # Accessing Element using key
print(dic1["Three"]["A"])
Output
{"One":"Monday","Two":"Tuesday","Three":
{"A":"Wednesday","B":"Thrusday"},"Four":"Friday"}
Tuesday
Wednesday
Adding Element or key to Dictionary
Ex : dic1[“Five”] = “Saturday”
print(dict1)
Output :
{"One":"Monday","Two":"Tuesday","Three":
{"A":"Wednesday","B":"Thrusday"},"Four":"Friday",”
Five”:”Saturday”}
Deleting The element and key (use del() function)
Ex:
del(dic1[“Five”])
print(dic1)
Output :
{"One":"Monday","Two":"Tuesday","Three":
{"A":"Wednesday","B":"Thrusday"},"Four":"Friday"}
for-Loop
Syntax :
for i in range(5) :
Ex : i=0 #not required
for i in range(2,5):
print(i)
Output :
2
3
4
for loop are used when we want to repeat
statements
Accessing Nested list using for loop
list_1 = [["A",2],["B",1],["C",3]]
print(list_1)
for item,chocolates in list_1:
print(item,chocolates)
Output :
[['A', 2], ['B', 1], ['C', 3]]
A2
B1
C3
while – loop
used when we want to print number up to a
particular position
Printing Numbers from 1 to 50 given condition to be
used is variable<50
a=0
while(a<50):
print("Number :",a+1)
a=a+1
Alternate
a=0
while(a<50):
a=a+1
print("Number :",a)
To print numbers from 5 to 30
a=5
while(a<=30 ):
print("Number :",a)
a=a+1
Main function
Syntax : if __main__ == '__main':
To import one file function to another file we use
import
mainfile.py
def addition(a,b):
sum=a+b
print(sum)
addition(2,4)
def multiplication(a,b):
product = a*b
print(product)
multiplication(3,5)
final.py
import mainfile
print(mainfile.addition(9,2))
Output(on running final.py file):
6
15
11
None
! Output is given for all files (mainfile.py and final.py)
but we want output for only final.py
For solving this problem we need to use main
function
mainfile.py
def addition(a,b):
sum=a+b
print(sum)
def multiplication(a,b):
product = a*b
print(product)
if __name__ == ‘__main__’:
addition(2,4)
multiplication(3,5)
#do calling from main function
final.py
import mainfile
print(mainfile.addition(9,2))
Output :
11
None
File Handling
We have a text file from c /d drive or
In particular idle we are using by using file handling
we can read ,write the text file
Modes of file
“r” - open file for reading –default mode
“w” – open file for writing
“x” – creates file if not exists
“a” – add more content to a file
“t” – text mode – default mode
“b” – binary mode
“+” – read and write
one.name = "Riya"
one.standarad = "10"
one.section = "a"
two.name = "Meera"
two.standard = "10"
two.section = "B"
two.subjects =["English","computer","science"]
print(one.name,"\n",two.subjects[0],"\
n",two.subjects)
Output :
Riya
English
['English', 'computer', 'science']
one.name = "a"
one.standard = "11"
one.section = "C"
two.name = "B"
two.standard = "12"
two.section = "D"
def details(self):
print(f"Name of the student is {self.name},
standard is {self.standard} and section is
{self.section}")
one = s("Riya","10","A")
two = s("seema","11","B")
print(one.details())
Output:
Name of the student is Riya, standard is 10 and
section is A
classmethod can be access from any instance(object)
or any class
If we want to make a method that can be accessed by
instance as well as class and the argument which we
pass and we don’t want to take self then we used
classmethod
Example:
class s:
no_of_subjects = 5
def __init__(self,aname,astandard,asection):
self.name = aname
self.standard = astandard
self.section = asection
def details(self):
print(f"Name of the student is {self.name},
standard is {self.standard} and section is
{self.section}")
one = s("Riya","10","A")
two = s("seema","11","B")
s.change_subject(21)
print(one.no_of_subjects)
Output:21
def details(self):
print(f"Name of the student is {self.name},
standard is {self.standard} and section is
{self.section}")
@staticmethod
def ptr_detail(string):
print("My name is "+string)
s.ptr_detail("Nikita Gupta")
one = s("Riya","10","A")
one.ptr_detail("Riya") 3staic members can be
accessed by objects but also without them
Output :
My name is Nikita Gupta
My name is Riya
Inheritance
Single Inheritance : Inheriting a class from a single
class
Example:
class One:
def func1(self):
print("this is the one class")
class Two(One):
def func2(self):
print("this is the two class")
obj=Two()
obj.func1()
obj.func2()
Output:
this is the one class
this is the two class
Multiple Inheritance: Inheriting more than one class
into a class
Example:
class plant:
def type(self):
print("t am a small plant")
def my(self):
print("I am Plant")
def m(self):
print("P")
class flower:
def kind(self):
print("i am a sunflower")
def my(self):
print("I am flower")
def m(self):
print("F")
class Purchaser(plant,flower):
def buy(self):
print("I will buy flower as well as plant")
def my(self):
print("I am Purchaser")
obj = Purchaser()
obj.type()
obj.kind()
obj.buy()
obj.my() # Purchaser actual function will be
called
obj.m() #Purchser inherited function from class
plant is called because it is inherited first
Output:
I am a small plant
i am a sunflower
I will buy flower as well as plant
I am Purchaser
P
Multilevel inheritance:
Example :
class Mother:
exercise = 2
class Daughter(Mother):
badminton = 3
def isbadminton(self):
print(f"She plays badminton {self.badminton}")
riya = Mother()
priya = Daughter()
seema = GrandDaughter()
print(seema.isbadminton())
Tinkter:
https://www.tutorialspoint.com/python/python_gui_programming.
htm#:~:text=Tkinter%20is%20the%20standard%20GUI,to%20the
%20Tk%20GUI%20toolkit.&text=Import%20the%20Tkinter
%20module.
>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
Numpy Library
.ljust(width)
.center(width)
>>> width = 20
>>> print 'HackerRank'.center(width,'-')
-----HackerRank-----
.rjust(width)
>>> width = 20
>>> print 'HackerRank'.rjust(width,'-')
----------HackerRank
Ex:
N, M = map(int, input().split())
for i in range(1, N, 2):
print(str('.|.' * i).center(M, '-'))
print('WELCOME'.center(M, '-'))
for i in range(N-2, -1, -2):
print(str('.|.' * i).center(M, '-'))
QGiven an integer, , print the following values for each integer from to :
1. Decimal
2. Octal
3. Hexadecimal (capitalized)
4. Binary
Function Description
Prints
The four values must be printed on a single line in the order specified above for
the binary value of and the values should be separated by a single space.
Input Format
Constraints
Sample Input
17
Sample Output
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
6 6 6 110
7 7 7 111
8 10 8 1000
9 11 9 1001
10 12 A 1010
11 13 B 1011
12 14 C 1100
13 15 D 1101
14 16 E 1110
15 17 F 1111
16 20 10 10000
17 21 11 10001
def print_formatted(number):
# your code goes here
l1=len(bin(number)[2:])
for i in range(1,number+1):
print(str(i).rjust(l1,' '),end=" ")
print((oct(i)[2:]).rjust(l1,' '),end=" ")
print(((hex(i)[2:]).upper()).rjust(l1,' '),end=" ")
print((bin(i)[2:]).rjust(l1,' '))
if __name__ == '__main__':
Incrementing Character by 1:
temp=’c’
temp=chr(ord(temp)+1)
String to list:
Temp=s.split(“ “)
List to string:
s=” “.join(map(str,temp))
temp=list(s.split())
for i in range(len(temp)):
temp[i] = temp[i].capitalize()
capitalize first letter of each word in list:
temp=list(s.split())
for i in range(len(temp)):
temp[i] = temp[i].title()
Set Operations
symmetric_difference()
The .symmetric_difference() operator returns a set with all the elements that are
.intersection()
The .intersection() operator returns the intersection of a set and the set of
elements in an iterable.
Sometimes, the & operator is used in place of the .intersection() operator, but it
.difference()
The tool .difference() returns a set with all the elements from the set that are not
in an iterable.
Sometimes the - operator is used in place of the .difference() tool, but it only
union(): The .union() operator returns the union of a set and the set of elements
in an iterable.
Itertools.product()
Itertools.permutations(iterable[,r])
generated.
Permutations are printed in a lexicographic sorted order. So, if the input iterable is sorted, the permutation tuples will be
Ex:
from itertools import permutations
>>> print permutations(['1','2','3'])
<itertools.permutations object at 0x02A45210>
>>>
>>> print list(permutations(['1','2','3']))
[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')]
print list(permutations(['1','2','3'],2))
[('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')]
Itertools.combination(iterable,r)
This tool returns the length subsequences of elements from the input iterable.
Combinations are emitted in lexicographic sorted order. So, if the input iterable is
Example:
Itertools.combinations_with_replacement(iterable,r):
This tool returns r length subsequences of elements from the input iterable
emitted in lexicographic sorted order. So, if the input iterable is sorted, the
List1.clear()
List1*=0
del list1=[:]
these three all have same time complexity but list1= [] this has the maximum time
Python allows to create files, read from files, write content to file and append content to existing content
through inbuilt functions!
Method Description
This method is used to open the file for the specified operation. The
open(file_path,operation)
operation can either be r,w,a for read, write and append.
close() This method is used to close a file which is already open.
This method is used to write a string to a file, if file is present. If not,
write()
it creates the file and writes the string into it.
read() This method is used to read all the contents of a file into a string.
try:
flight_file=open("flight.txt","r")
text=flight_file.read()
print(text)
flight_file.write(",Good Morning")
flight_file.close()
except:
print("Error occurred")
if flight_file.closed:
print("File is closed")
else:
print("File is open")
When we want to write a code that will run in all situations, we can put it in a finally block.
Since closing a file is necessary we can do it in the finally block instead of in the try block.