Python

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 157

PYTHON

INTRODUCTION :

Python was invented by Guido van Rossum.

1989 is python program was invented it Released in 1991.

Used by Google from the beginning.

Increasingly popular

Consider as a Scripting Language, but is much more


FEATURES OF PYTHON:

1. Python is easy Programming language compared to other


Languages.

2. Python is a “cross platform language” .

3. “Open-Sourced” Programming Language.

4. Python is Dynamic Typed Programming Language.

5. Python Contain Large Number of Libraries. The libraries


Contains Ready-Made code.
>>>help(‘modules’)
it Gathers the list of Libraries.

6. Python is Case Sensitive Programming Language.


7. Python is Embedded Programming Language.
It means the python language mixed other programming languages.
Python + java = Jython

8. Python is a General Purpose Programming Language.


It used to Develop many type of applications.

9. Python is Both Procedural Oriented and Object Oriented Programming


Language(OOPS).
Procedural oriented – single user applications
Object oriented -Multi user applications

10.Python is interpreted Programming Language.


It means No compilation Separately, line by line Execution, Programmer
Not need to Compile the program.
Python Syntax:

Python uses Indentation to indicate a block of


code.
Indentation in python is very important.

>>>if 10>2:
print(“10 is greater than 2”)

>>>if 10>2:
>>>print(“this statement is error”)
Python Comments:
Comments Starts with a #, and python will ignore them.

Comments can be used to explain the code.

>>>print(“hi”)#hi string print.

Multi line Comments:


if you want add multiple comments
insert # or “””……””” triple quotes using without
variable.
KEYWORDS

 Keywords in Python are reserved words that have special


meanings and purposes in the Python language. They are used
to define the syntax and structure of the language itself, and
cannot be used as variable names, function names, or any other
identifiers in your code.
DATA TYPES:
Fixed Data:
IF We are give the data directly with in the program then
that data is called as fixed data or static data.
Ex:
emp_name=“raj”

Dynamic Data:
The data is given at Execution time or Run-time.
In the Execution time user give a data. This data is called Dynamic data.

Dynamic data will be taken by using input() function.


VARIABLES
Variables are used to storing a data values

X = 32 # X is the type int


print(X)
Y = “Raja”
V #Y is the type str
print(Y)

Casting:
* If you specify the data type of the variable, that is Casting.

X = str(12) # X will be ‘12’


Y = int(12) #Y will be 12
Z = float(12) #Z will be 12.0
VARIABLE NAMES:
*A variable name start in letter or underscore.
*A variable name can only contain (A-Z,a-z,1-9,_)
*variable cannot start with number.

Many values to Multiple variables:


A, b, c = “cat”, “dog”, “cow” Output:
print(A, b, c) Cat dog cow

One value to multiple variable:


A=b=c=“Tiger” Output:
Print(A) Tiger
print(b) Tiger
print(c) Tiger
Type( ):
If you want data type of the variable we can use type() function.

X=5 Output:
print(type(X))
<class ‘int’>
Y=“hello”
<class ‘str’>
print(type(Y))

Case sensitive:
x=“hi” Output:
print(x)
X=213 hi
print(X) 213

x=4
x = “hi“ output : hi
print(x)
Python Output Variable:
Print() function is often used to output
variable.

x = “Mango”
Output:
y = “ is a”
Mango is a fruit
Z = “fruit”
Print(x, y, z)

Output Variables separated by , and we also use + operator. The + operator


Doesn’t support int + str .

Output:
Print(x + y +z) Mango is a fruit
PYTHON DATA TYPES
1. int ex: 1,2…

2. Float ex: 1.1,1.2…

3. Complex ex: 1+2i, 2+2i, …..

4. Str ex: “cat”, ”dog”

5. Boolean : True, False

6. None type : None

7. Range type : range(1,10)


1,2,…9
range Data type:

range data type is used to Generate the range of Numbers.

Ex: range(1,100) 1 to 99 Numbers are Generated.

range(0,101,10) 10 is a stepping value.

None type:
None type Represents no value or Nothing.
None type using for value Removed by memory.

>>>A=100
>>>A
100
>>>A=None
>>>type(A)
<class ‘None Type’>
PYTHON NUMBERS:
X=3 X=float(3)
Y=3.2 Y=complex(2)
Z=1+2j Z=int(2.1)

Print(type(X)) Print(X)
Print(type(Y)) Print(Y)
Print(type(Z)) Print(Z)

Print(type(x))
Print(type(Y))
Output:
Print(type(Z))

Output:
Casting:
If you specify the data type of the variable it’s
casting.

X = str(12) # X will be ‘12’


Y = int(12) #Y will be 12
Z = float(12) #Z will be 12.0
A=str(“hzs23”) #A will be “hzs23”

Print(X)
Print(Y)
Print(Z)
Print(A)
WHAT IS STRING?
String is a collection of Characters Which are Specified
Quotations. We also Specified the three Single and Double Quotes
inside the print( ) function otherwise They are consider Commend
lines.

‘hi’ Single quotes

“hi” Double quotes

‘’’hi’’’ Three single quotes

“””hi”””Three Double quotes


EX:
Any of the Object Names.
PANCARD Number.
BIKE Number.
House Address.
PYTHON STRINGS
We can use single quotes, double quotes, three quotes on a strings.

Print(‘hi’)
Print(“hi”)
Print(“’hi”’)

