0% found this document useful (0 votes)
4 views

Python Soc

Uploaded by

k04906948
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Soc

Uploaded by

k04906948
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

SKILL ORIENTED PROGRAM

FULL STACK WITH PYTHON-1

A Report submitted in partial fulfillment of the requirements for the award of credits
to a skill-oriented course: Full Stack with Python
Bachelor of Technology
II Year
In

COMPUTER SCIENCE AND ENGINEERING - ARTIFICIAL INTELLIGENCE &


MACHINE LEARNING

Submitted by :- C. Mohana Venkata Adithya


Name of the Student (Roll No) :- C. Mohana Venkata
Adithya(23JR1A4242)

Under the guidance of

Mohammad John Saida


Asst. Prof, Dept. of CSE-AI & ML

DEPARTMENT OF CSE- ARTIFICIAL INTELLIGENCE


KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
[AUTONOMOUS]
(Approved by A.I.C.T.E New Delhi || Permanently Affiliated to JNTUK, Kakinada) || Accredited with ‘A’ Grade by NAAC || NBA
Accreditation status for 5 B.Tech Programmes (Civil, CSE, ECE, EEE & Mech))

Vinjanampadu (V), Vatticherukuru (M), Guntur (DT), A.P-522017.

www.kitsguntur.ac.in

October-20
DEPARTMENT OF CSE-ARTIFICIAL INTELLIGENCE & MACHINE LEARNING
KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES
(Approved by A.I.C.T.E New Delhi || Permanently Affiliated to JNTUK, Kakinada) || Accredited with ‘A’ Grade by
NAAC || NBA Accreditation status for 5 B.Tech Programmes (Civil, CSE, ECE, EEE & Mech))

Vinjanampadu (V), Vatticherukuru (M), Guntur (DT), A.P-522017.

CERTIFICATE

This is to certify that this “Skill Oriented Course of Full Stack with Python” is
done by C. Mohana Venkata Adithya (23JR1A4242) in the duration of 2024
to 2025, who carried out the work under supervision and submitted in the partial
fulfillment of the requirements for the award of the degree of Bachelor of
Technology in Computer Science & Engineering-Artificial Intelligence &
Machine Learning from JNTU-Kakinada.

HEAD OF THE DEPARTMENT PROJECT GUIDE


DEPARTMENT OF CSE-ARTIFICIAL INTELLIGENCE &
MACHINE LEARNING

KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES


(Approved by A.I.C.T.E New Delhi || Permanently Affiliated to JNTUK, Kakinada) || Accredited with ‘A’ Grade by
NAAC || NBA Accreditation status for 5 B.Tech Programmes (Civil, CSE, ECE, EEE & Mech))

Vinjanampadu (V), Vatticherukuru (M), Guntur (DT), A.P-522017.

DECLARATION

We hereby inform that this t “Skill Oriented Course of Full Stack with Python” is
has been carried out by myself in the duration of 2024 to 2025, and submitted in
partial fulfillment for the award to the degree of Bachelor of Technology in
Computer Science and Engineering-Artificial Intelligence & Machine Learning to
Jawaharlal Nehru Technological University Kakinada under the guidance
of Mohammad John Saida, Asst. Prof, Dept. of Computer Science and Engineering-
Artificial Intelligence & Machine Learning.

C. Mohana Venkata Adithya


23JR1A4242
DEPARTMENT OF CSE-ARTIFICIAL INTELLIGENCE &
MACHINE LEARNING

KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES


(Approved by A.I.C.T.E New Delhi || Permanently Affiliated to JNTUK, Kakinada) || Accredited with ‘A’ Grade by
NAAC || NBA Accreditation status for 4 B.Tech Programmes (CSE, ECE, EEE & Mech))

Vinjanampadu (Vil), Vatticherukuru (Md), Guntur (DT), A.P-522017.

ACKNOWLEDGEMENT

We would like to express our profound gratitude towards Mohammad John Saida, Asst.Prof,
Department of CSE-AI & ML, who played a supervisory role to utmost perfection for guiding as
an internal guide methodically and meticulously.

We are highly indebted to Dr G Murali, Head of the Department, Computer


Science and Engineering-Artificial Intelligence & Machine Learning for
providing us all the necessary support.

We are very much thankful to the college management for their continuous
support and facilities provided.

We render our deep sense of gratitude to Dr. P. BABU, Principal & Dr K Hari Babu,
Academic Director , for permitting us to carry out Skill Oriented course on Full Stack with
Python development. We would like to express our sincere thanks to Computer Science and
Engineering-Artificial Intelligence & Machine Learning staff for lending us their time to help us
and complete the work successfully.We would also like to thank our staff, parents and friends
for their enduring encouragement and assistance whenever required.

C. Mohana Venkata Adithya


23JR1A4242

KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES


(Autonomous)
Accredited by NBA & NAAC with Grade “A” and Affiliated to JNTUK-Kakinada
Vinjanampadu, Vatticherukuru Mandal, Guntur, Andhra Pradesh522017
DEPARTMENT OF CSE - ARTIFICIAL INTELLIGENCE &
MACHINE LEARNING
Institute Vision and Mission

