Python Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Python Programming Language:

Python: Python is a general purpose, highlevel, interpreted ,object oriented, dynamic typed programming language.
Guido Van Rossum developed Python Programming language in the year of 1989 at National Research Institute Netherland.
th
The First version was released in 20 feb 1991.
The Complete Monties Python Circus which was brodcasted in BBc from 1964 to 1974 was the famous an favorate show of guido
from which he took Python Word.

Application Areas Of Python:


The Most common application are:
I) Devloping Desktop Application
II) Devloping Web Application
III) Database application
IV) Network Programming
V) Devloping GAmes
VI) Data Analysis Application
VII) Machine Learning
VIII) Artificial Intellegence Application
IX) Robotics Application

Features of Python:
I) Simple & Easy to Learn: Python is a simple programming language, when we read python program we can feel like reading
English statements.
II) Freeware and Open source: We can use Python Software without any liscense and it is freeware.
III) High Level Programming Language: It is a programmer friendly language. Being a programmer we are not required to
concentrate low level activities like memory management and security.
IV) Platform Independent: Once we write a python program it can run on any platform without rewriting once
again.PVM(Python Virtual Machine) is responsible to convert into machine understandable code.
V) ***Dynamically Typed:In Python there is no need to define type of data .
VI) Intrepreted Programming: The code which we type in this language will be executed line by line.
VII) Both Procedure(function) & Object Oriented Programming language: it support procedure oriented language like C,
Pascal,etc. It support Object Oriented P language like C++.
VIII) Extensive Library: Python has a reach inbuilt libraries.
IX) Embedded programming language: We can use Python program in any other language program.

Limitations Of Python Programming Language:


1) Not used of mobile application.
2) Python is a slow programming language as compared to java because of interpreter.

1) print(‘--’): Print is a function which is used to print output on screen.


Ex

2) Variables: Variables are the container or the memory location which is used to store values or data. E.g a=10, b=20, s=’hello’.

3) Rules For Define Variable:


I) Variables should not start with digits.
II) Variables are case sensitive.
III) Variable should start with alphabet symbol or ‘_’.
IV) We cannot use keywords or reserve words as a variables.

4) Keywords: Keywords are the reserved words which have special meaning in python. There are 35 keywords in python given
below:

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

5) Datatypes: Datatype represent the type of data present inside a variable. In python we are not required to specify the type
of date based on value provided, the type will be assigned automatically. Python contain following inbuilt data type:
Syntax:
Import keyword
print(keyword.kwlist)
I) Int
II) Float
III) Complex
IV) Bool
V) Str
VI) Byte
VII) Range
VIII) List
IX) Tuple
X) Dictionary
XI) Set
XII) Frozenset
XIII) None
XIV) bytearray

I) Int: We can use int data type to represent whole number.

II) Float: We can use float data type to represent floating point values or decimal values. E.g: f=10.5. We can also represent
floating ponit values by using exponential form. E.g. f=1.2e3.

III) Complex: Complex in the form of a+bj form where a= real number and bj= imaginary number.

IV) Bool: We can use this data type to represent boolean values. The only allowed values for this data type are true and false.
Internally python represent true as a one and false as a zero.

V) Byte: Byte data type are used to store integer numbers in the range of 0 to 255 character.

6) Comments: Comments are unexecutable part of program. There are two types of comments in python:
a) Single line comment(#)
b) Multiline comment(#)
i. Docstring(‘’’ ‘’’, “”” “””)

7) Type Casting:
a) int(): It is used to represent convert all datatypes into whole number.
Ex: a=10, print(int(a))
Note: We connot convert complex data type into int
If we want to convert string data type into int compulsory string should contain only intrgral value.

b) float(): It is used to represent convert all datatypes into float.


Ex: a=10, print(float(a))
Note: We connot convert complex data type into float.

c) complex(): We can convert other data type into complex. We can use this function to convert x*complex number with
real part x and imigenary part ‘0’.
Ex: x=10, print(complex(X))