STRING LENGTH:
X=“he is my friend”
Print(len(x)) Output:
15
STRING SLICING:
Return a range of Characters by using the Slice.

A=“Hi I am Raja, from India” NOTE:


print(A[3:7]) The first Character is index 0.
In this example Position 3 to position 7(Not
include) is print.
Output: I am

[:4] Print the Character start position to 4(not include)

[1:] Print position 1 to last


String Modify Methods:
Upper case
a = “ i like movies” print(a.upper())

Lower case
a=“I LIKE MOVIES”
print(a.lower())

Replace()
a=“ I Like Movies” print(a.replace(“Movies”,
“playing”))

Concatenation
a= “I”
b=“like” D=(a+” “+b+” “+c)
c=“movies” print(D)
Strip( )
a = “ Hello, World! ” output : Hello, World!
print(a.strip()) #Removeing White Space

Split( )
a = "Hello, Hi!“ output :[‘Hello, Hi!’] ['Hello',
' World!'b = a.split(",")
print(b) #Split( ) method returns a List

Format( )

age = 36
txt = "My name is Raj, I am " + age Output  Error
print(txt)

age = 36
txt = “I’m Raj, and I am { }“ Output  I’m Raj, and I am 36
print(txt.format(age))
String Format:(Interpolation)
Previously we are seeing we don’t combine the string and numbers.
But we are using format method we can combine the formation of the strings.

Quantity=5
Price=23
txt=“I want {} pieces of Cake and the rate of one piece is {} Rupees”
Print(txt.format(Quantity,Price))

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

We are also use index number to concatenate the words.


Python Boolean:
Boolean Represents One of two values True or False.
>>>print(10>21)
>>>print(10>=10)

False
True

bool( ) function evaluate any Value , and give True are False in
return

In Boolean Most values are True.


Any numbers(except 0), strings (except empty string), List,
Tuple, set, Frozenset, dict are True(except empty once).

>>>print(bool(123))
>>>print(bool(0))
OPERATORS OF PYTHON

OPERATOR:
An operator performs the operation on Data.

EX: 10+20
10 and 20 are the operands.
‘+’ is an operator.
TYPES OF OPERATORS IN PYTHON:

1. Arithmetic Operators.

2. Arithmetic Assignment Operators.

3. Assignment Operators.

4. Comparison Operators.

5. Logical Operators.

6. Membership Operators.

7. Identify Operators.
1. Arithmetic operators:

Arithmetic operators Performs the Mathematical Operators.


2.Assignment Operators:

= is an assignment Operators. An assignment


Operator is used to
assign a value to a variable.

A =100
A is an variable
= is an operator
100 is an Data
3. Arithmetic Assignment Operators:

It performs Arithmetic and Assignment Operations


4. Comparison Operators:

Comparison Operator will compare the values.


<, >, <=, >=, ==,!=

EX:
>>>10<2
False
>>>10==10
True
>>>10!=10
True
5. Logical Operators:
Logical Operators are used to check the multiple conditions
at a time and given a Boolean Result.
1.and
2.or
3.not
This 3 are logical operators.

and:
All conditions must be true, any one condition is false full condition
is false.
>>>10>2 and 10<2 and 10!=10
>>>False
>>>10==10 and 10>2 and 2!=3
>>>True
Or:
At least one Condition is True, condition True.
All condition False condition false.
>>>10>2 or 10>21 or 10==12
True
>>>10>21 or 12>21 or 10==21
False

not:
if condition is True. True is False.
if condition is False. False is True.
>>>not(100>30 and 20<15 or 1==1)
False
6.Membership Operators:
Membership Operator is used to check Whether is given Member is
Exited or not.

If given member is existed True comes otherwise False Comes.

There are 2 membership Operators.


* in *not in

>>>id_nums=[12,23,34,43]
>>>23 in id_nums
>>>True
>>>21 in id_nums
>>>False
7.Identity Operators:

Identity Operators are used to Check the Identity Numbers of the


Objects.

Identity Operators:
1.is 2.is not

>>>a=b=1000 a=1000
>>>id(a) b=89
2233554354443 print(id(a))
>>>id(b) print(id(b))
2233554354443 print(a is b)
>>>a is b False
True
Conditional statements:
Conditional Statements are used to check the Conditions. If the
onditions are true then one set of statements are executed.
if the condition is false other set of statement executed.

1. If

2. If…else

3. Multiple if….else

4. If….elif….else

5. Nested if…else
CONTROL STATEMENTS:

Control statements are used to control the execution flow


Of the program.
What to execute what not to execute will be called as a
“Execution flow of the program”.

TYPES OF CONTROL STATEMENTS:

1. Conditional Statements.
2. Looping Statements.
3. Transfer Statements.
Conditional Statements:
If Statements:
If
======
Syntax

If condition:
statement

If condition is true then Statement is executed.

A=21
B=32
if A<B:
print(“A is smaller”)
IF Statements:
 txt = "The best things are Happens In our life"
if “Happens" in txt:
print("Yes, ‘Happens' is present.")

 txt = "The best things are Happens in our life"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

 a=100
b=100
if a is b:
print("Two values are not same")

 a=int(input("enter your number:"))


if a is 10:
print("Two values are same")
Else statement:
If…else :
======
Syntax

If condition:
statement1
Else:
statement2