INSTITUTION VISION
To produce eminent and ethical Engineers and Managers for society by
imparting quality professional education with emphasis on human values and
holistic excellence.

INSTITUTION MISSION

 To incorporate benchmarked teaching and learning pedagogies in curriculum.

 To ensure all round development of students through judicious blend of


curricular, co- curricular and extra-curricular activities.

 To support cross-cultural exchange of knowledge between industry and academy.

 To provide higher/continued education and researched opportunities to the


employees of the institution.

KKR & KSR INSTITUTE OF TECHNOLOGY AND SCIENCES


(Autonomous)
Accredited by NBA & NAAC with Grade “A” and Affiliated to JNTUK-Kakinada
Vinjanampadu, Vatticherukuru Mandal, Guntur, Andhra Pradesh522017
DEPARTMENT OF CSE - ARTIFICIAL INTELLIGENCE &
MACHINE LEARNING

Department Vision and Mission

Department VISION

To be a renowned department for education in Artificial Intelligence and empowering students


into professional engineers with human values and holistic excellence.

Department MISSION

• Impart rigorous training to acquire knowledge through the state-of-the-art concepts and
technologies in Artificial Intelligence.

• Train students to be technically competent through innovation and leadership.

• Inculcate values of professional ethics, social concerns, life-long learning and environment
protection.

• Establish centers of excellence in leading areas of computing and artificial intelligence.


Index
S.No Item Page
No
1 Introduction 9
2 Features of python 9
3 Python Keywords 18
4 Indentation 19
5 Comments 19
6 Statements 19
7 Loop Statements 21
8 Strings 22
9 Lists 29
10 Tuples 33
11 Dictionary 34
12 Sets 36
13 Functions 38
14 OOP’s in Python 40
15 Inheritance 45
16 Patterns Programs in Python 48

7
PYTHON
Python is a high-level, interpreted programming language that is widely used for
various purposes such as web development, scientific computing, data analysis,
artificial intelligence, and more. It's known for its simplicity, readability, and ease of
use, making it a great language for beginners and experts alike.
➢ Less lines of code
➢ No rules
➢ No char,short int,long int,double,long double,sighned,unsighned
➢ No switch,do-while,pointers
➢ No braces for block statements
➢ No need for declaring variable
➢ Dynamic typing language-The data type of the variable is decided at run time
only

Features Of Python

1. Simple: Reading a program written in Python feels almost like reading


english. The main strength of Python which allows programmer to
concentrate on the solution to the problem rather than language itself.

2. Easy to Learn: Python program is clearly defined and easily readable. The
structure of the program is simple. It uses few keywords and clearly defined
syntax.

3. Versatile: Python supports development of wide range of applications such


as simple text processing, WWW browsers and games etc..

4. Free and Open Source: It is a Open Source Software. So, anyone can freely
distribute it, read the source code, edit it, and even use the code to write new
(free) programs.

8
5. High-level Language: While writing programs in Python we do not worry
about the low-level details like managing memory used by the program.

6. Interactive: Programs in Python work in interactive mode which allows


interactive testing and debugging of pieces of code. Programmer can easily
interact with the interpreter directly at the python prompt to write their
programs.

simple

Inter-preter
Easy to
learn

Features
of
object
oriented
Python High level
programming language

portable Dynamic

7. Portable: It is a portable language and hence the programs behave the same
on wide variety of hardware platforms with different operating systems.

8. Object Oriented: Python supports object-oriented as well as


procedureoriented style of programming .While object-oriented technique
encapsulates data and functionality with in objects, Procedure oriented at
other hand, builds programs around procedure or functions.

9
9. Interpreted: Python is processed at runtime by interpreter. So, there is no
need to compile a program before executing it. You can simply run the
program. Basically python converts source program into intermediate form
called byte code.

10.Dynamic and strongly typed language: Python is strongly typed as the


interpreter keeps track of all variables types. It's also very dynamic as it
rarely uses what it knows to limit variable usage.

11.Extensible: Since Python is an open source software, anyone can add


lowlevel modules to the python interpreter. These modules enable
programmers to add to or customize their tools to work more efficiently.

12.Embeddable: Programmers can embed Python within their C, C++, COM,


ActiveX, CORBA and Java Programs to give ‘scripting ‘capability for users.

13.Extensive Libraries: Python has huge set of libraries that is easily portable
across different .

10
Tokens

Data
Literals Identifiers keyWords Operators
Types

❖ Literals:
In programming constants are referred to variables that cannot be Changed.

• Numeric literal: It is a literal representation of a number, as opposed to a


variable or an expression that evaluates to a number.

1. Integer literal: Number llike 5,6,3 etc…


2. Floating literal:Numbers with decimal part like 3.14,6.8.5.0 etc…

Note:
For c precision part is 6 decimals.
For java and python precesion part is 15 decimals.

• String literal:

A string literal is a sequence of characters that is written directly in the code,


enclosed in quotes (either single quotes ' ' or double quotes " ").

It represents a string value, which can be a word, phrase, sentence, or even a


single character.

11
Examples of string literals include:
1. 'Hello, World!'
2. "This is a string"
3. 'a' (a single character string)
4. '123' (a string, not a number)

