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

Python

Python is a high-level, interpreted programming language known for its readability and simplicity, created by Guido van Rossum in 1991. It supports multiple programming paradigms, is platform-independent, and is widely used in various fields such as data science, web development, and artificial intelligence. Key features include easy learning, extensive libraries, and a flexible syntax that allows for quick prototyping.

Uploaded by

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

Python

Python is a high-level, interpreted programming language known for its readability and simplicity, created by Guido van Rossum in 1991. It supports multiple programming paradigms, is platform-independent, and is widely used in various fields such as data science, web development, and artificial intelligence. Key features include easy learning, extensive libraries, and a flexible syntax that allows for quick prototyping.

Uploaded by

akilakarthi2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 81

PYTHON

what is python:-
Python is a powerful high level language. Python is clearly defined and easily
readable. The Structure of the program is very simple. It uses few keywords. It was
created by Guido van Rossum, and released in 1991.

Why the name python?


The name "python" was adopted from the same series "Monty python's Flying
Circus".

Why Python?
Python works on cross platforms (Windows, Mac, Linux, Raspberry Pi, etc).

Python has a simple syntax similar to the English language.

Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.

Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.

Python can be treated in a procedural way, an object-oriented way or a functional way.


Python is platform independent:-
Python programs are platform independent because they can be run on
different platforms using PVM (Python Virtual Machine) built specifically for that
platform. Just like java(JVM), Python programs can be run on different platforms
using PVM built for that platform.

PVM converts the python byte code into machine executable code.

Features Of Python Programming:-


* Easy to learn.

* Free and open source.

* A high-level, interpreted language.

* Large standard libraries to solve common tasks.

* object-Oriented.

Uses of Python:-
o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions

Advantages of Python:-
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).

• Python has a simple syntax similar to the English language.

• Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.

• Python runs on an interpreter system, meaning that code can be executed as


soon as it is written. This means that prototyping can be very quick.

• Python can be treated in a procedural way, an object-oriented way or a


functional way.

Python download and install:-


Every Release of Python is open-source. Any version of Python can be
downloaded from Python Software Foundation website at https://www.python.org/.

To check if you have python installed on a Windows PC, search in the start
bar for Python or run the following on the Command Line (cmd.exe)

C:\Users\python
Run the program:-
Python is an interpreted programming language, this means that as a developer you

write Python (.py) files in a text editor and then put those files into the python
interpreter to be execute.

1) Write your program in editor or IDE.

2) Save file name as Filename.py extension.

3) Run the program in CMD as,

C:\Users\python Filename.py

Variables:-
Variables are containers for storing data values. It is memory location to store
the given data. Python has no command for declaring a variable. A variable is created
the moment you first assign a value to it.

For eg:

x = 5 # its integer variable

y = "John" # its string variable

Data types:-
Built-in-data types:
Data types are the classification or categorization of data items. It represents the
kind of value.

Python has the following data types built-in by default, in these categories:

Text Type : str x=“hello python”

Numeric Types : int, x=3

float, y=3.5

Sequence Types : list, X=[“banana”,”apple”,”cherry”]

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

range x=range(6)

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

Set Types : set, x={“apple”,”banana”,”cherry”}

frozenset x = frozenset({"apple", "banana",


"cherry"})

Boolean Type : bool (true,false)

Binary Types : bytes, bytearray, memoryview

Extensible:-

programming can embbed python within their c, c++, java script, Activex, etc,.

Interactive mode:-

Interactive mode is where you type commands and they are immediately executed.
>>>print("Csc computer education")

Csc computer education

Script mode:-

Script mode is where you write your code in a .py file and then run it with the python
command. This is the most common way that people use Python because it lets you
write and save your code so that you can use it again later.

Interpreter Language:-

* No Intermediate object code is Generated.

* Errors are displayed for every instruction interpreted (if any).

Python syntax:-

print("Csc Computer Education!")

Input and Output functions:-

Output function:

Eg, 1) print(“hello python”)

2) x=3

y=”john”

print(x)

print(y)
Input function:-

Python allows for user input.

That means we are able to ask the user for input.

Python uses the input() method to get the input from the users.

Eg, 1) username=input(“enter your name”)

print(username)

2) username=input(“enter your name”)

print(“username is ”+username)

3) x=int(input(“enter the x value”))

Y=int(input(“enter the y value”))

Z=x+y

Print(z)

Comments:-

A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # are part of the comment and the Python interpreter ignores them.

Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

For eg:

#This is a single line comment

print(“welcome to python”)
Multiline comments:-

Python does not really have a syntax for multi line comments.

To add a multiline comment you could insert a # for each line:

For eg:

#This is a comment

#written in

#more than just one line

print("Csc Computer Education!")

Basic programs of python:

1) x, y, z = "Orange", "Banana", "Cherry"

print(x)

print(y)

print(z)

2) x = y = z = "Orange"

print(x)

print(y)

print(z)
3) fruits = ["apple", "banana", "grapes"]

x, y, z = fruits

print(x)

print(y)

print(z)

4) x=4

y=3.6

z=7j

print(x)

print(y)

print(z)

print(type(x))

print(type(y))

print(type(z)) #type() is a predefined function to print the data type

#This is a single line comment