A=21
B=23
C=34
if A>B or B>C or C==A:
print(“Statement 1 is proved”)
else:
print(“Statement 2 is proved”)
IF ELSE Statements
a = int(input(“Enter the Number:”)
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

a=int(input("pls enter the num1:"))


b=int(input("pls enter the num2:"))
if a>b:
print("a is greater then b")
else:
print("b is Greater than a")
Short Hand Methods:
a = 20
b=3

if a > b: print("a is greater than b")

a=2
b = 330

print("A") if a > b else print("B")


Nested if else:
if condition1:
condition1 related statement
if condition2:
condition2 related statement
.
.
else:
else statement
College_code=input(“pls enter college code:”)
If college_code ==“NIT567”:
print(“your college code is right”)
HTNs=[101,102,103,104,105,106]
htn=int(input(“pls enter the htn:”))
if htn in HTNs:
print(“you allow the Exam”)
else:
print(“your number is invalid”)
else:
print(“Your college code is incorrect”)
id_num=int(input("pls enter the name:")) x = int(input(“pls enter the value:”))
if id_num == 1234:
print("your allow to enter the mark") if x > 10:
mark = int(input("Enter marks")) print("Above ten,")
if mark > 90: if x > 20:
print("Grade is o") print("and also above 20!")
elif mark > 80 and mark <=90: else:
print("Grade is A") print("but not above 20.")
elif mark >=70 and mark <=80: else:
print("Grade is B") print(“x is less then 10”)
elif mark >=60 and mark <=70:
print("Grade is C")
elif mark >=50 and mark <=60:
print("Grade is D")
else:
print("you got E grade")
else:
print("pls enter crt ID num")
If…elif…else:
If…else :
======
Syntax

If condition1:
statement1
elif condition2:
statement2
elif condition3:
statement3
Else:
A=191 statement4
B=23
if B>A:
print(“B is greater than A”)
elif B<A:
print(“A is greater than B”)
else:
print(“2 numbers are equal”)
a=int(input("pls enter the num1:"))
b=int(input("pls enter the num2:"))
c=int(input("pls enter the num3:"))
if a>b and b>c:
print("a is greater then b")
elif b>a and c>b:
print("Welcome")
elif c==a:
print("Hello")
else:
print("Those three Statements are not true")

price=int(input("Enter the price of bike"))


if price > 100000:
tax = 15/100*price
elif price >50000 and price <=100000:
tax = 10/100*price
else:
tax = 5/100*price
print("Tax to be paid ",tax)
What is loop?
if we want to Repeat any operation for multiple times then we
Have to use “looping” concept.

Looping Statements:
1. for loop

2. while loop

3. for with else block

4. while with else block


For loop:
A for loop is used to iterating over a sequence.

for i in range(1,11):
print(i,’*’,2,’=‘,i*2)

color=[“red”,”yellow”,”blue”] Output:
fruits=[“apple”,”banana”,”berry]
for I in color:
for j in fruits:
print(I, j)
Number Pattern
rows = 5
for i in range(1, rows + 1):
for j in range(1, i + 1):
print("*", end=' ')
print(‘ ‘)

rows = 5
b=0
for i in range(rows, 0, -1):
b += 1
for j in range(1, i + 1):
print(b, end=' ')
print('\r')
for loop with else block:
for x in range(1,10):
if x==5: break
print(x)
else:
print(“break Statement is executed else block is not executed”)
The break Statement:
we can stop the loop before it has looped through all the item.

Animals=[‘cat’,’dog’,’rat’,’lion’]
For i in Animals:
print(i)
if i==“rat”:
break

The continue Statement:


we can stop the current iteration of the loop,and continue
with the next.
Animals=[‘cat’,’dog’,’rat’,’lion’]
For i in Animals:
if i==“rat”:
continue
print(i)
While loop:
While loop we can execute a set of statements as long as a condition
is true.

i =1
while i<6:
print(i)
I +=1

rows = 5
i=1
while i <= rows:
j=1
while j <= i:
print((i * 2 - 1), end=" ")
j=j+1
i=i+1
print(‘ ')
Break statement for While loop:
we can stop the loop even if the while condition is true.

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

Continue Statement for While loop:


we can stop the current iteration and continue with the next.

i=0
while i<6:
i+=1
if i==3:
continue
print(i)
while loop with else block:
we can run a block of code once when the condition is no longer
is true else statement executed.

i=1
while i<6:
print(i)
i+=1
else:
print(“the while loop is end”)
COLLECTION DATA TYPES:

1. List Collection [1,2,3]

2. Tuple collection (1,2,3)

3. Set collection {1,2,3}

4. Frozenset collection frozenset({1,2,3})

5. Dict collection{“name “: “raj”, “age”:20, “native”:”chennai”}


LIST COLLECTIONS:

• List collection is a group of values and elements.

• It Represent with [] Brackets.

• It allow Both Homogeneous and heterogeneous Values.

• List allows indexing and Slicing.

• List allows duplicate values.

• List is mutable (insertion, updation, deletion) allowed.


>>>Homogeneous=[12,23,34,22] >>>Heterogeneous=[111,21.1,”hi”,True]
>>>Homogeneous >>>Heterogeneous
[12,23,34,22] [111,21.1,’hi’,True]
>>>type(Homogeneous)
<class ‘list’>

Nested list = Collection of lists


(or)
Nested list is a collection of sub lists.

>>Emp_Records=[[101,”Raj”,”IT”,”PYTHON Developer”,40000],[102,”Rani”,”IT”,
C Developer”,30000]]
>>Emp_Records
101,”Raj”,”IT”,”PYTHON Developer”,40000],[102,”Rani”,”IT”,
C Developer”,30000]]
What is Indexing?
The value will be accessed with its index number
That is called Indexing. We can access individual values.
>>>Student_details=[101,”Raj”,”maths”]
Student_details[1]
“Raj”