• Boolean literal: Boolean literals are used in programming to represent a


logical value that can be used in conditional statements, loops, and logical
operations.
It can be either “True” or “False

❖ Identifiers:

Identifiers are names given to identify something. This something can be a variable,
function, class, module or other object. For naming any identifier, there are some
basic rules.

Rules of Identifiers:-
1.The first character of an identifier must be an underscore ('_') or a letter (upper or
lowercase).
2.The rest of the identifier name can be underscores ('_'), letters (upper or
lowercase), or digits (0- 9).
3.Identifier names are case-sensitive.
For example, myvar and myVar are not the same.
4.Punctuation characters such as @, $, and % are not allowed within identifiers.
Examples of valid identifier names are sum, __my_var, num1, r, var_20, First,
etc…
Examples of invalid identifier names are 1num, my-var, %check, Basic Sal,
H#R&A, etc…

12
❖ Data types:

The variables can hold values of different type called Data type. They
are classifies into two type:

1.Immutable data type:An immutable data type is a type of data that cannot be
changed or modified once it is created. In other words, its state is immutable, meaning
it cannot be altered after it is initialize.
→ In python int,float,bool,String,tuple are the Immutable data type.
→ In immutable data types, when you change the value of a variable, both the
value and the memory location change.

2.Mutable datatype: Mutable data type means that the value of the data can be
changed (mutated) after it is created.
→ In python list,dict,set are called mutable data type.
→ In mutable data type when we change the value of variable only the value chages
but location not changes.

❖ Keywords:

• Keywords are the reserved words in Python.


• We cannot use a keyword as variable name, function name or any other
identifier.
• There are 35 keywords in Python 3.10.
This number can vary slightly in course of time. All the keywords except True,
False and None are in lowercase and they must be written as it .

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

❖ Operators:

Python supports the following operators


1. Arithmetic Operators
2. Relational Operator
3. Bitwise Operator
4. Shift Operator
5. Logical Operator
6. Membership Operator 7. Identity Operator
8. Assignment Operator
9. Comma Operator

1.Arithmetic Operator:

Arithmetic operators are used to perform mathematical operations like addition,


subtraction, multiplication, division, modulus, power.

Arithmetic Operator Symbols: + , - , * , / ,**.

→ / - True division or float division.


→ // - Floor division or Integer division
→ ** - Exponent Operator

• How to read multiple numbers in same line var1,


var2,… ,var n=map(int,input().split())
(or)
var1,var2,…,var n=map(int,input().split())
Ex:a,b,c=map(int,input().split())
2.Relational operator:

14
A Relational or Comparison operator checks the relationship between two operands. If
the relation is true, it returns 1; if the relation is false, it returns value 0.

Relational Operators Symbols: ==,!=,<,>,<=,>= .

For Example assuming a=100 and b=2000


we can use the comparison operators on them as specified in the following

== print(a= =b) False


!= print(a!=b) True
< print(a<b) True
<= print(a<=b) True
> print(a>b) False
>= print(a>=b) False

3.Bitwise operator:
As the name suggests, bitwise operators perform operations at the bit level.
These operators include bitwise AND, bitwise OR, bitwise XOR, and shift operators.
Bitwise operators expect their operands to be of integers and treat them as a sequence
of bits.
• If a number can be expressed in powers of 2 the binary number is 1
followed by x no.of zeroes.
eg: Let x=9 then 2**9=512 in bits 1000000000
• If a number is expressed 2**x-1 the binary value is x no.of ones. eg:
Let x=9 then 2**x-1 in bits 0111111111
→ If n&n-1= = 0 the n can be expressed in powers of 2 otherwise n can’t be
expressed in powes of 2

A B A&B A|B A^B !A


0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0

15
4.Shift Operators:
Python supports two bitwise shift operators. They are shift left (<<) and shift right
(>>). These operations are used to shift bits to the left or to the right.

Left shift(<<): In left shift we move the bit values by one place towards left
We neglect MSB and add 0 to LSB eg: Let
a=12 i.e 00001100 a<<i =a*(2**i)
If i=1 then a<<1=12*(2**1)=24
⸫ a=00001100 then a<<1 is 00011000 i.e 24

Right shift(>>): In right shift we move bit value by one towards rightside We
neglect LSB and add 0 to MSB.
eg: Let a=12 i.e 00001100 a>>i=a//(a**i)
If i=1 then a>>1=12//(2**1)=6
⸫ a=00001100 then a>>1 is 00000110 i.e 6

5.logical operators:
Logical operators are used to simultaneously evaluate two conditions or expressions
with relational operators.
→ Logical And(and): If the first condition false it does not evaluate the second
condition it directly gives false when the both conditions are true it gives true.
→ Logical OR(or): If one or both conditions are true it gives true.

6.Membership Operator(in,not in):

in: This operator gives true if the searching element is found in the given sequence or
iterable otherwise it gives false.

not in: This operator gives true if the searching element is not found in given sequence
or iterable otherwise it gives true.

7.Identity Operator(is, not is):


is:This operator gives true if both the variable shares the same memory location
otherwise it gives false
In immutable if the values are same then location also same

16
not is:This operator gives true if both variables not sharing same memory location
otherwise it gives false

