0% found this document useful (0 votes)
3 views61 pages

Python

pyhton is good language

Uploaded by

gowri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views61 pages

Python

pyhton is good language

Uploaded by

gowri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION OF PYTHON:

 Python is a popular programming language as well as one of the scripting


language.
 Python is a high level language.
 It can be used many more types of applications.
 It works on different platform.
 Python supports pop as well as oops concept.
 It has a simple syntax. It allows developers to write programs with fewer lines
that some other programming language.
 It was a large and broad library which provides a rich set of module and
functions.

HISTORY :
Python was started in the December 1989 by Guido Van Rossum at CWI in
[Link] van Rossum was also reading the published scripts from
“Monty python’s flying circus”, a BBC comedy series from the 1970s.

PYTHON APPLICATION:

 Console Based Applications


 Audio or video Based Applications -> provides multimedia applications
 Web Applications
 Enterprise Applications
 Applications for images.
Organizations using Python :
 Google(Components of Google spider and Search Engine)
 Yahoo(Maps)
 YouTube
 Mozilla
 Microsoft
 Spotify
Ex: Print(“Hello World”)

Keywords:
Keywords in Python are reserved words that can not be used as a variable
name, function name, or any other [Link] number of
keyword 35.
import keyword
print([Link])

Variables:
Variables are containers for storing data values.
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
X=3 #x is int
X=”python” #x is str

Comments:
Comments stars with a #.
Multiline Comment: ”””python”””

Indentation
 Indentation refers to the spaces at the beginning of a code line.
 Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
 Python uses indentation to indicate a block of code.

Ex: if 5 > 2:
print("Five is greater than two")
Many Values to Multiple Variables

Python allows to assign values to multiple variables in one line.

Ex: x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

One Value to Multiple Variables

Assign the same value to multiple variables in one line.

Ex: x = y = z = "Orange"
print(x)
print(y)
print(z)

PYTHON DATA TYPES:

Data types is used to create a memory allocation.

Text Type: str

Numeric Types: int, float, complex


Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType


EXAMPLE OF DATATYPES:

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

x = True bool
x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

x = None NoneType

You are getting data type using type() function.

EX: x=5
y=”python”
print(type(x)) # <class 'int'>
print(type(y)) #<class ‘str’>
PYHTON NUMBERS:

There are three numeric types in Python:

 int
 float
 complex
INT:

Int, or integer, is a whole number, positive or negative, without decimals, of


unlimited length.

EX:
x=1
y = 35656222554887711
z = -3255522
print(type(x)) #<class ‘int’>
print(type(y)) #<class ‘int’>
print(type(z)) #<class ‘int’>

FLOAT:

Float, or "floating point number" is a number, positive or negative, containing


one or more decimals.

EX:

x = 1.10
y = 1.0
z = -35.59
print(type(x)) #<class=’float’>
print(type(z)) #<class=’float’>
COMPLEX:

Complex numbers are written with a "j" as the imaginary part.

EX:
x = 3+5j

y = 5j
z = -5j
print(type(x)) #<class=’complex’>
TYPE CONVERSTION:

You can convert from one type to another with the int(), float(), and complex()
methods.

EX
#convert from int to float:
x = float(1)
#convert from float to int:
y = int(2.8)
#convert from int to complex:
z = complex(1)
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))

NOTE: You cannot convert complex numbers into another number type.
PYTHON STRING:
Strings in python are surrounded by either single quotation marks, or double
quotation marks.

'hello' is the same as "hello".

SLICING STRING:

You can return a range of characters by using the slice syntax.


EX:

b = "Hello, World!"
print(b[2:5]) #llo
print(b[2:]) #llo, World!
print(b[-5:-2]) #orl
Note: The first character has index 0.

MODIFY STRING:
Python has a set of built-in methods that you can use on strings.

EX:

a = "Hello, World!"

print([Link]()) #HELLO,WORLD!
print([Link]()) #hello, world!

a = " Hello, World! "


print([Link]()) #Hello, World!
print([Link]("H", "J")) #Jello, World!

a = "Hello, World!"
b = [Link](",")
print(b) #[‘Hello’ , ‘World’]
STRING CONCATENATION:
To concatenate, or combine, two strings you can use the + operator.