What is Slicing?
Our Required Values Can be accessed From the List.
It is called as Slicing.
>>>Student_details=[101,”Raj”,”maths”,”science’]
Student_details[0:3]
[101,”Raj”,”maths”]
Why List is an Mutable?

List is allow Changes.

!.) Insertion:
Student_id=[101,102,103]
(or)
Student _id=list((101,102,103))

Student_id.append(104)
append keyword is used to insert the value in last.

Student_id.insert(0,100)
insert the value by using index value.

Student_id.extend([105,106,107])
extend keyword is used to insert the multiple values in last.

We can also uses the append keyword but is created the Nested list
!!.)Updation:

Indexing is used to updates the value.

Product_prices[index] = newvalue

!!!.) deletion:

remove and del keyword is used to delete the list.


pop():

pop() method is used to delete last element from a list.

clear():
clear method is used to clear the all the values from the list.

sort():

sort method is used to sort a list in ascending order.

reverse():
it used to change the value in reverse.

copy():
copy keyword is used to copy the list.
min and max keywords:

min keyword is used to find the minimum value of the list.

max keyword is used to find the maximum value of the list.

>>>list1=[1,2,3,4,5]
>>>min(list1)
>>>1
len():
len() function is used to know the length of the list.
>>>list1=[1,2,3,4,5]
>>>len(list1)
>>>5
Count():
count() method is used to know the number of occurrences of
given element in a list.
>>>list1=[10,12,12,12,13,14,10]
>>>list1.count(12)
>>>3
2. Tuple collection:

*Tuple is a collection of values.

*Tuple is represented in ().

*it allow both homogeneous and heterogeneous values.

*It also support Indexing and Slicing.

*It allow duplicate values.

*Insertion order is maintained.

*Tuple is immutable.
insertion, updation, deletion are not allowed.
fruits = ("apple", "banana", "cherry", "apple", "cherry")
(or)
fruits = tuple(("apple", "banana", "cherry", "apple", "cherry"))

print(fruits)
Output : ("apple", "banana", "cherry", "apple", "cherry")

Prinrt(len(fruits))
Output : 5

Print(type(fruits))
Output : <class ‘tuple’>

Print(fruits[1])
Output : banana

Print(fruits[1:3]) #it allows Negative indexing also


Output : banana, cherry
fruits = tuple(("apple", "banana", "cherry"))

if “banana” in fruits:
print(“Ok”)
Output : Ok

y = list(fruits) #We can use all list keywords in tuple after changing tuple to list
y[1] = “Mango"
fruits = tuple(y)
print(fruits)
Output : (“apple”, “Mango”, “Cherry”) #if we want to change tuple first change
tuple to list

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


y = ("orange",)
fruits += y
print(fruits)
Output : ("apple", "banana", "cherry“, “orange”)

E
Unpacking Tuple:
fruits = ("apple", "banana", "cherry")
(carrot, tomato, potato ) = fruits

print(carrot)
Output : apple

fruits = ("apple", "mango", "papaya", "pineapple", "cherry")


(carrot, *watermelon , potato) = fruits

print(carrot)
print(watermelon)
print(potato)

Output : apple
[“mango”, “papaya” , “pineapple”]
cherry

If the asterisk is added to another variable name than the last, Python will
assign values to the variable until the number of values left matches the
number of variables left.
Adding and Multiplying Tuple:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)

Output : (“a”, “b”, “c”, 1, 2, 3)