8.Assignment Operator:
Assignment operators are used in Python to assign values to variables.
Expression is evaluated and result is stored in LHS i.e variable
Additional/Shortcut assign: += , - = ,*=,/=,//=,**= Multiple
assignment :
Var1,var2,var3...varn=val1,val2,val3...valn

9.Comma operator(,):
Variable separator and value separator

Character Set

In python or java Unicode is 2 Bytes i.e 216(0-65535).


• 0-127 unicode charcters are same as ascii character
ASCII Division (0-127)
0-31 Non printable character
32-47 Special characters
48-57 ’0’-’9’
58-64 Special Symbols
65-90 ’A’-’Z’
91-96 Special Symbols
97-122 ’a’-’z’
123-126 Special Symbols

• To check ascii in python the functions are

1) ord(): It gives the UNICODE value of a given single character.


2) chr(): It gives the character associated for the given UNICODE value.

17
Example:
print(ord(“a”))
print(chr($))
Output:
97
36

Indentation
Whitespace at the beginning of the line is called indentation. These white spaces or the
indentation are very important in Python.
In a Python program, the leading whitespace including spaces and tabs at the beginning
of the logical line determines the indentation level of that logical line.
Once we keep ‘:’ at the end of selection or loop statement then the body of selection or
loop statement will have tab space as identation.

Comments
These are non executable statements in python it is also used to understand the
program in easier manner.
# - It is the single line comment.
‘‘‘ ’’’ - It is the multi line comment.

Statements
A statement is an instruction that the Python interpreter can execute.

1.Expression Statements: Any arithemetic,bitwise,assignment,input,output


statements
2.Selection Statements:if-else,if-elif-else
3.Loop Statements:while,for
4.Jump Statements:break,continue
5.Block Statements:if,else,elif,for,while,functions,classes are all bloack statements(At
the end of these statements we will keep ‘:’).

2.Selection Statements:

18
if-else: If the condition is true statement1 is evaluated otherwise else part statement2 is
evaluated.

Syntax:
if condition:
statement1 else:
statement2

if-elif-else: If the condition is true statement1 is executed if condition false it


verifies elif condition if it is true statement2 is executes it is false else block i.e
statement3 is executed.

Synatx:
if condition1: statement1
elif condition2:
statement2 else:
statement3

LOOP STATEMENTS

Loop is an iterative statement which executes for a particular number of times. while
loop:
syntax:

19
initialization i=1
while condition: while i<=10:
statement print(i)
incr/decr i+=1
else: else:
statement2 print('end of while')
loop variable or control variable the initialized value is checked in the condition, as
long as the condition is True, the body of the loop(statements inside the loop) will be
executed, once the condition is False, else part will be executed.

for loop: syntax:


for var in range(start,stop,step):
statement1 else:
statement2
range() deals only with numbers start
means initialization(starting value) stop
means condition (last value) step means
incr/decr
➢ start and step are optional.
if start is not given, its default value is 0. if
step is not given its default value is 1.
→ stop is mandatory and it always executes till its previous value.
if start <stop then stop works till stop-1. if
start>stop then stop works till stop+1

STRINGS

String represents a group of character's. These are very important because most of
the data that we use in daily life in the form of string

Single quotes(‘ ’): ‘Hello world’


Double quotes (“ ”): “Hello world”

20
Triple quote (‘‘‘ ’’’):These are multi line

➢ Operations:
1.Concatenation(+):Merging of two string
It is homogeneous that means string only concatinate

2.Repetation(*):Same string is repeated for multiple times


Note:Repetition is applied only when size of string is <256 MB ofter repetition.

3.Indexing([ ]):Indexing starts from 0 to no.of characters-1 from left to right


Indexing also starts from -1 to -(no.of characters) from right to left

4.Slicing([ : : :]): syntax:


strvar[start:stop:step] start,stop
and step are all optional.
→ if step is not given, its default value is 1.
→ If start, stop are not given, their default value depends on the value of step.
→ If step is empty(1) or +ve, start default value is 0. stop default value is len(str)
[number of characters] and stop works till stop-1.
→ If step is negative, start default value is -1 and stop default value is (len(str)
+1) and stop works till stop+1.
where to use slicing:
If we wanted to extract a substring or subsequence we have to go for slicing.
Substitute string.

Example:
committment 3 output1:
mittmentcom output2:
entcommittm Code:
s=’commitment’ k=3
print(s[k: ]+s[ :k])
print(s[-k: ]+s[ :-k])

21
String Functions
len() count() find() index() rfind()
rindex() center() ljust() rjust() zfill()
lstrip() rstrip() strip() split() rsplit()
splitness() format() replace() upper() lower()
casefold() title() capitalize() swapcase() isalpha()
isalnum() isspace() isidentifier() isprintable() isascii()
isupper() islower() istitle() isdigit() isdecimal()
isnumeric() startswith() endswith() max() min()
expandtabs() join() chr() ord() str()

Functions:

len() :It gives the length of the string.


len(strvar)

count() :It gives the frequency of the specified pattern(either single character or a
string) in the given string.
strvar.count(pattern)