print(“welcome to python”)

print(“Csc Computer Education!") #This is a function to print.

Type casting:-
Type Casting is the method to convert the variable data type into a certain data
type in order to the operation required to be performed by users.

Ex:- x=float(1)

y=int(3.8)

z=str(4)

print(x)

print(y)

print(z)

Operators:-

Python divides the operators in the following groups:

• Arithmetic operators

• Assignment operators

• Comparison operators

• Logical operators

• Identity operators

• Membership operators

• Bitwise operators

Arithmetic operators:-

Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example

+ Addition x + y [x=7, y=3 print(x+y)]

- Subtraction x – y [x=7, y=3 print(x-y)]

* Multiplication x * y [x=7, y=3 print(x*y)]

/ Division x / y [x=7, y=3 print(x/y)]

% Modulus x % y [x=7, y=3 print(x%y)]

** Exponentiation x ** y[x=7, y=3 print(x**y)]

// Floor division x // y [x=7, y=3 print(x//y)]

Assignment operators:-

“ =” “//=”

x=3 x=7

print(x) x//=3 print(x)

“+=” “**=”

x=7 x=7

x+=3 x**=3

print(x) #that’s mean x=x+3 print(x)

“-=” “&=”
x=7 x=7

x-=3 x&=3

print(x) print(x)

“*=” “|=”

x=7 x=7

x*=3 x|=3

print(x) print(x)

“/=” “^=”

x=7 x=7

x/=3 x^=3

print(x) print(x)

“%=” “>>=” “<<=”

x=7 x=7 x=7

x%=3 x>>=3 x<<=3

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

Comparison operator:- (Relational operator)

Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y [x=7, y=7 print(x==y)]

!= Not equal x != y [x=7,y=3 print(x!=y)]

> Greater than x>y [x=7,y=3 print(x>y)]

< Less than x<y [x=7, y=3 print(x<y)]

>= Greater than or equal to x >= y [x=7, y=3 print(x>=y)]

<= Less than or equal to x <= y [x=7, y=3 print(x<=y)]

Logical operators:-

Logical operators are used to combine conditional statements:

“and”

Ex;-

x=5

print(x>3 and x<7) #Returns True if both statements are true

“Or”

Ex:-

x=5

print(x>7 or x<3) #Returns True if one of the statements is true

“not”

Ex:-

x=5
print (not(x>7 and x<3)) #Reverse the result, returns False if the result is true

Identity operators:-

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:

“is”

x=”Csc computer education”

y=”computer”

z=y

print(x is y) #returns False because x is not the same object as y, even if they have
the same content

print(z is y)

“is not”

x=”Csc computer education”

y=”computer”

print(x is not y) #Returns True if both variables are not the same object

Membership operator:-

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

“in”

x=”csc computer”
print(“computer” in x) #Returns True if a sequence with the specified value
is present in the object

“not in”

x=”csc computer”

print(“Csc” not in x) #Returns True if a sequence with the specified value is


not present in the object

Bitwise operator:-

Bitwise operators are used to compare (binary) numbers:

& AND Sets each bit to 1 if both bits are 1

Ex:

a=10, b=7

c=a&b

print(c)

| OR Sets each bit to 1 if one of two bits is 1

Ex:

a=10, b=7

c=a|b

print(c)

^ XOR Sets each bit to 1 if only one of two bits is 1

Ex:-
a=10, b=7

c=a^b

print(c)

~ NOT Inverts all the bits

One’s complement of a member A is equal to (A+1)

Ex:-

a=7, b=~a

print(b)

<< Zero fill left shift Shift left by pushing zeros in from the right and let the
leftmost bits fall off

Ex:-

a=10

print(a<<2)

>> Signed right shift Shift right by pushing copies of the leftmost bit in from the
left, and let the rightmost bits fall off

Ex:

a=10

print(a>>2)

Escape characters:-
An escape character is a backslash \ followed by the character you want to
insert.

Ex:-

txt = "We are the so-called \"Vikings\" from the north."

print(txt)

Other escape characters used in Python:

Code Result

\' Single Quote

\\ Backslash

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

Python Control Structures:-

 Conditional
 UnConditional

Conditional statement  Control statements are used to control the flow of the
execution of the loop based on a condition.

Type of conditional statement:-

 Branching  if(Conditional), if..else(alternative), if...elif..else(chained


conditional), nested if
 Looping for, while, for...else, while...else
Indentation:-

Python relies on indentation (whitespace at the beginning of a line) to define


scope in the code. Other programming languages often use curly-brackets for this
purpose. [:]

Syntax: if expression:
statement
Ex:-

x=3

y=5

if x==y:

print(“x is equal to y”)

If statements:-

A Python if statement evaluates whether a condition is equal to true or false.


The statement will execute a block of code if a specified condition is equal to true.
Otherwise, the block of code within the if statement is not executed.

Ex:-

a = 33

b = 200

if b > a:

print("b is greater than a")

elif statements:-
The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition".

Ex:-

a = 33

b = 33

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")

else statements:-

The else keyword executed anything which isn't executed by the preceding
conditions.

Syntax: if condition:
#block of statements
else:
#another block of statements (else-block)
Ex:-

a = 20

b = 33

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")

Nested if:-

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

num=15

if num>=0:

if num==0:

Print(“zero”)

else:

print(“Positive number”)

else:

print(“Negative number”)

Looping in python:-

Looping means repeating something over and over until a particular condition is
satisfied.

Python has two primitive loop commands:

• while loops
• for loops

While loop:-

A while loop is a control flow statement which allows code to be executed


repeatedly, depending on a condition. It stops executing the block if and only if the
condition fails.

Ex:-

i=1

while i < 6: # to print the numbers from 1 to 5

print(i)

i += 1 # i=i+1

For loops:-

A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).With the for loop we can execute a set of statements, once
for each item in a list, tuple, set etc.