New=tuple1 * 2
Print(New)
Output : ("a", "b" , "c“, "a", "b" , "c")
3. Set Collection:

• Set is also a collection of values.

• it Represented in {}

• set doesn’t allow duplicate values.

• insertion order is not maintained.

• homogeneous and heterogeneous values are allowed.

• Set doesn’t allow indexing and Slicing.

• set is mutable.
fruits = {"apple", "banana", "cherry", "apple"} #set doesn’t allow duplicate
(Or)
fruits=set((“apple", "banana", "cherry", "apple“)) #set constructor
print(fruits)

Output : {“apple", "banana", "cherry"}

fruits.add(“Mango”) #add method


Output : {“banana”, “cherry”, “apple”, “mango”}

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


fruits2= {"pineapple", "mango", "papaya"}
fruits1.update(fruits2) #update method

print(fruits1)
Output :{"apple", "banana", "cherry“, "pineapple", "mango", "papaya"}
fruits1 = {"apple", "banana", "cherry"}
fruits2= ("pineapple", "mango", "papaya")
fruits1.update(fruits2) #update method used any iterable

print(fruits1)
Output :{"apple", "banana", "cherry“, "pineapple", "mango", "papaya"}

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


fruits.remove("banana") #remove method, discard( ) same as remove
print(fruits)

#try pop( ), clear ( ) and del also

Output : {“apple”, “cherry”}


set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}

set3 = set1.union(set2) #union method is combine the two or more set in new
set collection
print(set3)

Output : {1, “a”, 2, 3, “b”, “c”}

set1.update(set2) #update method insert item in set1


print(set1)

Output : {1, “a”, 2, 3, “b”, “c”}


x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y) #Common item is print

print(x)
Output : {“apple”}

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


y = {"google", "microsoft", "apple"}
z = x.intersection(y)

print(z) #common item print in new set


Output : {“apple”}
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y) #uncommon items are print

print(x)
Output :{ "banana", "cherry“, "google", "microsoft"}

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


y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y) #uncommon items print in new set

print(z)
Output : { "banana", "cherry“, "google", "microsoft"}
4. Frozenset Collection:

• it Represented in {}

• Insertion order is not maintained.

• it allow both homogeneous and heterogeneous values.

• Not allow indexing and Slicing.

• Duplicate values are not allowed.

• Frozenset is immutable.
5. Dictionary collection:

• it is a collection of “key” :”value” pairs.

• it Represented with {}

• it allows both Homogeneous and Heterogeneous key : value


pairs.

• Insertion order is maintained.

• Indexing and slicing are not allowed.


we can access a value with it’s key.

• In Dictionary duplicate keys are not allowed, but duplicate


values are allowed.
dict1 ={
“id": 765,
“name": “raj",
“sub": “maths”
}
print(dict1)
Output : {“id": 765, “name": “raj", “sub": “maths”}

Print(dict1[“name”]) #calling with index


Output : raj

dict1 ={
“id": 765,
“name": “raj",
“sub": “maths”
“fav sports” : [“Football”, “chess”, “Cricket”]
}
Print(dict1)
dict1 ={
“id": 765,
“name": “raj",
“sub": “maths”
}
x = dict1.keys()
print(x)
Output : dict_keys([“id”, “name”, “sub”])

dict1 ={
“id": 765,
“name": “raj",
“sub": “maths”
}

x = dict1.values()
print(x)
Output : dict_values([765, “raj”, “maths”])
dict1 ={
“id": 765,
“name": “raj",
“sub": “maths”
}

x = dict1.items()
print(x)
Output : dict1_items([(“id”,765), (“name”,“raj”),(“sub”,“maths”)])

dict1 ={
“id": 765,
“name": “raj",
“sub": “maths”
} #try in update({“class”:10}) method also
dict1[“sub”]=“science” #we can also insert new key value pairs also
Print(dict1)
Output : {“id": 765, “name": “raj", “sub": “science”}
dict1 ={
“id": 765,
“name": “raj",
“sub": “maths”
}
Dict1.pop(“name”) #using pop method
Print(dict1)
Output : {“id”:765, “sub”:”maths”}

dict1 ={
“id": 765,
“name": “raj",
“sub": “maths”
}
for I in dict1: #if we want values use print(dict1[i])
print(I)
Output: id
name
Subprint
dict1 ={
“id": 765,
“name": “raj",
“sub": “maths”
}
dict2=dict1.copy( )
Print(dict2)
Output : {“id”:765, “name” : “raj” ,“sub”:”maths”}
dict1 ={
“id": 785,
#nested dict “name": “raj",
Dict={ “sub": “maths”
“dict1” : { }
“id": 765, dict2 ={
“name": “raj", “id": 965,
“sub": “maths” “name": “raj",
}, “dict2” : { “sub": “maths”
“id": 760, }
“name": “ram", dict3 ={
“sub": “science” “id": 705,
} , “dict3” : { “name": “raj",
“id": 965, “sub": “maths”
“name": “raja", }
“sub": “maths” Dict={
}} “dict1” = dict1,
“dict2” = dict2,
Print(Dict) “dict3” = dict3}

Print(Dict)
PYTHON FUNCTION:

A Function is a set of statements to perform a task.


Ex: “addition” function to perform the addition operation
“Multiplication” function to perform the multiplication operation.

The main advantage of the function is code Reusability.

In python There are two types.


1.system Defined function
2.user defined function
System Defined Function:
System defined functions are also called as “pre-defined functions”
are Ready made functions.

ex : print(), input(), type()…

User Defined Function:


User Defined function are also called as Programmer Defined
functions. According to the Business or any other Requirements.

Ex: Banking applications


Functions are defined four ways:

1. Function with parameters and with Return values.

2. Function with parameters and without Return values.

3. Function without parameter and with Return values.

4. Function without parameter and without Return values.


Ex: def addition a,b,c,d:
“def” is a keyword, it is used to define a
function.
“addition” is a function name.
“a,b,,c,d” is a parameter.

Parameters are used to pass the input values to


the Function.

def addition(a,b,c,d):
e=a+b+c+d
return e

def addition(a,b,c,d):
e=a+b+c+d
print(e)
Function Calling:

def function():
print(“hi i/’m good”)
function()

Parameters or Arguments:
A parameter is the variable listed inside the
parentheses in the Function definition.

Argument is the value that is sent to the function


when it is called.
def my_function(name, native):
print(name + “ “ + native)
my_function(“raja”, “Chennai”)

Default parameter value:

Def my_function(fruit=“apple”):
print(“I like” + fruit)
my_function(“mango”)
my_function()

Pass Statement:

function definitions cannot be empty but if you for some Reason


have a function definition with no content , put pass statement to avoid
getting an error.

def myfunction():
pass
Python Arrays:

Arrays are used to store a multiple values in single variable.


Python doesn’t have build in support for arrays,but python lists can be used
instead.

Fruits=[mango,apple,orange]

X=Fruits[1]

Print(X)
Modules:
A modules is a collection of functions. Module to be the same
as a code library. Save the python file using .py . use the module
using import
statement.
>>>help(“modules”)
>>>help(“math”)

>>>import math
>>>math.factorial(5)
120

>>>import numpy
>>>a=numpy.array([1,2,3,4,5])
>>>print(a)
NUMPY:
 NumPy is a Python library.
 NumPy is used for working with arrays.
 NumPy is short for "Numerical Python".
 NumPy was created in 2005
 NumPy aims to provide an array object that is up to
50x faster than traditional Python lists.
 In array object numpy is called ndarray

Installation of NumPy

In command prompt type pip install numpy

import numpy

import numpy as np #as keyword is used to import the numpy as np


import numpy
a = numpy.array([1, 2, 3, 4, 5])
print(a)

Output : [1,2,3,4,5]

import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(a)

Output : [1,2,3,4,5]

import numpy as np
a= np.array([1, 2, 3, 4, 5])
print(a)
print(type(a))

Output : [1,2,3,4,5]
<class ‘numpy.ndarray’>
Dimensions in Arrays

 0 –Dimension array
 1 –Dimension array
 2-Dimension array
 3-Dimension array

0-Dimension array:

import numpy as np
a = np.array(42) # if you give ([42])brackets this array is one dimension.
print(a)
print(a.ndim) #ndim keyword is use to know about How many Dimensions are
created

Output : 42
0
1-Dimension Array:
import numpy as np
a= np.array([1, 2, 3, 4, 5]) #An array that has 0-D arrays as its elements is called 1-D array .
print(a)
print(a.ndim)

Output :[1,2,3,4,5]
1

2-Dimension Array:
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]]) #array that has 1-D arrays as its elements is called a 2-D array.
print(a)
print(a.ndim)