find(): it gives the first occurrence of the specified pattern in the given string.
strvar.find(pattern)
strvar.find(pattern,startIndex)
strvar.find(pattern,startIndex,stopIndex) iffind()
is unsuccessful, it gives -1.
It works from left to right.

index(): it gives the first occurrence of the specified pattern in the given string.
It works from left to right.
ifindex()is unsuccessful, it raises an exception called ValueError.

rfind():it gives the last occurrence of the specified pattern in the given string.

22
strvar.rfind(pattern)
strvar.rfind(pattern,startIndex)
strvar.rfind(pattern,startIndex,stopIndex)
it works from right to left. if rfind() is
unsuccessful, it gives -1.

rindex(): it is same as rfind(), but if rindex() is unsuccessful, it raises an exception


called ValueError.

center(): it aligns the string as center aligned in a larger width, the remaining width
is filled by default with spaces or a given single fillchar.
strvar.center(width)
strvar.center(width,fillchar)

ljust(): it aligns the string as left justified in a larger width, the remaining width is
filled by default with spaces or a given single fillchar.

rjust(): it aligns the string in right justified in a larger width, the remaining width is
filled by default with spaces or a given single fillchar.

zfill(): it is same as rjust() but the remaining width is filled by zeros.

➢ HOW MANY TYPES OF SPACES IN PROGRAMMING LANGUAGE:

1. ' '(32)(whitespace character)


2. '\n'(10)(newline character(ENTER))
3.'\t'(9)(horizontal TAB(TAB KEY))
4. '\r'(13)(carriage return(HOME))
5. '\v'(11)(vertical TAB)
6.'\f'(12)(form feed)

23
istrip(): it removes the leading(before the start of the string) spaces or any
specified character in the given string strvar.lstrip() : it removes all spaces
strvar.lstrip(char): it removes all chars

rstrip(): it removes the trailing(after the end of the given string) spaces or any
specified character in the given string.
strvar.rstrip() : it removes all spaces strvar.rstrip(char):
it removes all chars

strip(): it removes both leading and trailing spaces or specific characters from the
given string.

split(): it divides the given string into multiple strings(list of strings) based on the
specified delimiter(by default it is space)

rsplit(): it divides the given string into multiple strings(list of strings) based on the
specified delimiter(by default it is space)

split() Vs rsplit(): when we customize the splittings, then split() works from left to
right and rsplit() works from right to left.

splitlines(): it works on '\n' '\v' '\r' '\f'.

upper():it converts the entire string to uppercase(it does not consider digits or
symbols)

lower():it converts all the uppercase letters to lowercase.

casefold(): it is same as lower().the difference is lower() works only on english


alphabet whereas casefold() works on english alphabet as well as other linguistics.

capitalize(): it converts 0th index lowercase alphabet to uppercase. if 0index is not


a alphabet then capitalize() does no change.

title(): it converts every words starting letter only to uppercase.

24
format(): it is used to place the existing variable in string.
1. using format():
2. using format specifiers
3. using f-strings

replace(): it replaces by default all the occurrences of the specified pattern with the
new pattern in the given string.
strvar.replace(old,new)

isalpha(): it gives True, if the string contains only alphabet(A_Z a_z), if the string
contains one non alphabet it gives False.

isalnum(): it gives True, if the string contains only either alphabet or digits, if the
string contains atleast one symbol it gives False.

isspace(): it gives True, if the string contains only spaces(all types of spaces), if the
string contains atleast one non space character, it gives False.

isidentifer(): it gives True, if the string contains a valid identifier(based on the


rules) otherwise it gives False.

isprintable(): it gives True, if the string contains only printable characters,


otherwise it gives False.

isascii(): it gives True, if the string contains characters with valid ASCII
values(0127) otherwise it gives False.

isupper(): it gives True, if the string contains only uppercase letters, if the string
contains atleast one lowercase letter it gives False.

islower(): it gives True, if the string contains only lowercase letters, if the string
contains atleast one uppercase letter, it gives False.

25
istitle(): it gives True, if the string is in titlecase(every words starting letter is only
uppercase), otherwise it gives False.

isdigit():it gives True, if the string contains digits or unicode digits(Ex: '\u00B2'),
otherwise it gives False.

isdecimal():it gives True, if the string contains digits otherwise it gives False.

isnumeric():it gives True, if the string contains digits or unicode digits or other
linguistic digits, otherwise it gives False.

startswith():it gives True, if the string is started with the specified pattern,
otherwise it gives False.

endswith():it gives True, if the string ends with the specified pattern, otherwise it
gives False.

Example:
s='this is a test'
print(s.startswith('thi')
)
print(s.endswith('tst'))
output: True
False

max(): it gives the character with maximum unicode value.

min(): it gives the character with minimum unicode value.

expandtabs():'\t' size can be increased or decreased(min 0) for the string.

join(): multiple strings can be converted into a single string.


joinchar.join(sequence/iterable)

26
LISTS

List is a mutable data type which is a dynamic array.


• list is a collection of elements of heterogenuous or different or dissimilar
data types.
• it is represented by [].

Method1: p=[]
n=int(input())
for i in range(n):
p.append(int(input())) print(p)

Output:
4
5
1

27
2
3
[5,1,2,3]

Method2(list comprehension): n=int(input())