Ex:- 1) fruits = ["apple", "banana", "grapes"]

for x in fruits:

print(x)

2) for x in "banana":

print(x)

For else:-

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!)

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.

 for x in range(6):

print(x)

 for x in range(2, 6):

print(x)

The range() function defaults to increment the sequence by 1, however it is possible to


specify the increment value by adding a third parameter: range(2, 30, 3):

Ex:- for x in range(2, 30, 3):

print(x)

Unconditional statement Python has various types of loop functions like for and
while. These loops are automatic and efficiently repeats the tasks. But sometimes,
where you want to exit the loop completely, skip an iteration or ignore that condition.
These can be done by unstructured loop control statements.

 Break
 Continue
 pass
Break:-

The break statement terminates the loop.

Ex:-

for i in “python”:

if i==”h”:

break

print(“Letter: “,i)

Continue:-

The loop to skip the remainder of its body and immediately retest its condition prior
to reiterate.

Ex:-

for i in “python”:

if i==”h”:

continue

print(“letter: “,i)

Pass:-

Pass statements is a null operation. Nothing happens when it executes.

Ex:-

for i in “python”:

pass
print(“finished”)

Array:-

Arrays are used to store multiple values in one single variable. An array is a
collection of items stored at contiguous memory locations. Python does not have built-
in support for Arrays, but Python Lists can be used instead.

An array can hold many values under a single name, and you can access the values by
referring to an index number.

String function:-

Strings(immutable) in python are surrounded by either single quotation marks,


or double quotation marks.

Ex:- “welcome”,”3”,”4.7”,”python”

#Using single quotes


str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)

#Using triple quotes


str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
print(str3)
Strings as array:

a = “csc computer education!"

print(a[1])

Looping through string:

for x in "banana":

print(x)

Indexing :-

Accessing elements in string each element is accessed using indexing. The position of
each character.

Indexing

Forward Indexing Backward Indexing

(positive) (Negative)

For Ex:-

Str = ”PYTHON”

0 1 2 3 4 5

P Y T H O N

-6 -5 -4 -3 -2 -1

Str[0]=’P’

Str[1]=’Y’
Str[2]=’T’

Str[3]=’H’

Str[4]=’O’

Str[5]=’N’

String length:

a = "csc computer education!"

print(len(a)) #len() is a predefined method(function)to count the string


length

String operators:-

+ (Concatenation operation)

Basic operators

* (replication operation)

Concatenation operation:
Concatenate two strings and forms new string.
Ex:-

a = "csc"

b = "computer education"

c=a+b

print(c)

Replication Operation:
The string will be repeated the number of time which is given by the integer
value.

Ex:-
a=”python” *5

print(a)

Slicing the string:

Slicing the string is done by using the indexing.

Syntax:-

<stringa_name>[start index:end index]

1. b = "Csc Computer Education!" #Get the character from index 2 to 4(5 not
include)

print(b[2:5])

2. b = " Csc Computer Education!" #It refers only the end index

print(b[:5]) #Likewise also we can use starting index


3. b = " Csc Computer Education!" #It takes the value from reverse index but
not included 0

print(b[-5:-2]) #It refers negative indexing

String methods:-

upper() Returns the string in uppercase

lower() Returns the string in lowercase

strip() Removes the whitespace in string

replace() Replace the string with other string

split() Split the string using a separator in the string

Ex:- ”Computer, Education”

Separator ‘,’,’m’,’u’

The format() method

The format() method is the most flexible and useful method in formatting strings. The
curly braces {} are used as the placeholder in the string and replaced by
the format() method argument.

Ex:-

# Using Curly braces


print("{} and {} both are the best friend".format("Devansh","Abhishek"))

#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))
#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ricky"))

Python String Formatting Using % Operator

Integer = 10;
Float = 1.290
String = "Devansh"
print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am st
ring ... My value is %s"%(Integer,Float,String))

List in python:-

Lists are used to store multiple items in a single variable. Lists are one of 4 built-in
data types in Python used to store collections of data.

Ex:-

 thislist = ["apple", "banana", "grape"]


print(thislist)
 2) list1 = ["abc", 34, True, 40, "male"]
 List items are ordered, changeable, and allow duplicate values.
 List items are indexed, the first item has index [0] and so on.
 If you add new items to a list, the new items will be placed at the end of the
list(ordered).
 we can change, add, and remove items in a list after it has been
created(changable).
 thislist = ["apple", "banana", "grapes", "apple", "grapes"]
print(thislist) #allow duplicates
 List items are indexed and you can access them by referring to the index
number.
Change the list items:

1) thislist = ["apple", "banana", "grapes"]

thislist[1] = "blackcurrant"

print(thislist)

2) The insert() method inserts an item at the specified index.

thislist = ["apple", "banana", "grapes"]

thislist.insert(1, "orange")

print(thislist)

3) The append() method used to add items in the end of the list.

thislist = ["apple", "banana", "grapes"]

thislist.append("orange")

print(thislist)

4) The extend() method is used to append elements from another list to current list.

thislist = ["apple", "banana", "grapes"]

tropical = ["mango", "pineapple", "papaya"]

thislist.extend(tropical)

print(thislist)

Remove list items:-


The remove() method removes the specified item.

thislist = ["apple", "banana", "grapes"]

t hislist.remove("banana")

print(thislist)

The pop() method removes the specified index. The del keyword also removes
the specified index.

thislist = ["apple", "banana", "grapes"]

thislist.pop(1)

print(thislist)

If you do not specify the index, the pop() method removes the last item.

thislist = ["apple", "banana", "grapes"]

thislist.pop()

print(thislist)

The del keyword can also delete the list completely.

thislist = ["apple", "banana", "grapes"]

del thislist

Looping in lists:

1) thislist = ["apple", "banana", "grapes"]

for x in thislist:

print(x)

2) thislist = ["apple", "banana", "grapes"]


[print(x) for x in thislist]

Join list:-

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

list2 = [1, 2, 3]

list3 = list1 + list2

print(list3)

Python List Operations

The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are

1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership

1. Repetition

The repetition operator enables the list elements to be repeated multiple times.

# repetition of list
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
2. Concatenation

It concatenates the list mentioned on either side of the operator.

# concatenation of two lists


# declaring the lists
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)

3. Length

It is used to get the length of the list

# size of the list


# declaring the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
# finding length of the list
len(list1)

4. Iteration

The for loop is used to iterate over the list elements.

# iteration of the list


# declaring the list
list1 = [12, 14, 16, 39, 40]
# iterating
for i in list1:
print(i)
5. Membership

It returns true if a particular item exists in a particular list otherwise false.

# membership of the list


# declaring the list
list1 = [100, 200, 300, 400, 500]
# true will be printed if value exists
# and false if not

print(600 in list1)
print(700 in list1)
print(1040 in list1)

print(300 in list1)
print(100 in list1)
print(500 in list1)

Iterating a List

A list can be iterated by using a for - in loop. A simple list containing four strings,
which can be iterated as follows.

# iterating a list
list = ["John", "David", "James", "Jonathan"]
for i in list:
# The i variable will iterate over the elements of the List and contains each element i
n each iteration.
print(i)
Python List Built-in Functions

Python provides the following built-in functions, which can be used with the lists.

1. len()
2. max()
3. min()

len( )

It is used to calculate the length of the list.

# size of the list


# declaring the list
list1 = [12, 16, 18, 20, 39, 40]
# finding length of the list
len(list1)

Max( )

It returns the maximum element of the list

# maximum of the list


list1 = [103, 675, 321, 782, 200]
# large element in the list
print(max(list1))

Min( )

It returns the minimum element of the list

# minimum of the list


list1 = [103, 675, 321, 782, 200]
# smallest element in the list
print(min(list1))

Build-in lists methods:-

Method Description

append()

Adds an element at the end of the list

clear()

Removes all the elements from the list

copy()

Returns a copy of the list

count()

Returns the number of elements with the specified value

extend()

Add the elements of a list (or any iterable), to the end of the current list

index()

Returns the index of the first element with the specified value

insert()

Adds an element at the specified position

pop()

Removes the element at the specified position


remove()

Removes the item with the specified value

reverse()

Reverses the order of the list

sort()

Sorts the list

Tuple in python:-

Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-
in data types in Python used to store collections of data.

Ex:- 1)thistuple = ("apple", "banana", "grapes")

print(thistuple)

2)tuple1 = ("abc", 34, True, 40, "male")

Print(tuple1)

 A tuple is a collection which is ordered and unchangeable.

 Tuple items are indexed, the first item has index [0], the second item has index
[1] so on.

 Tuple items are ordered, unchangeable, and allow duplicate values.

 Tuples are ordered that means the items have a defined order, and that order
will not change.

 Tuples are unchangeable, meaning that we cannot change, add or remove items
after the tuple has been created.

 thistuple = ("apple", "banana", "grapes", "apple", "grapes")


print(thistuple) #allow duplicate values

 You can access tuple items by referring to the index number.

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

print(thistuple[1]) #access by negative index and range of indexes

Change in tuple:-

 Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.

 But tuple items can be change by convert the tuple into list.

1) x = ("apple", "banana", "grapes")

y = list(x)

y[1] = "kiwi"

x = tuple(y)

print(x)

Add items to a tuple:

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

y = list(thistuple)

y.append("orange")

thistuple = tuple(y)

Add tuple to tuple:


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

y = ("orange")

thistuple += y # thistuple = thistuple+y

print(thistuple)

Tuples are unchangeable, so you cannot remove items from it like add items remove
is also done by convert the tuple into list.

Remove an item from tuple:

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

y = list(thistuple)

y.remove("apple")

thistuple = tuple(y)

Delete the tuple:

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

del thistuple

Unpacking a tuple:

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

(red, yellow, purple) = fruits

print(red)

print(yellow)

print(purple)
An asterisk in tuple:-

If the number of variables is less than the number of values, you can add an
*(asterisk) to the variable name and the values will be assigned to the variable as a list.

fruits = ("apple", "banana", "grapes", "strawberry", "raspberry")

(red, yellow, *purple) = fruits

print(red)

print(yellow)

print(purple)

Looping in tuple:-

 thistuple = ("apple", "banana", "grapes")

for x in thistuple:-

print(x)

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

i=0

while i < len(thistuple): # while loop in tuple

print(thistuple[i])

i=i+1

Join tuple:-

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

tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2

print(tuple3)

Built in tuple methods:

Method Description

count()

Returns the number of times a specified value occurs in a tuple

index()

Searches the tuple for a specified value and returns the position of where it was found

Sets in python:-

Sets are used to store multiple items in a single variable.Set is one of 4 built-in
data types in Python used to store collections of data.

Ex:- 1) thisset = {"apple", "banana", "grapes"}

print(thisset)

2) set1 = {"abc", 34, True, 40, "male"}

 Set items are unordered, unchangeable, and do not allow duplicate values.

 Unordered means that the items in a set do not have a defined order.Set items
can appear in a different order every time you use them, and cannot be referred to by
index or key.

 Set items are unchangeable, meaning that we cannot change the items after the
set has been created.

 Sets cannot have two items with the same value.


Ex:- thisset = {"apple", "banana", "grapes", "cherry"}

print(thisset)

Access set items:-

You cannot access items in a set by referring to an index or a key.But you can loop
through the set items using a for loop, or ask if a specified value is present in a set, by
using the in keyword.

 thisset = {"apple", "banana", "grapes"}

for x in thisset:

print(x)

Changing items in set:-

1) thisset = {"apple", "banana", "grapes"}

thisset.add("orange")

print(thisset) # to add one item to a set use add() method.

2) thisset = {"apple", "banana", "grapes"}

tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical) #to add items from another set into current set use update()

print(thisset)

Removing set items:-

1) thisset = {"apple", "banana", "grapes"}

thisset.remove("banana") # to remove item in a set use remove() method.

print(thisset)

2) thisset = {"apple", "banana", "grapes"}

thisset.discard("banana") # to remove item in a set use discard() method.


print(thisset)

3) thisset = {"apple", "banana", "grapes"}

thisset.clear() # to empty the use clear() method.

print(thisset)

4) thisset = {"apple", "banana", "grapes"}

del thisset # delete keyword delete the set.

print(thisset)

Join sets:-

You can use the union() method that returns a new set containing all items from
both sets, or the update() method that inserts all the items from one set into another.

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

set2 = {1, 2, 3}

set3 = set1.union(set2)

print(set3)

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

set2 = {1, 2, 3}

sent3=set1.update(set2)

print(set1)

Built in Set methods:-

Method Description
add()

Adds an element to the set

clear()

Removes all the elements from the set

copy()

Returns a copy of the set

difference()

Returns a set containing the difference between two or more sets

difference_update()

Removes the items in this set that are also included in another, specified set

discard()

Remove the specified item

intersection()

Returns a set, that is the intersection of two other sets

intersection_update()

Removes the items in this set that are not present in other, specified set(s)

isdisjoint()

Returns whether two sets have a intersection or not

issubset()

Returns whether another set contains this set or not

issuperset()

Returns whether this set contains another set or not


pop()

Removes an element from the set

remove()

Removes the specified element

symmetric_difference()

Returns a set with the symmetric differences of two sets

symmetric_difference_update()

inserts the symmetric differences from this set and another

union()

Return a set containing the union of sets

update()

Update the set with the union of this set and others

Python Dictionaries:-

Dictionaries are used to store data values in key:value pairs. Dictionaries are
written with curly bracket and have keys and values.

Ex:- thisdict = { key : values

"brand": "Ford",

"model": "Mustang", immutable mutable

"year": 1964

print(thisdict)
 Dictionary items are ordered, changeable, and does not allow duplicates.

 Dictionaries are ordered, it means that the items have a defined order, and that
order will not change.

 Dictionaries are changeable, meaning that we can change, add or remove items
after the dictionary has been created.

 Dictionaries cannot have two items with the same key.

Ex:- thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964,

"year": 2020

print(thisdict)

Access items in dictionaries:-

1)You can access the items of a dictionary by referring to its key name, inside
square brackets.

 thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = thisdict["model"]

 x = thisdict.get("model") # get() is another method to get same output.


Change items in dictionaries:-

1) You can change the value of a specific item by referring to its key name.

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict["year"] = 2018

2) The update() method will update the dictionary with the items from the given
argument.The argument must be a dictionary, or an iterable object with key:value
pairs.

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict.update({"year": 2020})

Add items in dictionaries:-

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

Ex:- thisdict = {
"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict["color"] = "red"

print(thisdict)

Remove items in dictionaries:-

1) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict.pop("model") #pop() method removes the item with specified key

print(thisdict)

2) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict.popitem() #popitem() method removes the last inserted item

print(thisdict)
3) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

del thisdict["model"] #delete keyword removes items in specified key

print(thisdict)

4) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

thisdict.clear() #clear() method empties the dictionaries

print(thisdict)

Looping in dictionaries:-

1) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict: # to print all key names in dictionary


print(x)

2) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict: # to print all values in dictionary

print(thisdict[x])

3) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict.values(): #values() method to return values

print(x)

4) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict.keys(): #keys() method to return keys

print(x)
5) thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x, y in thisdict.items(): #item() method to return both key&value

print(x, y)

Built in dictionaries methods:-

Method Description

clear()

Removes all the elements from the dictionary

copy()

Returns a copy of the dictionary

fromkeys()

Returns a dictionary with the specified keys and value

get()

Returns the value of the specified key

items()

Returns a list containing a tuple for each key value pair

keys()

Returns a list containing the dictionary's keys


pop()

Removes the element with the specified key

popitem()

Removes the last inserted key-value pair

setdefault()

Returns the value of the specified key. If the key does not exist: insert the key, with
the specified value

update()

Updates the dictionary with the specified key-value pairs

values()

Returns a list of all the values in the dictionary

Python function:-

A function is a block of code which only runs when it is called. You can pass data,
known as parameters, into a function. A function can return data as a result.

Ex:- def my_function():

print("Hello from a function")

Advantages of Functions in Python:-

Python functions have the following Perks.

o By including functions, we can prevent repeating the same code block


repeatedly in a program.
o Python functions, once defined, can be called many times and from anywhere in
a program.
o If our Python program is large, it can be separated into numerous functions
which is simple to track.
o The key accomplishment of Python functions is we can return as many outputs
as we want with different arguments.

Calling the function:-

1. def my_function():

print("Hello from a function")

my_function() #function name followed by parenthesis is used to calling.

2. # Defining a function
def a_function( string ):
#This prints the value of length of string
return len(string)

# Calling the function we defined


print( "Length of the string Functions is: ", a_function( "Functions" ) )
print( "Length of the string Python is: ", a_function( "Python" ) )

Defining a function with parameter:-

Syntax:-

def <function_name>([parameters])
Ex:-

def add(a,b)

c=a+b

print(c)

add(5,6)

1.local variable

2.global variable

Local variable:

Variables declared inside a function body is known as local variable.

Ex:-

def a() #local variable

a=”Ravanan”

print(a)

a()

Ex:-

def msg()

a=10 #local variable (‘value of a is’,a).

Print(a)

msg()

print(a) #it will show error since variable is local.


Global variable:

Variable defined outside the function is called global variable.

Ex:-

def msg()

print(“inside Function”,r)

r=”Manikutty”

msg()

print(“outside Function”,r)

Types of functions in python:

1.Built-in functions (also called as predefined).

2. User-defined.

Buil-in(Predefine)

Functions that are predefined. We have many predefined functions in python.

Ex:- Python Package and Library min(), max(), count(), index(a,b)......lower(a),


upper(a)...etc...

User-defined:-

Function that are created according to the requirements .

Ex:- Developers write to meet certain requirements.


Function Arguments

The following are the types of arguments that we can use to call a function:

 Positional argument
 Default argument
 Key word argument
 Arbitrary argument

1. positional argument (Required argument)

Ex:- def sum(a,b): #function having two parameters.

c=a+b

print(c)

sum(10,20)

sum(20) (so, the number a parameter in the function call should match with be
number of parameter in this function definition)

2. Default argument

Ex:-

#function definition

def msg(Id,Name,Age=21):

#printing the passed valued

Print(Id)

Print(Name)

Print(Age)

return
#function call

msg(Id=100,Name=”Arun”,Age=20)

msg(Id=101,Name=”Raj”)

3. Keyword argument (Named argument)

Ex:-

def msg(Id,Name):

#printing passed value

Print(Id)

Print(Name)

msg(Id=1000,Name=”Mani”)

msg(Name=”veera”,Id=1001)

4. Arbitrary argument (Variable length argument)

Ex:-

def greetings(*friends):

for greeting in friends:

print("hi",friends)

greetings("mani","marish","karthika","mathika")

FUNCTION PROTOTYPES

1. Function without arguments and without return type.

2. Function with arguments and without return type.

3. Function without argument with return type.


4. Function with argument and with return type.

WITHOUT RETURN TYPE


WITHOUT ARGUMENT WITH ARGUMENT
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) print(c)
c=a+b a=int(input("enter a"))
print(c) b=int(input("enter b"))
add() add(a,b)

WITH RETURN TYPE


WITHOUT ARGUMENT WITH ARGUMENT
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) return c
c=a+b a=int(input("enter a"))
return c b=int(input("enter b"))
x=add() x=add(a,b)
print(x) print(x)

Anonymous Functions:-

A lambda function is a small anonymous function. A lambda function can take

any number of arguments, but can only have one expression. Anonymous function are

created by using a keyword “Lambda”.

Rules for lambda function:-

1. They can take many number of argument.

2. It returns only one value in the form of expression.


3. Lambda function are single line function.

Syntax:

lambda [argument1 [,argument2... .argumentn]] : expression

Ex:- 1) x = lambda a : a + 10

print(x(5))

2) x = lambda a, b : a * b

print(x(5, 6))

3) x = lambda a, b, c : a + b + c

print(x(5, 6, 2))

Ex:-
# Defining a function
lambda_ = lambda argument1, argument2: argument1 + argument2;

# Calling the function and passing values


print( "Value of the function is : ", lambda_( 20, 30 ) )
print( "Value of the function is : ", lambda_( 40, 50 ) )

Python Function within Another Function

# Python code to show how to access variables of a nested functions


# defining a nested function
def word():
string = 'Python functions tutorial'
x=5
def number():
print( string )
print( x )

number()
word()

Python sum() Function

As the name says, python sum() function is used to get the sum of numbers of an
iterable, i.e., list.

Python sum() Function Example

s = sum([1, 2,4 ])
print(s)

s = sum([1, 2, 4], 10)


print(s)

Recursive function:-

Recursion is the process of defining something in terms of itself.

Best ex: (factorial & Fibonacci)

Def fact(n):

if n==1:

return 1

else:

return(n*fact(n-1))
num=5

print(“the factorial of”,num,”is”,fact(num))

Lambda function with function:-

Ex:- 1) def myfunc(n): # n is a function argument

return lambda a : a * n # a is a lambda function argument

mydoubler = myfunc(2) # 2 is a argument for function

print(mydoubler(11)) # 11 is a argument for lambda function

2) def myfunc(n):

return lambda a : a * n

mydoubler = myfunc(2)

mytripler = myfunc(3)

print(mydoubler(11))

print(mytripler(11))

Python OOPs Concepts:-

Like other general-purpose programming languages, Python is also an object-oriented


language since its beginning. It allows us to develop applications using an Object-
Oriented approach. In Python, we can easily create and use classes and objects.

o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation

Class

The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it
should contain an attribute and method, i.e. an email id, name, age, salary, etc.

Syntax

class ClassName:
<statement-1>
.
.
<statement-N>

Object

The object is an entity that has state and behavior. It may be any real-world object like
the mouse, keyboard, chair, table, pen, etc.

Everything in Python is an object, and almost everything has attributes and methods.
All functions have a built-in attribute __doc__, which returns the docstring defined in
the function source code.

Example:

class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)

c1 = car("Toyota", 2016)
c1.display()

Method

The method is a function that is associated with an object. In Python, a method is not
unique to class instances. Any object type can have methods.

Inheritance

Inheritance is the most important aspect of object-oriented programming, which


simulates the real-world concept of inheritance. It specifies that the child object
acquires all the properties and behaviors of the parent object.

Example:-

# Python code to demonstrate how parent constructors

# are called.

# parent class

class Person(object):

# __init__ is known as the constructor


def __init__(self, name, idnumber):

self.name = name

self.idnumber = idnumber

def display(self):

print(self.name)

print(self.idnumber)

def details(self):

print("My name is {}".format(self.name))

print("IdNumber: {}".format(self.idnumber))

# child class

class Employee(Person):

def __init__(self, name, idnumber, salary, post):

self.salary = salary

self.post = post

# invoking the __init__ of the parent class

Person.__init__(self, name, idnumber)

def details(self):

print("My name is {}".format(self.name))

print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))

# creation of an object variable or an instance

a = Employee('Rahul', 886012, 200000, "Intern")

# calling a function of the class Person using

# its instance

a.display()

a.details()

Polymorphism

Polymorphism contains two words "poly" and "morphs". Poly means many, and
morph means shape. By polymorphism, we understand that one task can be performed
in different ways. For example - you have a class animal, and all animals speak. But
they speak differently. Here, the "speak" behavior is polymorphic in a sense and
depends on the animal. So, the abstract "animal" concept does not actually "speak",
but specific animals (like dogs and cats) have a concrete implementation of the action
"speak".

Example:-

class Bird:

def intro(self):

print("There are many types of birds.")

def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):

def flight(self):

print("Sparrows can fly.")

class ostrich(Bird):

def flight(self):

print("Ostriches cannot fly.")

obj_bird = Bird()

obj_spr = sparrow()

obj_ost = ostrich()

obj_bird.intro()

obj_bird.flight()

obj_spr.intro()

obj_spr.flight()

obj_ost.intro()

obj_ost.flight()

Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to
restrict access to methods and variables. In encapsulation, code and data are wrapped
together within a single unit from being modified by accident.

Example:-

# Python program to

# demonstrate private members

# Creating a Base class

class Base:

def __init__(self):

self.a = "GeeksforGeeks"

self.__c = "GeeksforGeeks"

# Creating a derived class

class Derived(Base):

def __init__(self):

# Calling constructor of

# Base class

Base.__init__(self)

print("Calling private member of base class: ")

print(self.__c)

# Driver code

obj1 = Base()

print(obj1.a)
# Uncommenting print(obj1.c) will

# raise an AttributeError

# Uncommenting obj2 = Derived() will

# also raise an AtrributeError as

# private member of base class

# is called inside derived class

Data Abstraction

Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation. Abstraction is
used to hide internal details and show only functionalities. Abstracting something
means to give names to things so that the name captures the core of what a function or
a whole program does.

Classes and Objects

Creating Classes in Python

In Python, a class can be created by using the keyword class, followed by the class
name

class Employee:
id = 10
name = "Arunraj"
def display (self):
print(self.id,self.name)
Creating Objects (instance) in Python

A class needs to be instantiated if we want to use the class attributes in another class or
method. A class can be instantiated by calling the class using the class name

<object-name> = <class-name>(<arguments>)

class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
# Creating a emp instance of Employee class
emp = Employee()
emp.display()

Delete the Object

We can delete the properties of the object or object itself by using the del keyword.

Example

class Employee:
id = 10
name = "John"

def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
# Creating a emp instance of Employee class

emp = Employee()

# Deleting the property of object


del emp.id
# Deleting the object itself
del emp
emp.display()

Python Constructor

A constructor is a special type of method (function) which is used to initialize the


instance members of the class.

In C++ or Java, the constructor has the same name as its class, but it treats constructor
differently in Python. It is used to create an object.

Constructors can be of two types.

1. Parameterized Constructor
2. Non-parameterized Constructor

Creating the constructor in python

In Python, the method the __init__() simulates the constructor of the class. This
method is called when the class is instantiated. It accepts the self-keyword as a first
argument which allows accessing the attributes or method of the class.

We can pass any number of arguments at the time of creating the class object,
depending upon the __init__() definition. It is mostly used to initialize the class
attributes. Every class must have a constructor, even if it simply relies on the
default constructor.

Example
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name

def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))

emp1 = Employee("John", 101)


emp2 = Employee("David", 102)

# accessing display() method to print employee 1 information

emp1.display()

# accessing display() method to print employee 2 information


emp2.display()

Counting the number of objects of a class

The constructor is called automatically when we create the object of the class.
Consider the following example.

Example

class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)

Python Non-Parameterized Constructor

The non-parameterized constructor uses when we do not want to manipulate the value
or the constructor that has only self as an argument.

class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")

Python Parameterized Constructor

The parameterized constructor has multiple parameters along with the self.

class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()
Python Default Constructor

When we do not include the constructor in the class or forget to declare it, then that
becomes the default constructor. It does not perform any task but initializes the
objects.

class Student:
roll_num = 101
name = "Joseph"

def display(self):
print(self.roll_num,self.name)

st = Student()
st.display()

Python Inheritance

Syntax
class derived-class(base class):
<cl ass-suite>

class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()

Python Multi-Level inheritance

Multi-level inheritance is archived when a derived class inherits another derived class.
There is no limit on the number of levels up to which, the multi-level inheritance is
archived in python.

Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>

Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()

Python Multiple inheritance

Python provides us the flexibility to inherit multiple base classes in the child class.
Syntax

class Base1:
<class-suite>

class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... BaseN):


<class-suite>

Example

class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))

Modules :-
Modules:- (collection of function)

A module is a file containing python definitions function, statements and


instructions.

Ex:-

Built-in python modules are,

1.math-mathematical function:

Math.sqrt(x)- Return the square root of x

math.pi- The mathematical constant π=3.141592

Type of modules:-

1. User-defined
2. Predefined

Predefined function:-

 String
 Math
 Random
 Range

User-define:-

There are different ways by which you we can import a module(the file name is the
module name with the suffix .py).

Using import statement:

“import” statement can be used to import a module.

Syntax:-

import <file_name1, file_name2.............(n)=” “>

</file_name1>

Example:

Save the file by name arithmetic operation.py to import this file “import” statement is
used.

import addition

addition.add(10,20)

addition.add(30,40)

FILES:-

File is a continuous sequence of data in memory.

Type of files:-
1. Text Files
2. Binary Files

Binary files are not human readable files and the data is stored as machine
understandable binary language(OS and IS).
A text file is a sequence of characters stored on a permanent medium like a hard
drive, flash memory, or CD-ROM. Text file is a human readable file.

Modes of file

1. Read mode
2. Write mode
3. Append mode

1. READ MODE ‘r’ Read mode which is used when the file is only
being

2. WRITE MODE ‘w’ Write mode which is used to edit and write new
information to the file

3. APPEND MODE ‘a’ Which is used to add new data to the end of the
file.

Errors & Exceptions:-

Errors or mistakes in a program are often referred to as bugs.

Errors can be classified into three major groups:-

 Syntax errors
 Runtime errors
 Logical Errors

Syntax error:-

Syntax errors are mistakes in the use of the python language, and are analogous to
spelling or grammar mistake in a language like English.

Syntax error in python:

My function(x,y):
return x+y

else:

print(“Hello”)

if mark>=50

print(“You paased!”)

if arriving:

print(“Hi!”)

else:

print(“BYE!!!”)

Runtime Errors:-

A runtime error is a type of error that occurs during program execution.

Logical errors:-

They occur when the program runs without crashing, but produces an incorrect result

Exceptions:-

An exception is an event, which occurs during the execution of a program that


disrupts the normal flow of the program’s instructions.

Ex: Google sign password

Handling Exceptions:-

TRY, CATCH, EXCEPT, ELSE, FINALLY


try:

fh=open(“testfile”,”w”)

fh.write(“This is my test file for exception handling!!”)

exceptIOError:

print “Error: can’t open file in write mode

else:

print “Written content in the file successfully”

fh.close()

Output:-

Written content in the file successfully.

You might also like