Output : [[1 2 3]
[4 5 6]]
2
3-Dimension Array:
import numpy as np
a = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a) #An array that has 2-D arrays as its elements is called 3-D array.
print(a.ndim)

Output : [[[1 2 3]
[4 5 6]]

[[1 2 3]
[4 5 6]]]
3
Multi Dimension Array:

import numpy as np
a= np.array([1, 2, 3, 4], ndmin=5) #we can create multi dimension Array using
ndmin
print(a)
print('number of dimensions :’, a.ndim)

Output : [[[[[1 2 3 4]]]]]


5
Numpy Array Indexing

import numpy as np
a = np.array([1, 2, 3, 4])
print(a[0] + a[2])

Output : 4

import numpy as np
a = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print( a[1, 4] + a[0,2])

Output : 13
import numpy as np
a = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(a[0, 1, 2])

Output : 6

“””First number represents the first dimension it contain two arrays


[[1, 2, 3], [4, 5, 6]]
and:
[[7, 8, 9], [10, 11, 12]]

We select 0
[[1, 2, 3], [4, 5, 6]]

The second number represents the second dimension, which also contains two arrays:
[1, 2, 3]
and:
[4, 5, 6]

We select 1 [4, 5, 6]

The third number represents the third dimension, which contains three values: 4 5 6

We select 2 print 6”””


Array Slicing
import numpy as np
a= np.array([1, 2, 3, 4, 5, 6, 7])
print(a[4:])

Output : [5 6 7]

import numpy as np
a= np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(a[1, 1:4])

Output : [7 8 9]

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7]) #step slicing
print(arr[::2])

Output : [1 3 5 7]
import numpy as np
a = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(a[0:2, 1:4]) #First slicing represents 0 to 2 index 2nd Represents values

Output : [[2 3 4]
[7 8 9]]

Copy and view:


import numpy as np
import numpy as np
a = np.array([1, 2, 3, 4, 5]) a = np.array([1, 2, 3, 4, 5])
x = a.copy() x = a.view()
a[0] =0 a[0] = 0

print(a) print(a)
print(x) print(x)

Output : [0 2 3 4 5] Output : [0 2 3 4 5]
[1 2 3 4 5] [0 2 3 4 5]
Array Shape:
import numpy as np
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a.shape)

Output : (2,4)

Array Reshape: 1D to 2D and 1D to 3D


import numpy as np
a= np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
b= a.reshape(4, 3)
print(b)

Output : [[1 2 3]
[4 5 6]
[7 8 9]
[10 11 12]]
import numpy as np
a= np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
b= arr.reshape(2, 2, 3)
print(b)

Output : [[[1 2 3]
[4 5 6]]
[[7 8 9]
[10 11 12]]]
For Loop and Array iterating:
import numpy as np
import numpy as np
a= np.array([[1, 2, 3], [4, 5, 6]])
a= np.array([[1,2,3],[4,5,6]])
for x in a:
for y in x: for x in np.nditer(a):
print(y) print(x)

Output : 1 Output : 1
2 2
3 3
4 4
5 5
6 6
Array Concatenation
import numpy as np
a1 = np.array([[1, 2], [3, 4]])
a2 = np.array([[5, 6], [7, 8]])
a = np.concatenate((a1, a2), axis=1) #axis represents row
print(a)

Output : [[1 2 5 6]
[3 4 7 8]]