d) bool(): If x is int data type then zero is false and non zero is true.
Ex: X=10, print(bool(X) #true.
If x is float if float number value is zero then result is false otherwise true.
If x is complex data type if both imigenary and real number value is zero then result is false.

e) id(): It is used to return memory address.

f) String: String is a sequence of character which enclosed in single quote(‘ ‘) or double quote(“ “) sequence of
character.
i. Accessing Element from string:
1. Indexing:
a) Positive Indexing:
s='itvedant'

print(type(s))

print(s[0])#i
print(s[1])#t
print(s[2])#v
print(s[3])#e
print(s[4])#d
print(s[5])#a
print(s[6])#n
print(s[7])#t

b) Negative Indexing:

#Negative Indexing
print(s[-1])#t
print(s[-2])#n
print(s[-3])#a
print(s[-4])#d
print(s[-5])#e
print(s[-6])#v
print(s[-7])#t
print(s[-8])#i

2. Slicing: Accessing parts of string.


#positive slicing
print(s[0:8:1])#itvedan
print(s[0:7:1])#itvedan
print(s[0:7:2])#ivdn
print(s[0:])#itvedant
print(s[4:8])#dant

#negativ slicing

print(s[-8:])#itvedant
3. Length function: It is used to find length of string
s="python"
print(len(s))

for i in s:
print(i)

for i in range(len(s)):
print(i)

for i in range(len(s)):
print(s[i])
4. Mathematical operations on String:
1. Concatenation: Addition of strings.
Rule: To use + operator for string cumpulsory both argument
should be str type.
2. Multiplication/repetation : repetation of string.
To use * operator compulsory one aurgement should be in string
and other should be int.
5. Using for loop
g) Find Function: Find function returns index of first occurrence of the given sub string. If it is not available then we will
get -1.
Syntax:
s=”python”
s.find(substr)

h) Index Function: Index function is same as find function but the difference is that if the given substr is not available it
will give value error

i) Count Function: Count() function find the number of occurrence of substr present in given string.
s.count(substr,begin,end.
print(s.count("e"))

j) Replace Function: It is wsed to replace every occurrence of old string will be replaced with new string.
Syntax: S.replace(oldstr, newstr)

k) Split Function: Split function is used to split give string according to specified seperator by using split function, Thee
default seperator is space. The return type of split method is list.
Syntax: s.split( seperator)
l) Join Function: We can join a group of string with respect to given seperator.
Syntax: ‘seperator’.join(stringname)

Changing Case of String:


m) upper(): To convert all characters to upper case.
n) lower(): To convert all characters to lower case.
o) swapcase(): converts all lower case character to upper and all upper case character to lower case.
p) title(): To convert all character to title case . I.e. first character in every should be upper.
q) capitalize(): Only first character will be converted into upper case and all remaining characters can be converted to
lower case.

Checking Starting and Ending Part of String:


r) startswith(): s.startswith(substr)
s) Endswith(): s.endswith(substr)

To check type of character present in String:


t) isalnum():It returns true if all character are alphanumeric.
u) Isdigit:It returns true if all character are digtit only(0-9).
v) Isalfa: It returns true if string are alphabet only(a-z, A-Z).
w) Istitle: It returns true if all character are in title format.
x) Islower: It returns true if all character are in lowercase.
y) Isupper:It returns true if all character are in uppercase.
z) Isspace: It returns true if string contain onlt space.

In python if an new variable is required then pvm wont create object immediately first it will check is any object available
with the required content or not if available then existing object will be reused, if it is not available new objest will be
created.
The advantages of this approach is memory utilization and performance will increase.

Operators in Python:
Operators are special symbol which is used to perform specific operation operant.

Types of Operators:
I) Arithmatic Operator: It is the type of operators which is used to perform arithematic operations.
a) Addition(+)
b) Substraction(-)
c) Multiplication(*)
d) Division(/)
e) Floor division(//)
f) Modulo(%)
g) Exponential(**)

II) Comaprision/Relational Operator:


a) >,<,>=,<=
b) Equlity operator(==, !=)

III) Logical Operator:


a) and operator: If both condition are true then the result will be true.
b) or operator: If atleast one condition is true then the result will be true.
c) not operator

IV) Bitwise Operator:


a) Bitwise and (&) operator: If both bit are one then result will be one otherwise result will be zero.
b) Bitwise or(|) operator:If atleast one bit is one then result will be one otherwise zero.
c) Bitwise xor(^) operator: If both bits are different then result is one otherwise zero.
d) Bitwise left shift(<<) operator: after shifting the empty cell we have to fill end cells with zero.
e) Bitwise Right Shift(>>) operator: after shifting to right we have to fill zero for positive and one for negative.
f) Bitwise Compliment(~) operator:

V) Assignment Operator: Assignment operator are used to assign value to the variable.
EX: +=, -=, /=, *=, //=, **=, %=

a+=1 -> a=a+1


a-=1 -> a=a-1

VI) Special Operator:


a) Menbership Operator: IT IS USED TO CHECK given object is present in collection or string.
1. In:
2. Not in:
b) Identity Operator: We can use identity operator for address comparision.
1. is operator: It returns true if both variables are pointing to same object.
2. is operator: It returns true if both variables are not pointing same object.
VII) Input function: It is used to take input from user
Ex:
num1=input('Enter Number:')
num2=input('Enter Number2:')

print(num1)
print(num2)

VIII) Print function: Used to display output.


Ex:
print('The value of num1',num1)
>>> The value of num1 5

A) end=’ ‘ :
Ex:
print('hello',end=' ')
print('python',end=' ')
>>>hello python

Conditional statement in Python:

1. IF: If particular condition is true then execute if block.


Syntax:
If condition:
“code to be executed
2. IF ELSE: If condition is true then execute if block, otherwise execute else block.
Syntax:
If condition:
“code to be executed
Else:
“code to be executed

3. IF ELIF ELSE:
Syntax:
If condition:
“code to be executed
Elif
‘code to be executed
Elif
“code to be executed
Else
“code to be executed

Transfer Statement:
I) Break:
II) Continue statement: Skip the current iteration and move to the next iteration.
Ex:
i=1
while i<=200:
i+=1
if i==100:
continue
print(i)

III) Pass: Pass is a null statement in python.Pass is a keyword. Pass is used to define empty block.
Ex:
i)for i in range(11):
Pass

ii)Def hello():
Pass

List Datatype: If you want to represent a group of individual object a s a single entity where insersetion order is reserved and
duplicates are allowed then we should go for list. Duplicate objects are allowed in a list. Heterogeneous objects are allowed. List
is a mutable datatype.
We can define list using square bracket.

Syntax:
List_name=[value1,value2,…..]

Ex:
L=[1,2,3,”a”,”b”,2.0]

 Inbuilt Function in list:


1. List_name.len(): It gives number of element in list
2. List_name.count(): It returns numbe of occurences of specific element in list.
3. List_name.append(): It is used to add a new element at the end of list.
4. List_name.insert(posit,element): It is used to add element at a specific position.
5. List_name1.extend(list_name2):It is used to add all items of one list to another list.
6. List_name.remove(): it is used to remove specific item or element present in a list.if the element present
multiple times the only first occurrence will be removed.
7. List_name.pop(): it is used to remove last element of the list.this is only function which manipulates index value
inside.
8. List_name.reverse(): It is used to reverse order of element of list.
9. List_name.sort(): It is used to sort a list. By default it sorts list in ascending order for number.By default sorting
order for string is alphabetical order.
10. List_name.clear(): It is use to remove all the element from the list.
 Aliasing & cloning:
Aliasing: The process of giving another reference variable to the existing list called as Aliasing.
Ex:
L=[1,2,3,4,5,”hello”]
L1=L
Print(id(L))
Print(id(L1)
The problem in this approach by using one reference variable if we are changing content then those changes will be
reflected to the another reference variable.
Ex:
L1[2]=8
L1.append(5)
print((L))
print((L1))
L1=[1, 2, 8, 4, 5, 'hello', 5]
L=[1, 2, 8, 4, 5, 'hello', 5]
To overcome this problem we use cloning.
Cloning:The process of creating exactly duplicate independent object is called as cloning. We can implement cloning by
using slicing or copy function.
Ex:
Using Slicing:
m=[1,2,3,4,5,6]
m1=m[:]
m1[3]=33
print(m1)
print(m)
m1=[1, 2, 3, 33, 5, 6]
m=[1, 2, 3, 4, 5, 6]

Using copy function

n=[1,2,3,4,5,6]#using copy function


n1=n.copy()
n1[3]=33
print(n1)
print(n)
n1=[1, 2, 3, 33, 5, 6]
n=[1, 2, 3, 4, 5, 6]
 Mathematical operator for list object:
Concatenation:
X=[1,2,3,4]
Y=[5,6,7,8]
Z=x+y
Print(Z)
Z={1,2,3,4,5,6,7,8]

Multiplication:
X=[1,2,3,4]
Z=x*3
Print(Z)
Z={1,2,3,1,2,3,1,2,3]

X2=[1,2,3,4,5,6,7,8,9,10]
Print(6 in X2)

 Nested List: Some times we can take a list inside another list called as nested list.
EX:
Mylist= [10,20,30,[100,200,[1,2,3,]],50]
To access element inside nested list:
print(Mylist)
print(Mylist[3])
print(Mylist[3][2])
print(Mylist[3][2][1])

 List Comprehensions: It is a very easy and compact way of creating list object from any iterable objects.
Syntax:
List=[expression for I in iterable_object if condition]
 min() & max() function: min function returns minimum value from list & max function returns max value from list.

Tuples in Python: Tuple is a ordered collection of hetrogeneous data which are imutable. We can define tuple using round
bracket().

T=(1,2,3,4)
t

When to use Tuple:


If our data is fixed and never change then we should go for tuple, duplicates are allowed in tuple.
Accessing Element in Tuple:
Syntax:
Using Indexing:
Tuple_name[idx value]

Using Slicing:
Tuple_name[starting Idx value: end idx value: steps]

Using loop:
for i in tuple_name:
print(i)

Cancatenation Operation On Tuple:

t1=(1,2,3,4)
t2=(5,6,7,8,9)
t3=t1 + t2
print(t3)

t4=t1*t2
print(t4)

Functions in Tuple:

1. len(tup_name): It is used to calculate length of tuple.


c=(2,4,6,8,10,12)
print(len(c))
2. tuple_name.count(): It is use to get the number of occurrence of element in a tuple.
print(c.count(6))
3. Tuple_name[idx value]: It will return the first occurrence of go=iven element, if mot present it will give value error.
print(c[2])
4. print(sorted(tuple_name)): It is used to sort element of tuple based on natural sorting order.
print(sorted(c)
print(sorted(c,reverse=True))
5. max() & min(): It will return maximum or minimum value of element from tuple.
print(min(c))
print(max(c))
6. Cmp(): Compare Function: It is used to compare element of both tuple. If both tuples are equal then returns 0, If the first
tuple less than second tuple then then returns -1, If the first tuple is grater than second tuple then returns 1.
7. Tuple Packing & Unpacking:
a) Tuple Packing: Creating a tuple by packing a group of variables.
a=10
b=20
c=5
d=25
t=(a,b,c,d)
print(t)
print(type(t))
b) Tuple Unpacking: Unpacking is a reverse of packing.
a,b,c,d=t
print(a,b,c,d)

8. Tuple Comprehension: Tuple Comprehension is not supported by python.

***Dictionary Data type: If you want to represent a group of object as a key : value pair then we should go for dictionary.
Duplicate keys are not allowed in dictionary but value can be duplicate. Hetrogeneous objects are allowed for bath key and
values. Insersion order is not pre reserved. Indexing and slicing is not applicable for dictionary. We can define dictionary using {}
brackets.

You might also like