p=[int(input()) for i in range(n)] print(p)

Output:
3
1
5
8
[1,5,8]

Type-2: the array elements are in a single line separated by a space.

Code:
n=int(input())
p=list(map(int,input().split()))[:n]
print(p)
Output:
3
123456
[1,2,3]

method2(list comprehension) n=int(input())


p=[int(x) for x in input().split()][:n]
print(*p)
Output: 5
12345
12345

➢ Operations:
1. concatenation(+)

28
2. repetition(*)
3. indexing([])
4. slicing([::])
List Functions
len() count() index() clear()
copy() append() insert() pop()
remove() sort() sorted() min()
max() sum() reverse() extend()

Functions:

1.len(): it gives the length of the list(number of elements).

2.count(): it gives the frequency of given element in the list.

3.index(): it gives the first occurrence of the specified element in the given list. if
the element is not found, it raises an exception called ValueError.

5.clear(): it will make the list empty(clear all the elements).

5. copy(): it copies only values from one list to another list(it does not share
location). Example: p=[1,2,3] q=p.copy() print(p,q) Output:
[1,2,3] [1,2,3]

6. append(): one element is appended(added at last) to the list.


listvar.append(element)

29
7. insert(): one element is inserted at a particular index.
listvar.insert(index,element) if the index specified is more than the len(list) then
insert() will behave like append().

8. pop(): it removes an element specified by the index, by default it removes the


last element, if the index specified is not available, it raises an exception
called IndexError.

9.remove(): it removes the specified element from the list. if the element is not
available, it raises an exception called ValueError.
TIM SORT(insertion +merge)

10.sort(): the elements are sorted in ascending order.


listvar.sort()

11.sorted(): the elements are sorted in ascending order.


listvar=sorted(listvar)

12.max(): it gives the element with maximum value. to apply max() elements must
be of same type.

13.min(): it gives the element with minimum value to


apply min() elements must be of same type.

14.sum(): it gives sum(total) of the elements of the list. to apply sum() elements
must be of number type.

15.reverse(): the given list is reversed. listvar.reverse()

16.extend(): it is same as +(concatenation operator), it merges two lists.


listvar.extend()

Example: p=[1,2,3]
p.append(84) print(p)
p.insert(64387438,666) print(p)

30
p.extend([23,56])
print(p)

Output:
[1,2,3,84]
[1,2,3,84,666]
[1,2,3,84,666,23,56]

TUPLES

➢ It is same like list but tuple is immutable and list is mutable. represented
by ().
➢ Tuples contain multiple objects with diffrent data types.

Example:
Code:
t= (1,2,3) a=(1,’String’,[1,2,3])
print(t) print(a)
Output:
(1,2,3)
(1,’String’,[1,2,3])

• Operations:
1. concatenation
2. repetition
3. indexing
4. slicing

31
Tuple Functions

len() Count() Index() Max()


Min() Sum() Sorted()

➢ Tuples are utilized by functions in python when they return multiple values.

DICTIONARY

➢ It is a mutable data type where each element has a pair of objects called Key
and Value separated by a ':'.
➢ where Keys are unique(no duplicates) and immutable(we cannot use list or
dict or set as keys).
➢ values may be immutable or mutable.
➢ Dictionaries does not have any order, because order is decided by hashing
technique, that is the reason dictionary in Python is unordered Dictionary.
➢ How to create a dictionary. d={} d=dict()
➢ Operations:
1. indexing: indexing can be done that too key is the index of the
dictionary.

Dictionary Functions
len() max() min() sum()
clear() copy() sorted() updated()
setdefault() pop() popitem() keys()
values() items() fromkeys() get()

Functions:

32
1.len():it gives the length.

2. max(): it gives the maximum key.

3. min(): it gives the minimum key.

4. sum(): it gives sum of keys(keys must be number type)

5. clear():it will make the Dictionary empty(clear all the elements).

6. copy():to insert elements into dictionary we have three ways.


7. sorted():the elements are sorted in ascending order.

8. update(): one or more elements can be inserted into dictionary.


dictvar.update({k1:v1,k2:v2,..kn:vn})

9.setdefault(): one element will be inserted using setdefault().


dictvar.setdefault(key,value)

if the key is already available in the dictionary, then setdefault() does nothing.
if the key is not avaialable, then key,value pair will be inserted.
dictvar[key]=value

10.pop(): it removes a specific element with the given key. dictvar.pop(key)


if the key specified is not in the dictionary, pop() raises KeyError exception.

11.popitem(): it removes the lastly inserted element in the dictionary.


dictvar.popitem()

12.keys(): it retrieves the keys of the dictionary. dictvar.keys()

13.values(): values of the dictionary will be retrieved.


dictvar.values()

14.items(): key,value pair will be retrieved from the dictionary. dictvar.items()

33
15.fromkeys(): a dictionary will be created with the existing sequence elements as
keys and by default values are None. dictvar.fromkeys(sequence)
dictvar.fromkeys(sequence,value)

16.get(): the value of the particular key will be retrieved. dictvar.get(key): if the key
is not available, it returns None dictvar.get(key,value) : if the key is not available, it
returns the default value specified.

SETS

• Set is a mutable data type where it does not allow duplicates. set is mutable,
but set elements are immutable.
• set in Python is unordered, because order is decided by hash function.
we need to use set when we need to remove duplicates but there is no issue
with the order.
p=set()
• Operations:
1. union
2. intersection

Sets Functions

Len() Max() Min() Sum()


Copy() Clear() Sorted() Update()
Add() Pop() Remove() Discard()

Functions:

1.len():it gives the length.

2. max(): it gives the maximum key.

3. min(): it gives the minimum key.

34
4. sum(): it gives sum of keys(keys must be number type)

5. clear():it will make the Dictionary empty(clear all the elements).

6. copy():to insert elements into dictionary we have three ways.

7. sorted():[no use on sets]

8.update(): we can insert one or more elements into set at a time(if duplicates
are given it will ignore)
setvar.update({ele1,ele2,...elen})

9.add(): one element is inserted into the set.


setvar.add(element)

10.pop(): it removes the first element of the set(whichever may be)


setvar.pop()

11.remove(): it removes a specific element from the set. if the element is not
avaiable, it raises KeyError. setvar.remove(element)

12.discard(): it is same as remove() but if the element is not available, it does not
raise any exceptions.

35
FUNCTIONS

• Function is set of statements which has self defined task, which is executed
upon access or call or request.
• Functions are two types:
1.built-in functions(pre-defined functions) factorial(),
gcd(), sqrt(), print()
2.user-defined functions:

syntax for function definition def


function_name(args-list): #body of
the function
return exp or return (exp) or return

arguments or parameters: input to the function.


def fun(): print('hi') fun()

NOTE:
The function definition must be placed above the function call and in the same
indentation. specific features of functions in Python: 1. A function can be assigned
to a variable.
2. A function can return multiple values at a time 3.
Nested functions are possible.
4. A function can return another function(it avoids the problem in nested functions)
5. Afunction can be used as an argument to another function.

• calling function: Function which is specified in the function call.


• called function: Function which is specified in the function definition.

36
• actual arguments: The arguments which are specified in the calling
function
• formal arguments: The arguments which are specified in the called
function.
The communication between actual and formal arguments is called as parameter
passing mechanism.

1. call-by-value(pass-by-value): if the actual arguments are immutable, then


the function call is call by value
2. call-by-reference(pass-by-reference): if the actual arguments are mutable,
then the function call is call-by-reference.

Based on actual and formal arguments our functions are categorised into
1.Positional arguments
2.keyword arguments
3.default arguments
4.variable length arguments
5.variable length keyword arguments

Anonymous functions

Nameless functions are called as anonymous functions.


lambda functions are anonymous functions. syntax:
var=lambda macro:sequence p=lambda
x:x**3
print(type(p))

NOTE: lambda functions are used to implement one liner logics only.

1. map(): map(function, sequence)


2. filter(): filter(function,sequence)
3. reduce(): reduce(function, sequence)

RECURSIVE FUNCTIONS:
When a function calls itself, it is known as Recusion.

37
We need to go for recursive function when we can divide a problem into sub
problems.

OOPS IN PYTHON

• Python is a light weight oop language.


• Without using a keyword called class, if we cant execute a program then it is
called as pure oop otherwise it is partial oop.
• Java is pure oop and coming to python it is a partial oop.

FUNCTION AND METHOD:

• When we use function inside a class is called method.


• When we use function outside the class is called function.

FEATURES OF OOPS IN PYTHON

1.Class
2.Object
3.Encapsulation
4.Inheritance
5.Polymorphism
6.Methods
7.Constructor

1)Class:
Class is a blue print from which objects are created. Class contains data members to
store information and member functions to operate upon data members. Syntax for
class in python: class classname(super class name):

2)Object:
Object is an instances of a class. It is basically a real world implementation of the
class having all those property values which are define or structured in the class.
Syntax for object creation: object name = classname(parameters)

38
3)Encapuslation:
Acquiring properties from one class to another class, the class which gives
Inheritance is called super class or base class or parent class.
The class which gets inheritance is called sub class or derived or child class.

Types of Inheritance:
1.Single or simple Inheritance
2.Multiple inheritance
3.Hierarchical Inheritance
4.Multi level Inheritance
5.Hybrid or Multipath Inheritance

1.Single or simple Inheritance: One base class and one derived class .
2.Multiple inheritance: One derived class and two or more base classes.
3.Hierarchical Inheritance: One base class and two or more derived classes.
4.Multi level Inheritance: One base class(A), one derived class(B) which in turn
serves as a base class for one more derived(C) class.
5.Hybrid or Multipath Inheritance: Combination of two or more inheritance.

5)Polymorphism: One entity which is exhibited in many forms.

i)Compile time polymorphism: polymorphism which happens at the time of


compilation.
EX: Method overloading, method overriding, operator overloading.

ii)Runtime polymorphism: polymorphism which happens at run time In


python there is no run time polymorphism.

Self: Self is a memory variable, which stores the reference of the current calling
object.
Self is used to:

39
1)To access the class variable or members of the class inside the class.
2)To differentiate class variable and local variable if names are same.
➢ In class, there are two types of variables:

1)Class variable or static variable.


2)Instance variable.

1)Static variable: It is available through out the class.

2)Instance variable: The variables created or defined inside the constructor of the
class.

6)Methods:

There are 3 types of methods:

1)Instance method.
2)Class method.
3)Static method.
Instance method:

class A:
a = 78
b = 89

def disp(self):
self.a += 22
self.b += 12

p = A()
print(p.a, p.b)
p.disp()
print(p.a, p.b)

40
q = A()
print(q.a, q.b)
Class method:

class A:
a = 78
b = 89

@classmethod
def disp(cls):
cls.a += 22
cls.b += 12 p =
A() print(p.a,
p.b) p.disp()
print(p.a, p.b) q
= A() print(q.a,
q.b)
Static method:

static method is same as class method it does not have any default positional
argument called self class method and static method can be called using object of
the class or class name also but not instance methods.

7)Constructor:

Constructor is a special method which is executed when we create object for the
class.
• The rule in java or c++ is constructor name is same as the classname and
there is no return type for constructor.
• In python __init__() is the constructor.

1)Default constructor: The constructor without any arguments other than self.

41
2)Parameterized constructor: The constructor with atleast one parameter other
than self.

eg: def SUM(a,b):


Return a+b
def SUM(a,b,c):
Return a+b+c
print(SUM(5,6,7))

NOTE:
i)In python, we cannot define multiple methods with same name (either
constructors also or functions also).

ii)We cannot define multiple constructors in the same class (only one constructor
will be executed).

INHERITANCE

42
1.Simple Inheritance: One super class gives inheritance to one sub class.
Uses of super():
• To access the super class constructor in sub class constructor.
• To access super class member inside the subclass constructor or method.
• To access super class method inside subclass constructor or method.

Super() also differentiates super class variable and class variable if names are same.
Like object is superclass of all classes In java,object in the super class of all classes
in python.

2.Multiple Inheritance: One derived class and two or more base classes.

3.Hierarchical Inheritance: One base class and two or more derived classes.

4.Multi-level Inheritance: One base class(A), one derived class(B) which in turn
serves as a base class for one more derived(C) class.

Hybrid Inheritance: Combination of two or more inheritance.

Method Overriding:
When a super class method’s name is same as the method name in sub class,
irrespective of the parameters subclass method will always override superclass
method.

Operator Overloading:
Allows you to define custom behavior for operators when they are used with
userdefined objects. This means you can extend the meaning of operators beyond
their predefined operational meaning. For example, the + operator can be used to
add two integers, concatenate two strings, or merge two lists.

Operator Overloading

43
Pre-defined method for
Operator
Overloading
+ __add__()
- __sub__()
* __mul__()
/ __truediv__()
// __floordiv__()
% __mod__()
** __pow__()
< __lt()__()
> __gt__()
<= __le__()
>= __ge__()
== __eq__()
!= __ne__()
& __and__()
| __or__()
^ __xor__()
<< __lshift__()
>> __rshift__()
~ __invert__()
+= __iadd()
-= __isub__()
*= __imul__()

44
/= __idiv__()
//= __ifloordiv__()
%= __imod__()
**= __imod__()
&= __iand__()
|= __ior__()
^= __ixor__()
_ __neg__()

Abstract class

An abstract class can be considered as a blueprint for other classes. It allows goes
to create a set of methods that must be created within any child classes built from
the abstract class. A class which contains one or more abstract methods is called an
abstract class, an abstract method is a method that has a declaration but does not
have an implementation while we are designing large functional units we use an
abstract class.

By defining an abstract base class, you can define a common application program
interface for a set of subclasses.

45
Patterns programs in Python
1) Write a python program to print the given pattern.
*****
*****
*****
*****
*****

Code:

for x in range(1,6):
for y in range(1,6):
print(“*”, ends=””) print()

2) Write a python program to print the given pattern.


11111
22222
33333
44444
55555

Code:

for x in range(1,6):
for y in range(1,6):
print(x,ends=””) print()

3) Write a python program to print the given pattern.


12345
12345
12345
12345
12345

46
Code:

for x in range(1,6):
for y in range(1,6):
print(y, ends=””) print()

4) Write a python program to print the given pattern.


ABCDE
ABCDE
ABCDE
ABCDE
ABCDE

Code:

for x in range(1,6):
for y in range(65,70):
print(chr(y),ends=””) print()

5) Write a python program to print the given pattern.


AAAAA
BBBBB
CCCCC
DDDDD
EEEEE

Code:

for x in range(65,70): for


y in range(1,6);
print(chr(x),ends=””) print()

6) Write a python program to print the given pattern.

47
55555
44444
33333
22222
11111

Code:

for x in range(5,0,-1):
for y in range(5,0,-1):
Print(x,ends=””)
Print()

7) Write a python program to print the given pattern.

EEEEE
DDDD
CCCC
BBBBB
AAAAA

Code:

for x in range(69,64,-1):
for y in range(1,6):
Print(chr(x),ends=””)
Print()

8) Write a python program to print the given pattern.


54321
54321
54321
54321
Code:

48
for x in range(5,0,-1):
for y in range(5,0,-1):
Print(x,ends=””)
Print()

49

You might also like