import numpy as np
a1 = np.array([[1, 2], [3, 4]])
a2 = np.array([[5, 6], [7, 8]])
a = np.concatenate((a1, a2))
print(a)

Output : [[1 2]
[3 4]
[5 6]
[7 8]]
Array Sort:
import numpy as np
a = np.array([[13, 9, 4], [15, 12, 1]])
print(np.sort(a))

Output :[[4 9 13]


[1 12 15]]
Pandas:
 Pandas is a Python library used for working with data sets.
 It has functions for analyzing, cleaning, exploring, and
manipulating data.
 The name "Pandas" has a reference to both "Panel Data", and
"Python Data Analysis“
 Pandas allows us to analyze big data and make conclusions based
on statistical theories.
 Pandas can clean messy data sets, and make them readable and
relevant

Pandas installation:
In command prompt type pip install pandas

import pandas

import pandas as pd #as keyword is used to import the pandas as


pd
Pandas DataFrames:

import pandas as pd
data = {
"name": ["Arun", "praveen", "Raja"], import pandas as pd
'Marks': [100, 70, 82] data = {
} "name": ["Arun", "praveen", "Raja"],
new = pd.DataFrame(data) 'Marks': [100, 70, 82]
print(new) }
new = pd.DataFrame(data,index=[“one”,” tw
Output : name marks “three”])
0 arun 100 print(new)
1 Praveen 70
2 Raja 82 Output : name marks
one arun 100
two Praveen 70
three Raja 82
Pandas Series:
import pandas as pd
import pandas as pd a = [1, 2, 8]
a = [1,2,8] new = pd.Series(a, index = ["x", "y", "z"])
new = pd.Series(a) print(new)
print(new)
Output : x 1
Output : 0 1 y 2
1 2 z 8
2 8 dtype: int64
dtype: int64

import pandas as pd
names = {"name1": "Arun", "name2": "Raja", "name3": "Praveen"}
new = pd.Series(names)
print(new)

Output : name1 Arun


name2 Raja
name3 Praveen
dtype: object
Matplotlib:
Matplotlib is a plotting library for the python programming
language and it’s numerical mathematic extension of Numpy.

Matplotlib is a low level graph plotting library in python that serves as a


visualization utility

In command prompt type pip install matplotlib

import matplotlib
import sys # if the Runtime error comes we use sys otherwise no need
import matplotlib
matplotlib.use(‘Agg’) #this line Doesn’t need for windows users

import matplotlib.pyplot as plt #pyplot is a subplot of matplotlib


import numpy as np

xpoints = np.array([0,6])
ypoints= np.array([0,250])

plt.plot(xpoints, ypoints)
plt.show()

#sys module in Python provides various functions and variables that


are used to manipulate different parts of the Python runtime
environment

#Agg, is a non-interactive backend that can only write to files. It is used
on Linux
OOPS
In simple terms OOPS is related to Objects. Object is a Real World
entity. The Entity is existed in the real world.
Entity= a thing (or) an element.

Every Object is having :


!.) State
!!.) behaviour

Not a programming terms we are saying “state” of the object means


the Properties of object or the characteristics of the object. Let us
take student
Object. Student object having State are Student name, mobile no,….
“behaviour” of the student object is having writing the notes and
practice the
Program.

In programming terms State means “Variable”, behaviour means “


method”
Concept of the OOPS:

To Construct an object, We should use a class. Class is like


a blueprint of the object. It is used to construct the
object.

For Examble we create Student class, we will Constuct the


Student Object.

Class student:
def accept(self):
self.Student_id=input(“pls enter the student name:”)

Class is a keyword to create the classes.


Def is a keyword to define the method or create the method.
Self is a keyword to represent current object.
class tree:
e=40
def demo(self,a,b,c=76):
d=a+b+c+self.e
print(d)
objt=tree()
objt.demo(10,24)

The __init__() Function:(Constructor)

class person:
def __init__(self, name, age):
self.name1=name
self.age1=age
def myfunction(self):
print(“my name” + self.age)
p1=person(“raj”,32)
p1.myfunction()
Program:
Let us create employee class.

Class employee :
def accept(self):
self.emp_id=int(input(“pls enter emp id:”))
self.emp_name=input(“pls enter emp name:”)
def display(self):
print(“Employee Details”)
print(“EMPLOYEE ID:”,self.emp_id)
print(“EMPLOYEE NAME:”,self.emp_name)

employee1=employee()
employee1.accept()
employee1.display()

employee2=employee()
employee2.accept()
employee2.display()
Types of Variables in OOPS:
1.Static Variable
2.Instance Variable

Static Variable:
* In OOPS the data is Common to all objects then the data is
called the Static variable.
* In Employee objects are having the same Company Details.

Instance Variable:
* In the data is Changing from one Object to another object
then the data Is stored in the instance variable.
Local Variable:
A Variable is defined in Inside of the Function.
It’s called Local variable.

def addition():
a=100
b=200
Print(a+b)

Global Variable:
A Variable is defined in Outside of the function.
It’s called global variable.

A=100
B=100
def addition():
print(A+B)
INHERITANCE:
A class Gets Features from another Class or A child class is
getting
Features from Parent class.

Types of Inheritance:

1. Single Inheritance

2. Multiple Inheritance

3. Multi-level Inheritance

4. Multi- path Inheritance

5. Hierarchical Inheritance

6. Hybrid Inheritance
Single Inheritance:
A single Child Class is Inherited from single
parent class.