EXAMPLE:

a = "Hello"
b = "World"
c = a + b
print(c)

String Methods:

a="python language"
b=[Link]()
print(b)

a="PYTHON language"
b=[Link]()
print(b)
a="python language"
b=[Link]()
print(b)

a="python language"
b=[Link]()
print(b)

b=[Link](50)
print(b)

a="py is a py in py"
b=[Link]("py")
print(b)
a="python language"
b=[Link]('e')
print(b)

b=[Link]("lang")
print(b)

a=("python","language")
b="*".join(a)
print(b)

a="python language"
b=[Link]("python","java")
print(b)

a=("python language")
b=[Link]()
print(b)

a="python language"
b=[Link]()
print(b)

b=[Link]("p")
print(b)

Output:

Python language
python language
False
True
python language
3
True
7
python*language
java language
['python', 'language']

Python Language
True

STRING FORMAT() FUNCTION:

Combine strings and numbers by using the format() method.


EXAMPLE:

age = 36
txt = "My name is John, and I am {}"
print([Link](age))

ANOTHER EXAMPLE:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print([Link](quantity, itemno, price))

Output:

I want to pay 49.95 dollars for 3 pieces of item 567.

PYTHON USER INPUT:

Python get user input using input() function.

EXAMPLE:

a=int(input(“Enter the value”))


name=input(“Enter your name”)
b=float(input(“Enter the number”))
PYTHON OPERATOR:

Operators are used to perform operations on variables and values.

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

ARITHMETIC OPERATOR:

Arithmetic operators are used with numeric values to perform common


mathematical operations.

OPERATOR OPERATION
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
** Exponentiation
// Floor Division

EXAMPLE:

x=int(input(“Enter the x value”))


y=int(input(“Enter the y value”))
print(x+y)
print(x-y)
print(x*y)
print(x/y)
print(x%y)
print(x//y)
print(x**y)

ASSINGMENT OPERATOR:

Assignment operators are used to assign values to variables.

EXAMPLE:

a=a+10 a+=10

a=a-10 a-=10

a=a*10 a*=10

a=a/10 a/=10

COMPARISION OPERATOR:

Comparison operators are used to compare two values.


OPERATOR OPERATION
== Equal to
!= Not equal
< Less than
<= Less than or equal to
> Greater than
>= Grearer than or equal to
EX:

x=int(input(“Enter x value”))
y=int(input(“Enter y value”))
print(x==y)
print(x!=y)
print(x<y)
print(x<=y)
print(x>y)
print(x>=y)
LOGICAL OPERATOR:
Logical operators are used to check whether an expression is true or false.

OPERATOR EXAMPLE MEANING


and expression1 and True only if both
expression 2 expression1 and
expression2 are true.

or expression1 or expression True if either expression1


2 or expression2 is true
not not expression True if expression is false
and vice versa

EX:

x=int(input(“Enter x value”))
y=int(input(“Enter y value”))
print(x>=y and x>y)

print(x==y or x<y)

print(not(x!=y and x<=y))


IDENTITY OPERATOR:

Identity operators are used to compare the objects, not if they are equal, but
if they are actually the same object, with the same memory location.
OPERATOR DESCREPTION
is Returns True if both variables are the
same object
is not Returns True if both variables are not
the same object

EX:

x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is y) #false
print(x is z) #true
print(x==y) #true
print(x is not y) #true

MEMBER SHIP OPERATOR:

Membership operators are used to test if a sequence is presented in an


object.
OPERATOR DESCRIPTION
in Returns True if a sequence with the
specified value is present in the object.
not in
Returns True if a sequence with the
specified value is not present in the
object.
EX:

x = ["apple", "banana"]
print("banana" in x) #true

print(“pineapple” not in x) #true

BITWISE OPERATOR:

Bitwise operators are used to compare (binary) numbers.

OPERATOR DESCRIPTION
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Shift left
>> Shift right

EX:

x=int(input(“Enter the x value”))


y=int(input(“Enter the y value”))
print(x&y)
print(x|y)
print(x^y)
print(~x)
print(x<<2)
print(x>>3)
CONTROL STATEMENT:

Control statements are statements which control or change the flow of


execution.
 if statement
 if … else statement
 if … elif … else statement
 while loop
 for loop
 else suite
 break statement
 Continue statement
 Pass statement

IF STATEMENT:

This statement is execute the some condition. If the condition is true it


executes a block of code.

EX:

a = int(input(“Enter a value”))
b = int(input(“Enter b value”))
if b > a:
print("b is greater than a")
print(“Hello”)
IF….ELSE STATEMENT:

This statement is check with two conditions. If the condition is true the set of
statement is executed. Otherwise another set of statement is executed.

Syntax:

if(contidion):
statement
else:
statement
EX:

a =int(input(“Enter a value”))
b = int(input(“Enter b value”))
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Exercise:

1.)Write a program to check with odd or even.


2.)Write a program to check with leap year or not.
3.)Write a program to check with positive or negative.
4.)Write a program to check with eligible for vote or not.

IF…ELIF…ELSE STATEMENT:

This statement is execute the more than condition is checked.


Syntax:

if condition:
statements
elif condition:
statements
elif condition:
statements
else:
statements
EX:

a = int(input(“Enter a value”))
b = int(input(“Enter b value”))
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")

Exercise:

1.) Write a program using elif in student mark list.


2.) Write a program using elif in upper case ,lower case,digits and special symbols.
NESTED IF STATEMENT:

You can have if statements inside if statements, this is called nested if


statements.
Syntax:
if condition:
if condition:
statement
else:
statement
else:
if condition:
statement
else:
statement
EXAMPLE:

a=int(input("Enter a value"))
b=int(input("Enter b value"))
c=int(input("Enter c value"))
if a>b:
if a>c:
print("A is big")
else:
print("C is big")
else:
if c>b:
print("C is big")
else:
print("B is big")

USING “and” OPERATOR:


The and keyword is a logical operator, and is used to combine
conditionalstatements.

EX:

a = int(input(“Enter a value”))
b = int(input(“Enter b value”))
c = int(input(“Enter c value”))
if a > b and c > a:
print("Both conditions are True")
else:
print(“Both conditions are false”)

USING “or” OPERATOR:

The or keyword is a logical operator, and is used to combine


conditionalstatements.
EX:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
else:
print(“Both conditions are false”)

USING “not” OPERATOR:

The not keyword is a logical operator, and is used to reverse the result of the
conditional statement.

EX:

a = int(input(“Enter a value”))
b = int(input(“Enter b value”))
if not a > b:
print("a is NOT greater than b")
else:
print(“a is greater than b”)
PASS STATEMENT:

If statements cannot be empty, but if you for some reason have an if


statement with no content, put in the pass statement to avoid getting an error.
EX:

a = 33
b = 200
if b > a:
pass
PYTHON LOOP:

Python has two primitive loop commands:

 while loop
 for loop

WHILE LOOP:

The while loop we can execute a set of statements as long as a condition is


true.
EX:

i=1
while i < 6:
print(i)
i += 1
Exercise
1. write a program using while loop in

12+22+32+................+n2
1+3+5+.............+n
1+5+10+……..+n
2. write a program using while loop in
Sum of digits
Reverse the digits
Armstrong no
Palindrome no
BREAK STATEMENT:

The break statement we can stop the loop even if the while condition is true.
EXAMPLE:

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
CONTINUE STATEMENT:

the continue statement we can skip the current iteration, and continue with
the next.
EXAMPLE:

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
ELSE STATEMENT:

The else statement we can run a block of code once when the condition no
longer is true.
EX:

i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
FOR LOOP:

A for loop is used for iterating over a sequence. the for loop we can execute
a set of statements, once for each item in a list, tuple, set etc.

EX:

fruits = ["apple", "banana", "cherry"]

for x in fruits:
print(x)

ITERATING STRING USING FOR LOOP:

for x in "banana":
print(x)

RANGE FUNCTION:

The range() function returns a sequence of numbers, starting from 0 by


default, and increments by 1 (by default), and ends at a specified number.

EX:

i=1
n=int(input("Enter the number?”))
for i in range(0,10):
print(i,end = ' ')
Ex:
sum=0
for i in range(2,10,2):
sum=sum+i
print(sum)
NESTED FOR LOOP:

A nested loop is a loop inside a [Link] "inner loop" will be executed one
time for each iteration of the "outer loop"

EX:
n = int(input("Enter the number of rows you want to print?"))
i, j=0,0
for i in range(0,n):
print()

for j in range(0,i+1):
print("*",end="")
ELSE STATEMENT:

The else keyword in a for loop specifies a block of code to be executed when
the loop is finished.

EX:

for x in range(6):
print(x)
else:
print("Finally finished!")

BREAK STATEMENT:

The break statement we can stop the loop before it has looped through all the
items.
Ex:

str = "python"
for i in str:
if i == 'o':
break
print(i)
CONTINUE STATEMENT:

The continue statement we can stop the current iteration of the loop, and
continue with the next:

EX:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

PASS STATEMENT:

For loops cannot be empty, but if you for some reason have a for loop with
no content, put in the pass statement to avoid getting an error.

EX:

n=[1,2,3,-4,-5,6,-7,-8,9]
for i in n:
if i>0:
pass
else:
print(i)
PYTHON LIST:

 Lists are used to store multiple items in a single variable. A list


can bedefined as a collection of values or items of different types.
 The items in the list are separated with the comma (,) and enclosed with
thesquare brackets [].
 It allows duplicates.

EXAMPLE:

L1 = ["John", 102, "USA"]


L2 = [1, 2, 3, 4, 5, 6]
L3 = [1, "Ryan"]

print(L1) #[‘John’,102,’USA’]
print(L2) #[1,2,3,4,5,6]
print(L3) #[1,’Ryan’]

Accessing the values using for loop:

list=[10,20,30,40,50]
print(‘using while loop’)
i=0
while i<len(list):
print(list[i])
i+=1
print(‘using for loop’)
for i in list:
print(i)
USING range() FUNCTION:

list = ["apple", "banana", "cherry"]


for i in range(len(list)):
print(list[i])
List indexing and splitting:

The elements of the list can be accessed by using the slice operator [].

UPDATAING LIST VALUES:

List are mutable. It means we can modify the contents of a list.

Ex:

list=list(range(1,5)) #create a list using list() and range()


print(list) #[1,2,3,4]

[Link](9)
print(lst) #[1,2,3,4,9]
list[1]=8
print(lst) #[1,8,3,4,9]

list[1:3]=10,11
print(lst) #[1,10,11,4,9]

[Link](11)
print(lst) #[1,4,9]

PYTHON LIST OPERATION:

Consider a List l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8]

Operator Description Example

Repetition The repetition operator enables the list L1*2 = [1, 2, 3,


elements to be repeated multiple times.
4, 1, 2, 3, 4]

Concatenation It concatenates the list mentioned on l1+l2 = [1, 2, 3,


either side of the operator.
4, 5, 6, 7, 8]

Membership It returns true if a particular item exists print(2 in l1)


in a particular list otherwise false. prints True.

Iteration The for loop is used to iterate over the for i in l1:
list elements. print(i)
Output 1 2 3 4

Length It is used to get the length of the list len(l1) = 4


Adding elements to the list:

Python provides append() function by using which we can add an element


tothe list.

EX:

l =[]
n = int(input("Enter the number of elements in the list"))
for i in range(0,n):
[Link](input("E
nter the item?"))
print("printing the list items ")
for i in l:
print(i, end = " ")

Output:
Enter the number of elements in the list 5
Enter the item?1
Enter the item?2
Enter the item?3
Enter the item?4
Enter the item?5
printing the list items 12345
LIST COMPREHANSION:

List comprehension offers a shorter syntax when you want to create a new
list based on the values of an existing list.

EX:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = []
for x in fruits:
if "a" in x:
[Link](x)
print(newlist)
output: ['apple','banana','mango']

SORT LIST:

List objects have a sort() method that will sort the list alphanumerically,
ascending, by default.

list = ["orange", "mango", "kiwi", "pineapple", "banana"]

[Link]()
print(list)

list1=[2,3,4,1,5]
[Link]()
print(list1)
COPY LIST:

copy() method copies the list and returns the copied list

Ex:
a = [6,8,2,4]
b =[Link]()
print("Original list:",a)
print("Copy list:",b)
JOIN LIST:
Joining two list.
EX:

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)

USING append() METHOD:


Add an element at the end of the list.

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]
for x in list2:
[Link](x)
print(list1)

USING extend() METHOD:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]
[Link](list2)
print(list1)

reverse() METHOD:

fruits = ['apple', 'banana', 'cherry']


[Link]()
print(fruits)
pop() METHOD:

fruits = ['apple', 'banana', 'cherry']


[Link](1)
print(fruits)
[Link]()
print(fruits)
Clear():
a = ['apple', 'banana', 'cherry']
[Link]()
print(a)
Count():
a = ['apple', 'banana', 'cherry']
b=[Link]("banana")
print(b)
Index:
a = ['apple', 'banana', 'cherry']
b=[Link]("banana")
print(b)
Insert:
a = ['apple', 'banana', 'cherry']
[Link](1,"cherry")
print(a)
Remove:
a = ['apple', 'banana', 'cherry']
[Link]("cherry")
print(a)

PYTHON TUPLE:

 Tuples are immutable lists and cannot be change in anyway once it is


created.
 Tuples are defined in the same way as lists
 They are enclosed within parenthesis and not within square braces
 Elements of the tuple must have a defined order
 Negative indices are counted from the end of the tuple, just like lists
 Tuple also have the same structure where the values are separated by
commas.
CREATING TUPLES:

An empty tuple can be written as follows.


T1 = ()
The tuple having a single value must include a comma.
T2 = (90,)
T3 = (101, "Ayush", 22)
T4 = ("Apple", "Banana", "Orange")
To create a tuple from a list.
L=[1,2,3]
T=tuple(L)
Print(T)

ACCESSING TUPLE ELEMENTS:

Accessing the elements from a tuple can be done using indexing or slicing.

EXAMPLE:

t=(20,30,50,40,60,70)

print(t[0]) #20

print(t[-1]) #70
print(t[-6]) #20

print(t[:]) #(20,30,50,40,60,70)

print(t[1:4]) #(30,50,40)

print(t[::2]) #(20,50,60)
print(t[::-2]) #(70,40,30)

print(t[-4:-1]) #(50,40,60)

UPDATE TUPLE:

Tuples are unchangeable, meaning that you cannot change, add, or remove
items once the tuple is created. So you can change the list than we will change the
items.

EXAMPLE:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
[Link]("orange")
x = tuple(y)
print(x)
[Link]("apple")
x= tuple(y)
print(x)

UNPACKED TUPLE:

we create a tuple, we normally assign values to it. This is called "packing" a


[Link] are also allowed to extract the values back into variables. This is called
"unpacking".

EX:

fruits = ("apple", "banana", "cherry")


(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
LOOP TUPLE:

You can loop through the tuple items by using a for loop.
EX:

thistuple = ("apple", "banana", "cherry")


for x in thistuple:
print(x)

USING RANGE FOR LOOP:

You can also loop through the tuple items by referring to their index
[Link] the range() and len() functions .

EXAMPLE:

thistuple = ("apple", "banana", "cherry")


for i in range(len(thistuple)):
print(thistuple[i])
JOIN TUPLE:

To join two or more tuples you can use the + operator.

EX:

tuple1 = ("a", "b" , "c")


tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
MULTIPLY TUPLES:
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
PYTHON SET:

 Sets are used to store multiple items in a single [Link] items are
unordered,unchanged and do not allow duplicate values.
 Set items are unordered.
EX:

set = {"apple", "banana", "cherry"}


print(set)
ACCESSING SET ITEMS:

set = {"apple", "banana", "cherry"}


for x in set:
print(x)

ADD SET ITEMS:

To add one item to a set use the add() method.

EX:

set = {"apple", "banana", "cherry"}


[Link]("orange")
print(set)

ADD SETS:

To add items from another set into the current set, use the update() method.

EX:

X = {"apple", "banana", "cherry"}


Y = {"pineapple", "mango", "papaya"}
[Link](Y)
print(X)
REMOVE ITEM:

To remove an item in a set, use the remove() method.

EX:

set = {"apple", "banana", "cherry"}


[Link]("banana")
print(set)

JOIN SET:

You can join the set using union() method.

EX:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}
set3 = [Link](set2)
print(set3)
PYTHON DICTIONARY:
 Dictionary is an unordered set of key and value pair.
 It is an container that contains data, enclosed within curly braces.
 The pair i.e., key and value is known as item.
 Dictionary items are changeable.
 It doesn’t allow duplicate items.
 The key and the value is separated by a colon(:).

# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: “apple”, 2: “ball”}
EX:

x={1:"C",2:"C++",3:"Java",4:"Python"}
print(x)
y=x[2]
print(y)
z=[Link]()
print(z)
a=[Link]()
print(a)
x[2]="R"
print(x)

USING update() METHOD:

x={1:”C”,2:”C++”,3:”Java”,4:Python”}

[Link]({3:"java"})
print(x)

ADD ITEMS:

Adding an item to the dictionary is done by using a new index key and assigning
a value to it.

EX:

dict = {“name”:”Jack”, “age”: 26}


dict[“city”]=”madurai”
print(dict) #{‘name:’Jack’,’age’:26,’city’:’madurai’}

[Link]({"favcolor": "red"})
print(dict)
REMOVING ITEMS:

Using pop() and popitem() to Remove the items in dictionary.

EXAMPLE:

dict={“name”:”Jack,”age”:23,”city”:”Madurai”,”favcolor”:”green”}
[Link](“city”)
print(dict) #{‘name’:’Jack’,’age’:23,’favcolor’:’green’}

[Link]()
print(dict) #{‘name’:’Jack’,’age’:23}

LOOP DICTIONARY:

You can loop through a dictionary by using a for loop.

Example for printing keys:

dict = {"name": "Jack","age”: 23,"city": “Madurai”}


for x in dict:
print(x)
dict = {"name": "Jack","age”: 23,"city": “Madurai”}
for x in [Link]():
print(x)

Example for printing values:

dict = {"name": "Jack","age”: 23,"city": “Madurai”}


for x in dict:
print(dict[x])
for y in [Link]():
print(y)
Example for iterating key,value pair:

dict = {"name": "Jack","age”: 23,"city": “Madurai”}


for x, y in [Link]():
print(x, y)
COPY DICTIONARY:

We can copy one dictionary to another dictionary using copy() method.

EX:

dict = {"name": "Jack","age”: 23,"city": “Madurai”}


mydict = [Link]()
print(mydict)
Switch:
Python doesn’t have any switch statement. Dictionary to work
like switch.
Ex:
a={"a":122,"b":123,"c":124,"d":125}
n=input("Enter the Character:")
if(n>="e"):
print("enter valid choice")
else:
print("The result for n is :",[Link](n))

PYTHON FUCNTION:

A function is a block of code which only runs when it is called.


SYNTAX:

EXAMPLE:

def my_function(): #function definition


print("Hello from a function")
my_function() #function calling
Ex:
ch=int(input("Enter the value:"))
def a():
print("hai")
def b():
print("hello")
def c():
print("welcome")
if ch==1:
a()
if ch==2:
b()
if ch==3:
c()
RETURN VALUES:

def my_function(x):
return 5 * x
print(my_function(3)) #15
print(my_function(5)) #25
print(my_function(9)) #45

LAMDA FUNCTION:

 A lambda function is a small anonymous function.

 A lambda function can take any number of arguments, but can only have one
expression.

EX:

x = lambda a: a + 10
print(x(5)) #15

USING MULTIPLE VALUES IN LAMDA FUNCTION:

x = lambda a, b: a * b
print(x(5, 6)) #30
PYTHON EXCEPTION HANDLING:

 The try block lets you test a block of code for errors.

 The except block lets you handle the error.

 The else block lets you execute code when there is no error.

 The finally block lets you execute code, regardless of the result of
the try-and except blocks.

Common Exceptions

1. ZeroDivisionError: Occurs when a number is divided by zero.

2. NameError: It occurs when a name is not found. It may be local or


global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.

5. Value Error: a function or method is called with an invalid argument or


input, such as trying to convert a string to an integer when the string
does not represent a valid integer.
6. Key Error :This exception is raised when a key is not found in a
dictionary.
7. Index Error: Index is out of range for a list, tuple, or other sequence
types.
8. Attribute Error: An attribute or method is not found on an object, such
as trying to access a non-existent attribute of a class instance.
9. Type Error : This exception is raised when an operation or function is
applied to an object of the wrong type, such as adding a string to an
integer.
Type Error:
x=5
y = "hello"
try:
z=x+y
except TypeError:
print(“Cannot add an int and a string")
Zero division Error:

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c=a/b
print(c)
except Exception as e:
print(e)
else:
print("Hi I am else block")

EXAMPLE FOR FINALLY BLOCK:

try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Name Error:
try:
n="sathya"
print(age)
except NameError as e:
print(e)
Value Error:
try:
n=int(input("enter no:"))
except ValueError as e:
print(e)
except NameError as e:
print(e)
Index Error:
try:
l=[10,20,30,40]
print(l[6])
except IndexError as e:
print(e)
Key Error:
try:
d={'name':'python','lang":"high"}
print(d['city'])
except KeyError :
print("city not in dictionary")
RAISE AN EXCEPTION:

As a Python developer you can choose to throw an exception if a condition


occurs. To throw (or raise) an exception, use the raise keyword.

EX:

x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
PYTHON FILE:

The data is stored in a place, it is called a file.

Advantages of file:

• When the data is stored in a file, it is stored permanently.

• It is possible to update the file data.

• Once the data is stored in a file, the same data can be shared by various
programs.
FILE HANDLING:

The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.

MODE MEANING
“r” – read Default value. Opens a file for reading,
error if the file does not exis
“w” – write Opens a file for writing, creates the file
if it does not exist

“a” –append Opens a file for appending, creates the


file if it does not exist

“x” – create Creates the specified file, returns an


error if the file exists

CREATING A FILE:

• The new file can be created by using one of the following access modes with
the function open().

• x: it creates a new file with the specified name. It causes an error a file
exists with the same name.

Ex:
fileptr = open("[Link]","x")
if fileptr:
print("File created successfully")

Output: File created successfully


WRITING IN A FILE:

• a: It will append the existing file. The file pointer is at the end of the file. It
creates a new file if no file exists.

• w: It will overwrite the file if any file exists. The file pointer is at the
beginning of the file.

EX:

f=open('[Link]','w')
s=input('enter text:')
[Link](s)
[Link]()
Output: enter text : hai hello

Reading the file contents:

It is used to read the file contents.

EX:

f=open('[Link]',‘r')
s=[Link]()
print(s)
print(s1)
[Link]()
Output:
hai hello
hai
OOPS CONCEPT

 Class and Object


 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

CLASS:
 Class is a blueprint for an object.
 Class is a Logical Entity.

Syntax:
class class_name:
variables
methods

OBJECT:
Object is a physical entity, that works on class data.

Note:
 Each object has a distinct role (or) responsibility.
 Object creates space on memory as per class member.
Syntax:

object_name=class_name()

Ex:

class A:
a=10
def fun(self):
print("this is fun")
obj=A()
[Link]()
self:
self is keyword or [Link] class function access the [Link] used to pass the
values from another class [Link] function are automatic using self keyword.

class A:
def fun(self,a,b):
self.a=a
self.b=b

def fun1(self):
c=self.a+self.b
print(c)

obj=A()
[Link](10,2)
obj.fun1()

Package:
Python modules may contain several classes, functions, variables, etc. whereas
Python packages contain several modules. In simpler terms, Package in Python is a
folder that contains various modules as files.
Creating Package

class Factorial:
def
fact(self,num):
f=1
for i in
range(1,num+1):
f*=i
return f

import package:

from Factorial
import*
num=int(input("Enter the value:"))
obj=Factorial()
r=[Link](num)
print(r)

INHERITANCE:

When we define a class that inherits all the properties of other class
called Inheritance.

Syntax:

class Father:
properties
class Daughter(Father):
properties

Types:

 Single Inheritance
 Multiple Inheritance
 Multi-level Inheritance
 Hierachical Inheritance
 Hybrid Inheritance
Single Inheritance:

Single Inheritance is nothing but which contain one parent class and
only one child class.

Syntax:

class A:
properties
class B(A):
properties
EX:
class A:
def fun(self):
print("This is function")
class B(A):
def fun1(self):
print("Hai")
obj=B()
[Link]()
obj.fun1()
Multiple Inheritance:

Class which contain more than one Base class and only one derived
class is called Multiple Inheritance.
Syntax:

class A:
properties
class B:
properties
class C(A,B):
properties
Ex:
class A:
def value(self):
a=int(input("Enter the value:"))
self.a=a
class B:
def value1(self,pi):
[Link]=pi

class area(A,B):
def value2(self):
area=[Link]*self.a*self.a
print("Radius of circle:",area)
a=area()
[Link]()
a.value1(3.14)
a.value2()

Multi-Level Inheritance:

In this inheritance we have one parent class and multiple child class.

Syntax:

class A:
properties
class B(A):
properties
class C(B):
properties

EX:
class myclass:
def get(self):
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
self.a=a
self.b=b
class process(myclass):
def swap(self):
self.t=self.a
self.a=self.b
self.b=self.t
class myswap(process):
def display(self):
print("After swapping")
print("a=",self.a)
print("b=",self.b)
s=myswap()
[Link]()
[Link]()
[Link]()

Hierachical Inheritance:

This inheritance which contain only one parent class and multiple
child class but each child classes can access parent class properties.
Syntax:

class A:
properties
class B(A):
properties
class C(A):
properties
Ex:

class A:
def getx(self):
x=int(input("Enter the number:"))
self.x=x
def showx(self):
print("X=",self.x)
class B(A):
def gety(self):
self.x
y=int(input("Enter the number:"))
self.y=y
def showy(self):
print("Y=",self.y)
class C(A):
def getz(self):
self.x
z=int(input("Enter the number:"))
self.z=z
def showz(self):
print("Z=",self.z)
p=B()
g=C()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
Hybrid Inheritance:

The Hybrid Inheritance is a combination of other type of


[Link] it is a conbination of Multi-Level and Multiple Inheritance.

ENCAPSULATION:
Using OOP in python ,we can restricted access to methods and
[Link] does not have any private keywords. Unlike java, This prevents data
from direct modification which is called Encapsulation.

In python we denote private attributes using underscore as a prefix.


i.e.,
single underscore : _name(Protected)
double underscore : __age(Private)

EX:
class Car:
def __init__(self):
self.__maxprice=900000
def sell(self):
print("Selling price:",format(self.__maxprice))
def setmaxprice(self,price):
self.__maxprice=price
c=Car()
[Link]()
c.__maxprice =1000000
[Link]()
[Link](1000000)
[Link]()

ABSTRACTION:

Data Abstraction and Encapsulation are often used as synonyms. Abstraction is


used to “Hide” internal details and “Show” only functionalizes.
For Example:
You know how to run turn on (or) off a light using a switch but you don’t know what is
happening behind the socket.
An Abstract class cannot be instantiated which means you cannot create objects for
this class. It can only be used for inheriting the functionalities.
POLYMORPHISM:
Polymorphism consists of two words “poly” and “morph” poly
means “many” and “morph” means “shape” (form).
Polymorphism means using a families interface for multiple forms (data types).
EXAMPLE PROGRAM:
class parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parror can't fly")
class penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Pengunin can swim")
def flying_test(bird):
[Link]()
par=parrot()
peg=penguin()
flying_test(par)
flying_test(peg)
Types:
Method overloading
Method overriding

Method Overloading:
Same function name different arguments
EX1:
class A:
def fun(self,a=None,b=None,c=None):
if a!=None and b!=None and c!=None:
return a+b+c
elif a!=None and b!=None :
return a+b
else:
return a
obj=A()
print("Result=",[Link](10,20,30))
print("Result=",[Link](10,20))
EX 2:

class Myclass:
def func(self,*args): #*args=more than a values(parameter passing a fun)
sum=0
for i in args:
sum+=i
print("Sum:",sum)
obj=Myclass()
[Link](10)
[Link](1,5)
[Link](1,2,3)
Method Overriding
Same functi
class A :

def fun(self):
print("Java")
class B:
def fun(self):
print("Python")
obj=B()
[Link]()

You might also like