Multiple Inheritance:
A single child class is inherited from Multiple parent
class.

Multi-level Inheritance:
A Class is inherited from multiple level of
classes. Or A child class is inherited from subclass and
this subclass is inherited from a super class.

Multi-path Inheritance:
A child class is inherited from two sub classes and
the sub Classes are inherited from one super class.
Hierarchical Inheritance:
Multiple Child Classes are inherited from single
Parent Class.

Hybrid Inheritance:
Hybrid Inheritance is a Combination of the
Multiple types of Inheritance
Single Inheritance:
Multiple inheritance:
Polymorphism:

#function Overloading
#function Overriding

Class Demo(): class Demo():


def function(self): def function(self):
print(“hi”) print(“HI”)
def function(self,A): Class Demo1(Demo):
print(A) def
function(self):

print(“Hello”)

obj=Demo() obj=Demo1()
obj.function() obj.function()
obj.function(20)
Encapsulation:
Encapsulation is the Bundling data and Methods with in a single unit.
When you create a Class, it means you are implementing encapsulation.
it’s used to Hiding the data and Restricts the access of data from the
outside the world.

Data Abstraction:
Used to Hide the internal function from the user.
The user only interact with the basic implementation of the function
but inner working is hidden.
Exception Handling:
Handling the Run time error. In python Exception Handling done
with following blocks.
#1.try
#2.except
#3.finally

try:
A=12
B=0
C=A/B
print(C)
except:
print(“Error is Occured”)
finally:
X=12
print(X)
File Handling:
Performing the Operation on files is called as “File Handling”.
File is a collection of Records.

Types of Files:
1.Text files:
Alphabets, Degits, Symbol
Text files are also called as “Human Handling files”.
2.Binary files:
Image files, audio files, video files, machine understandable
files, execution files.
Binary files are also called as Human unreadable files.

#file object = open(“file name”,”mode”)


#mode r,w,a or r+,w+,a+
#attributes name,mode,closed
Reading and Writing a File:

f=open("D:/python/lo.txt", "r") f=open("D:/python/lo.txt", “w”)


ab=f.read() f.write(“HI”)
print(ab) print(“HI message is stored”)
f.close() f.close()

f=open(“file location and name”, “r”) f = open(“file location and name”, “r”)
no_of_lines=len(f.readlines()) ab=input(“enter the data”);
print(no_of_lines) count=0
for I in f.readlines(): for I in f.readlines():
print(I) count=count+1
f.close() if ab in I:
print(“your data is
foundinline”,I)
f.close()
WHAT IS SQL
 Structured Query Language SQL

 SQL is a language, not a database

 SQL language is used in MySQL, SQL Server, MS Access, Oracle,


Sybase, Informix, Postgres database systems.
WHAT IS MYSQL

 MYSQL Is a Relational database management System(RDBMS)


and popular open source database.

 RDBMS is the basis for all modern database systems such as


MySQL, Microsoft SQL Server, Oracle, and Microsoft Access.
RDBMS uses SQL queries to access the data in the database.

Install mySQL In Python:

In Comment Prompt  pip install mysql-connector-python


HOW TO DOWNLOAD MYSQL IN WINDOWS:

1. GOOGLE  Search mySQL  open official link  choose Downloads

2. Choose MySQL community (GPL) Downloads

3. Choose MySQL Installer for windows

4. Choose larger file to download(435 or above MB)

5. Choose No thanks , just start my download.

6. After that download Install the MySQL

7. Choose the setup type  Custom  Next

8. Select Products Available products  MySQL Server (choose server


Latest product)  After choose move to the Product to be installed.
9. Select Product Available Product Applications  MySQL
Workbench  Move to the Product to be installed.

10. Select Product  Available Product  MySQL Shell  Move to the


product to be installed Next

11. Installation  Execute Next

12. Product Configure  Next


 Type and Networking  Next
 Authentication Method  Next
 Accounts and Roles  set a password (user name: root)
Default.  Next
 Windows Service  Next
 Apply configuration Execute  Finish  Next

13. Don’t click Finish

14. In C drive  program files MySQL  mysql server (choosed


version)bin (copy that file path of the C folder)
15. In search option Search  Edit the System Environment Variable 
Environment variable system variables  path(double click)  New
 paste ok  ok  ok

16. Finish

17. Open Commend prompt  type mysql –version


type mysql –u root –p
Enter password:*********

18. If you don’t get any error you successfully installed mysql
workbench
If you get that in output you Successfully Connected to the database.
2. Given any name

3. Select the option

4. Click ok
1. Click the + symbol
New connection folder
is Created
CREATE DATABASE:

SHOW DATABASE:
CREATE TABLE:

SHOW TABLE:
Run the python program

Use your database name and Click


the Thunder symbol to run
After that type that two lines and click the Thunder Symbol to Run
Commit() is used to Reflect the changed data in the
database.
Refresh and click the
Thunder button
SELECTING AND GETTING DATA:
WHERE AND LIKE:
UPDATE AND LIMIT:
We can also use ORDERBY age
also and DESC

Descending
DELETE:
rollback() method updated name and age
is not printed in database
THREADS ESSENTIAL:
REGULAR EXPRESSION
DATE AND TIME:

import datetime
X=datetime.datetime.no
w()
Print(X)
Print(X.year)
Print(X.strftime(“%a”))

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy