Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Class Xi - Full Notes

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

1. Python Fundamentals.

Python Character Set


Character set is a set of valid characters that a language can
recognize. A character represents a letter, digit or any other
symbol. Python supports Unicode encoding standard. Python
has the following character set:-
Letters A-Z, a-z
Digits 0-9
Special Symbols #,&,.’,”,[],(),{},%,!,-,_
White spaces Blank spaces, tab spaces, newline etc.
TOKENS (Lexical Units)
The Smallest individual unit in a program is known as a token.
Python has the following tokens:-
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Punctuators
1. Keywords
Keywords are the reserved word (built-in) in Python
which convey a special meaning to the language
interpreter. These words are reserved for some special
purposes.
Eg: for, break, True etc.
2. Identifiers (user-defined names)
Identifiers are fundamental building blocks of a program
and are used for giving user defined names in different
parts of a program. Identifier forming rules of Python
are given below:-
1. An identifier must be a sequence of letters and digits.
2. The first character must be a letter or an
underscore(_)
3. A keyword cannot be used as an identifier.
4. An identifier must not contain any blank spaces or
special characters except underscore.
5. Upper case and lower case letters are treated
different.
Example
Valid Identifiers: Myfile, AGE, Num1, Sum, My_age
etc.
Invalid Identifiers: data-rec, 29CLT, My.File, int, age 1
etc.
3. Literals (constants)
Literals are data items that never change their value
during the execution of a program.
Python allows several kinds of literals:-
1. String literal
The group of characters enclosed with in single or
double quotes or triple quotes (‘a’,”abc”,’’’abc’’’)
forms a string literal in Python.

2. Numeric Literals
The numeric literals in Python can be of integers,
floating point numbers (real numbers) and complex
numbers.

3. Boolean Literals
A Boolean literal in Python is used to represent one of
the two Boolean values ie, True or False.
4. Special Literal
Python has one special literal called as None. It is
used to indicate the absence of a value.
4. Operators
Operators are symbols that represent an operation.
They are tokens that trigger some
computation/action when applied to variables
(operands).
Variables or objects to which computation is applied ,
are called operands.
5. Punctuators
Punctuators are symbols that are used in
programming languages to organize
programmingsentence structures. Most common
punctuators used in Python Programming Language
are
‘, “ , ; , [ ] ,{ },( ), :, = etc.
Expression
An expression is a legal combination of variables,
constants and operators. An expression in python can
be evaluated and which then produces a result.
Eg: (3+4)/10 a+5*2
Statement
A statement is a programming instruction that does
something; ie, some action takes place.
Variables
A variable is a named storage location whose values
can be used and processed during the program run.
Eg: >>>x=3
>>>y=4
>>>z=x+y >>>z=z+1
>>>x=y
>>>y=5
A variable has three main components:- 1.
Identity of the variable
It refers to the address in the memory which does
not change once it has been created. The address
of a variable can be checked using the function id().
Syntax:-
>>>id(variable name)
Eg:- >>>x=100
>>>id(x)
1614996384; which is the address of memory
location storing the value 100.
2. Type of the variable
The type of the variable determines the data type
of it. Data type refers to the type of the data
associated with a variable. The function type()
determines the data type of a variable.
Syntax:-
>>>type(variable name)
Eg: >>>x=100
>>>type(x)
‘class int’
>>>y=100.5
>>>type(y)
‘class float’
>>>z=’haai’
>>>type(z)
‘class str’
3. Value of the variable
To bind value to a variable, we use the assignment
operator(=). This process is termed as building of a
variable.
The concept of assignment operator can be
explained as:
 There should be one and only one variable on
the left hand side of the assignment operator.
 This variable is called Left-value or L-Value
 There can be any valid expression, literal or
variable on the right hand side of the
assignment operator
 This expression in called the Right-value or
RValue.
 The statement L-Value=R-Value is the
assignment statement.
input () function
In Python, To get input from the user interactively, we can
use the built-in function input().
Syntax:-
Variable-name=input(“<message to be displayed>”)
The input() function always returns a value of String type. But
string values cannot be used for numeric operations. So to
input numeric values, Python offers two functions int() and
float() to be used with input () to convert the values received
through input () function.
Syntax:-
Variable-name=int(input(“<message>”))
Variable-name=float(input(“<message>”))

Multiple Assignments1
1. Assigning same value to multiple variables
We can assign same value to multiple variables in a single
statement in python.
Eg: >>>a=b=c=10
In the above statement, the value 10 is assigned to all three
variables a, b and c.
2. Assigning multiple values to multiple variables
We can assign multiple values to multiple variables in a
single statement in python.
Eg: >>>x,y,z=10,20,30
The above statement will assign the values order wise. Ie
first variable is given first value, second variable the
second value and so on. Ie The above statement will assign
values 10 to x , 20 to y and 30 to z.
Note:
In Python when we want to swap two values, we need to
write
>>> x,y=y,x
The above statement will swap(exchange ) the values of x
and y.
Eg: >>>x=10
>>>y=5
>>>x,y=y,x
After executing the above statement, the values of x and y
are swapped ie
>>>x=5
>>>y=10

4. DATA HANDLING
Python provides a predefined set of data types for handling
the data it uses. Data can be stored in any of the data types.
Data type
It is the way to identify the type of data stored in a variable.
Data can be of many types. Python offers the following
built-in core data types:
Core Data Types
Numbers Sequences Mappings (Sets) None
Integer-----bool Strings Dictionary.
Floating point Lists
Complex Tuples
1. Numbers
Number data types are used to store numeric values in
Python. The Numbers in Python have following core
data types:-
i) Integers
Integers are whole numbers that have no fractional
parts. It can be positive or negative. There are two
types of integers in Python:
a) Integers (signed):- It is the normal integer
representation of whole numbers. Python 3.x
provides a single data type called int to store any
Integer; whether big or small.
b) Boolean:- These represent the truth values False
and True. The Boolean type is a subtype of
integers as the Boolean values (True or False)
represents 1 or 0 respectively. It is represented
by the data type bool.
ii) Floating point Numbers
A number having fractional part is a floating point
number. For eg: 3.14159 is a floating point number.
The data type used to represent a floating number
is float.
The two advantages of floating point numbers over
integers are:
 They can represent values between the
integers.
 They can represent a much greater range of
values.
Disadvantage over integers:-
 Floating point numbers are usually slower
than integer operations.
iii) Complex Numbers
A complex number is of the form a+bi where i is an
imaginary number.
Python represents complex numbers in the form of
a+bj. ie to represent imaginary number python
uses
‘j’ in place of traditional ‘i’.
For eg: x=0+3.1j
y=1.5+2j
The data type used to represent a complex number
is complex .
2. Sequence Data types
i) Strings
A string is a character or a group of characters
enclosed with in single, double or triple quotes. In
Python 3.x, each character stored in a string is a
Unicode character. Unicode is a system designed to
represent every character from every language. The
data type used to represent a string is str.
ii) Lists
A list in Python represents a list of comma
separated values of any data type enclosed between
square brackets. Eg: a=[1,2,3,4]
B=[‘a’,’e’,’i’,’o’,’u’]
C=[1,100.45,’hai’,’r’] iii)
Tuples
Tuples are represented as group of comma-separated
values of any data type with in simple parentheses.
Eg: t=(1,2,3,4)
A=(1,’a’,’e’,100.5)
3. Mappings i) Dictionary
The dictionary is an unordered set of comma
separated key:value pairs with in curly-brackets {
}. Eg: d={‘a’:1,’e’:2,’i’:3,’o’:4,’u’:5}.

The data type used to store a dictionary is dict.


OPERATORS
The symbols that trigger an operation/action on data are
called Operators. The operations are represented by
operators and objects of the operands are referred to as
Operands.

Python provides the following operators:-


1. Arithmetic Operators
Python provides two types of arithmetic operators. They are
a) Unary Operators
The operators that act only on one operand is referred
to as Unary operator.
Unary + and Unary – are the two operators.

Eg: if a=5 then +a means 5 (Unary +)


If a=-5 then +a means -5 (Unary -)
b) Binary Operators
Operators that act upon two operands are referred to as
binary operators. The binary operators in Python are: i)
Addition Operator (+)
It adds the values of its operands and the result is
the sum of the values of its two operands.
Eg: 5+10 results 15 ii)
Subtraction Operator(-)
It subtracts the second operand from the first.
Eg: 5-10 results -5 iii)
Multiplication Operator(*) It
multiplies the value of its
operands.
Eg: 5 * 10 results 50 iv)
Division Operator (/)
It divides its first operand by the second operand
and always returns the result as a float value
Eg: 4/2 results 2.0
5/2 results 2.5
v) Floor Division Operator(//)
It performs the floor division, that is the division in
which only the whole part of the result is given in
the output and fractional part is truncated.
Eg: 5//2 results 2.0
6.5 // 2 results 3.0
4//2 results 2 vi)
Modulus operator (%)
It finds the remainder of its first operand relative to
the second. That is it produces the remainder of
dividing the first operand by the second operand.
Eg: 10 % 2 results 0
19 % 6 results 1
5 % 3 results 2 vii)
Exponentiation Operator (**)
It performs exponentiation (power) calculation.
that is it returns the result of a number raised to a
power.
Eg: 5 ** 2 results 25
3 ** 3 results 9
10 ** 3 results 1000

Augmented Assignment Operator


Python has an assignment operator = which assigns the value
specified on the RHS to the variable on the LHS of ‘=’. Python
also offers augmented assignment arithmetic operators,
which combine the impact of arithmetic operator with an
assignment operator.
If you want to add value of b to a and assign the result to
a, then instead of writing a=a+b, we can write a+=b.

2. Relational Operators
Relational operators determine the relation among
different operands. Python provides six relational
operators for comparing values (thus also called
comparison operators). If the comparison is true, the
relational expression results into the Boolean value True. If
the comparison is false, the relational expression results
into the Boolean value False.
The six relational operators are:
< (less than) > (greater than) <=(less than or equal to)
>= (greater than or equal to) ==(equal to)
!= (not equal to)
Example

p q p<q p>q p<=q p>=q p==q p!=q


3 30 True False True False False True
6 4 False True False True False True
‘A’ ‘A’ False False True True True False
‘A’ ‘a’ True False True False False True
‘god’ ‘God’ False True False True False True
3. Identity Operators
There are two identity operators in Python. They are
i) is ii) is not
They are used to check if both of its operands points to the
same memory location and also returns True or False
accordingly.
4. Logical Operators
Python provides three logical operators to combine
existing expressions. These are or, and & not.
i) The or Operator
The or operator combines two expressions, which
makes its operands. The or operator evaluates to
True if either of its operands (expressions)
evaluates to True; False if both operands evaluates
to False.
E.g. >>>(5>10) or (5%2==1) results True
>>>(6>10) or (10<6) results False ii)
The and Operator
The and operator combines two expressions, which
makes its operands. The and operator evaluates to
True if both of its operands evaluates to True; False
if either or both operands evaluates to False. E.g.
>>> (5>10) and (5%2==1) results False >>> (6<10)
and (10>6) results True.
iii) The not operator
The Logical not operator works on a single
operand. i.e it is a unary operator. The logical not
operator negates the truth value of an expression.
That is if the expression is true, the not expression
results a False value and vice versa.
e.g. >>> not 5 results a False value because 5 is
non-zero.
>>> not 0 results a True value
>>>not(5>10) results True
Write a program to obtain a number ‘N’ and print
N2, N3 and N4.
Write a program to calculate the radius of a sphere
whose area is 𝐴=4𝜋𝑟2 is

Expression
An expression in Python is any valid combination
of operators, literals and variables. The
expressions in python can be of 5 types:- 1.
Arithmetic Expression a+b-c
2. Relational expression a<=b
3. Logical expression a and b not c
4. String ‘hello’+’welcome’
5. Compound a+b>c or a*b<c*d
DEBUGGING
Debugging refers to the process of locating the
place of error, cause of error and correcting the code
accordingly.
ERRORS IN A PROGRAM
An error is sometimes called a ‘bug’. There are broadly
three types of errors.
1. COMPILE-TIME ERRORS
2. Run-time errors
3. Logical errors.
1. Compile time errors
Errors that occur during compile time are compile time
errors. When a program compiles, its source code is
checked for whether it follows the programming
language’s rules or not.
There are two types of compile time errors.
1. Syntax error
Syntax errors occur when rules of a
programming language are violated. Eg: x <--
Y*Z
2. Semantic error
It occurs when statements in a program are not
meaningful. Eg: X * Y=Z
2 Run-time errors
Errors that occur during the execution of a program are run
time errors. These errors are harder to detect. Some
runtime errors stop the execution of the program.
3 Logical errors
Sometimes, if there is no error during compile time and run
time, the program code doesn’t work. This is because of the
programmer’s mistaken analysis of the problem he/she is
trying to solve. Such errors are called logical errors.
Flow of Control Types of Statements in Python
Statements are the instructions given to the computer to
perform any kind of action; be it data movements and be it
making decisions or be it repeating actions. Python
statements can be of three types:-
1. Empty statement (Null statement)
The simplest statement is the empty statement. i.e, a
statement which does nothing.In python an empty
statement is the ‘pass’ statement. Whenever python
encounters a pass statement, Python does nothing and
moves to the next statement in the flow of control.

2. Simple Statement
Any single executable statement is a simple statement
in python. For e.g.
print(“hello”) n=input(“Enter
Name”) .
3. Compound statement
A compound statement represents a group of
statements executed as a unit. The compound
statements of python are written in a specific pattern
as follows:-
<compound statement header>:
<intended body containing simple or multiple
statements>
Statement Flow Control
In a program, statements may be executed
sequentially, selectively or iteratively. Every
programming language provides constructs to support
sequence, selection and iteration.
1. Sequence Construct
In this construct, the statements are being executed
sequentially. This represents the default flow of
statement.
Every python program begins with the first
statement of the program. Then each statement in
turn is executed. When the final statement of the
program is executed, the program is done. Sequence
is the normal flow of control in a program.

2. Selection Construct
In this construct, the execution of statements
depending upon a condition-test. If a condition
evaluates to True, a set of statements is executed,
otherwise another set of statements is executed..
This construct is also known as Decision construct
because it helps in making decision about which set
of statements is to be executed.
3. Iteration Construct
In this construct, repetition of a set of statements
depending on a condition test. A set of statements
are repeatedly executed (again and again) until a
condition becomes False and When the condition
becomes False, the repetition stops. This construct is
also known as Looping Construct.

Python provides statements that support the


Selection construct.
1. The simple ‘if’ statement
The if statements are the conditional statements in
Python and these implement selection constructs.
(decision constructs).
An if statement tests a particular condition; if the
condition evaluates to True, a statement or set of
statements are executed. Otherwise those
statements are ignored.
The syntax of if statement is as follows:- if
<conditional expression>:
statement
where the statement may consist of a single
statement or a compound statement.
2.The if-else statement
This form of if statement tests a condition and if the
condition evaluates to True, the statements followed
(intended) below the ‘if’ will be executed. And if the
condition evaluates to False, the statements followed
(intended) below the ‘else’ part will be executed.
The syntax of if-else statement is as follows:-
if <conditional expression>:
statement/ statements
else:
statement/statements
Note: - The block below if gets executed if the condition
evaluates to True and the block below else gets executed if
the condition evaluates to False.

3.The if-elif Statement

if condition:
statements elif
condition:
statements elif
condition:
statements

.
.
.
Else:
Statements
4. The Nested if statement
If <condition>:
If <condtion>:
Statements Else:
statements
Else:
If <condtion>:
Statements Else:
statements
Iteration/Looping Statements
The iteration statements or looping statements allow a set of
instructions to be performed repeatedly until a certain
condition is fulfilled. The iteration statements are also called
loops. Python provides two kinds of loops:- for loop and
while loop which represents two categories of loops. They
are
1. Counting loops:- the loops that repeat a certain number
of times. Python’s for loop is a counting loop
2. Conditional loops:- the loops that repeat until a certain
condition become False. Python’s while loop is a
conditional loop.
The for loop
The Synatx of a for loop is as given below:- for
<control variable> in <sequence>:
Body-of-Loop // Statements to repeat.
A for loop in Python is processed as:
Step 1: The loop variable is assigned the first value in the
sequence.
Step 2: All the statements in the body of for loop are
executed with assigned value of a loop variable
Step 3: Once step 2 is over, the loop variable is assigned to
the next value in the sequence and the loop body is
executed (ie step 2 repeated) with the new value of the
loop variable.
Step 4: This continues until all values in the sequences are
processed.
Note:-
1. for loop ends when the loop is repeated for the last
value of the sequence.
2. The for loop repeats n number of times, where n is the
length of the sequence given in for loop’s header.
The range() function
The range() function of Python in normally used with the
python for loop. It generates a list which is a special
sequence type. The common use of range() is in the
following forms:-
1. range(n):- This type of range() function creates a list
from 0 to n-1; where n is an integer.
Eg: range(5) produces a list [0,1,2,3,4]
2. range(<lower limit>, <upper limit>):- This range()
function will produce a list having values from l,
l+1,l+2,-------u-1.(l and u being integers). Eg:
range(0,5) produce a list [0,1,2,3,4]
Range(5,10) produce a list [5,6,7,8,9]
3. range(<l>,<u>,<stepvalue>):- This type of range()
function will produce a list having values as l,l+s,l+2s,-
----<=u-1.
Eg:- range(0,10,2) will produce a list [0,2,4,6,8]
range(10,50,10) will produce a lsit [10,20,30,40]

Conditional loop-The while loop


A while loop is a conditional loop that will repeat the
instructions within it as long as the condition remains True.
The general form of python while loop is as follows:-
Initialization expression
while test-condition:
<body of loop>
Update expression (also with in loop body)

Parts of a while loop


1. Initialization expression:- Before entering in a while
loop, its loop variable must be initialized. The
initialization expression gives a first value to the
loop control variable. It must be specify outside the
while loop before it starts.
2. Test condition:- It is an expression whose truth
value(True/False) decides whether the loop-body
will be executed or not. If the test condition
evaluates to True, then the loop-body gets
executed, otherwise the loop is terminated.
3. The Body of Loop:-The statements that are
repeatedly executing forms the body of loop.
4. Update expression: - It changes the value of the
loop control variable. The update expression is
given as a statement inside the body of while loop.

Note:-
I. In a while loop, control variable should be
initialized before the loop begins, as an
uninitialized variable cannot be used in an
expression.
II. If the update expression is missing inside a while
loop, then such types of loops are called endless
loops or infinite loops.
Eg: i=1
while i<=10:
print(i)
HW.
1. Write a python program to print the series from 1
to 100 using while loop.
2. Write a python program to print the first ‘n’ even
series using while loop.
3. Write a python program to find the sum of first ‘n’
natural numbers using while loop
Note:
• Nested loop is one loop inside another loop
• Once the condition of the outer loop is true,
the control is transferred to the inner loop,
first the inner loop is terminated and then the
outer loop terminates.
• The inner loop must have a different name for
its loop counter variable so that it will not
conflict with the outer loop.
JUMP Statements
Jump statements are used to transfer the program
control flow unconditionally. Python offers two
jump statements to be used with in loops to jump
out of loop iterations. The jump statements are,
1. break
The break statement enables a program to skip
over a part of code. When the break statement
gets executed, it terminates the execution from the
smallest enclosing loop and then the control
reaches to the statement immediately following
the loop.
2. continue
The continue statement forces the next iteration of
the loop to take place, by skipping any code in
between. The program control resumes (continues)
the next iteration of the loop after executing the
continue statement.

HW
1. WAP to input a digit (0-9) and print it in words.
2. WAP to print the first ‘n’ odd numbers in
descending order.
3. Write a program to print the following pattern
4321
432
43
4
1
1 1
11 1
111 3
1111 17
6. STRING MANIPULATION
In python, a group of characters enclosed
between single or double quotation marks is
known as a string.
Creating Strings
Strings are the most popular data types in python. We can
create them by simply enclosing characters in single, double,
or triple quotes. Python treats single quotes the same as
double quotes. Triple quotes are generally used to represent
multi line strings.
An empty string is a string that has 0 character.
Example: >>> str1=”Hello world”
>>>str2= ‘Python Programming’
Special String Operators
1. Concatenation operator (+)
The ‘+’ operator creates a new string by concatenate
(joining) two operand strings.
>>>’1’+’1’ results ‘11’
>>>’A’+’pple’ results ‘Apple’
>>>’tea’+’ pot’ results ‘tea pot’
>>>”123”+”abc” results “123abc”
Note:- We cannot combine numbers and strings as operands
with a ‘+’ operator.
Eg:>>> ‘111’ + 1 is an invalid operation
>>> ‘abc’ + 3 is an invalid operation
2. Replication operator (*)
The ‘*’ operator creates a new string by repeating
multiple copies of the same string.
Eg: >>> ‘abc’ * 3 returns ‘abcabcabc’
>>>’1’ * 2 returns ‘11’
>>> ‘@’ * 5 returns ‘@@@@@’
Note:- While using replication operator, one operand must
be string type and other must be of number type. It cannot
work with both operands of string type.
3. Membership Operators
There are two membership operators for strings. These
are in and not in.
a) in :- It returns True, if a character or a substring
exists in the given string: False otherwise
b) not in:- It returns True, if a character or a substring
does not exist in the given string; False otherwise
Both membership operators require that both
operands used with them are of string type.
Syntax:
<character/substring> in <String>
<character/substring> not in <String>
Eg: >>>’a’ in ‘abcd’ returns True
>>>’’Jap’ in ‘’Japan” returns True
>>>’aa’ in ‘Hello’ returns False
>>>’’1234’ not in ‘12345’ returns False
>>> ‘’jap” not in “Japan” returns True Traversing
a String
Traversing a string means accessing all the elements of the
string one after the other by using the subscript or index
value.
Each character in a string has an index value which starts
from 0 and ends with length-1.(string length: total no of
characters in the string)
Individual elements can be accessed by specifying string
variable name along with index value, enclosed in square
brackets.
Example: s=”Hello World”
>>>s[0] represents the character ‘H’
Character Representation in a string
S=”Python Programming”
Forward 01 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1
indexing( 0 1 2 3 4 5 6 7
positive
index)
String S Py t ho n P r og r a m mi n g
Backward - - - - - - - - - - - - - -
indexing 1 1 1 1 1 9 8 7 6 5 4 3 2 1
(negative 4 3 2 1 0
index)

Note:- To access any character from a string, we use the


square brackets along with the index.
Eg: S[1]=’y’
S[5]=’n’
S[-7]=’r’

Iterating through the string


Each character of the string can be accessed sequentially
using for loop.
Eg: for j in “Python”:
Print(j)
Output:-
P
yt
h
o
n
String Slices
String Slice refers to the part of a string, where strings are
sliced using range of indices. Part of a string containing some
contiguous characters from the string.
For a string, say str=”amazing”, we can slice the string str in
the following ways:-
1. str[n:m]- where n is the starting index and m is the
ending index, then python will return a slice of the string
by returning the characters falling between n and m,
starting from n, n+1,n+2,--------,m-1.

0 1 2 3 4 5 6
a m a z i n g
-7 -6 -5 -4 -3 -2 -1

Then,
str[0:7] will return string slice as
‘amazing’ str[0:3] will return ‘ama’
str[2:5] will return ‘azi’
str[-7:-3] will return ‘amaz’ str[-5:-1]
will return ‘azin’
Note:- In a string slice, the character at last index is not
included in the result.
2. In a string slice, slicing range in the form str[ : m], where
m is the ending index and starting index is missing;
python will consider the starting index as 0. Then it will
extract the substring from beginning until the last
index1 .(m-1)
Str [ :7] will return ‘amazing’
Str[: 5] will return ‘amazi’
3. In a string slice, slicing range in the form str[n: ], where n
is the starting index. Here for the missing last index,
python will consider the length of the string. Then it will
extract the substring from starting index to length of the
string.
Str[3:] will return ‘zing’
Str[5:] will return ‘ng’
4. For any index n, str[:n] + str[n:] will give the original
string.
Str[:7] + str[7:] will give the string ‘amazing’

5. We can give a third value in string slice.


Eg: str[1:6:2] will take every 2nd character starting from
first index until less than 6(end index)
>>>str[1:6:2] will return ‘mzn’
>>>str[-7:-3:3] will return ‘az’
>>>str[: : -2] will return ‘giaa’
>>>str[: : -1] wil return ‘gnizama’ (The reverse order of
the string)
STRING FUNCTIONS AND METHODS Built-in
functions
1. len ()- It returns count of characters in the passed string.
Syntax:- len(string)

Eg: >>> len(“Hello”)


5
>>>name=”Maria”
>>>len(name)
5
2. capitalize():- It returns a copy of the string with its first
character capitalized.
Syntax:- <string.capitalize()>
Eg: >>>’hello’.capitalize
Hello
>>>’i love India’.capitalize() I
love India
3. count() :- It returns the number of occurrences of a
substring ‘sub’ in the string.
Syntax:- <string>. count(sub, start, end)
4. find():- It returns the lowest index in the string where
the substring ’sub’ is found within the slice range of
start and end. Returns -1 if sub is not found. Syntax:-
<string>.find(sub, start, end)
5. index():- It returns the lowest index where the specified
substring is found. If the substring is not found, then an
exception , ValueError, is raised.
Syntax:-<string>.index(sub, start, end)
6. isalnum():- It returns True if the characters in the string
are alphanumeric(alphabets or numbers) and there
must be at least one character. Syntax:-
<string>.isalnum()
7. isalpha():- It returns True, if all characters in the string
are alphabetic. Otherwise it returns False. There must
be at least one character in the string. Syntax:-
<string>.isalpha()
8. isdigit():- It returns True, if all the characters in the string
are digits. Otherwise it returns False. Syntax:-
<string>.isdigit()
9. islower():-It returns True, if all alphabets in the string are
in lower case(small letters). Otherwise it returns False.
Syntax:- <string>.islower()
10 . isupper():-It returns True, if all alphabets in the
string are in upper case(capital letters). Otherwise it
returns False.
Syntax:- <string>.isupper()
11 isspace():- It returns True, if there are only white
space characters in the string. Otherwise it returns
False
Syntax:- <string>.isspace()
12 lower():- It returns a copy of the string converted
into lowercase.
Syntax:- <string>.lower()
13 upper():-It returns a copy of the string converted
into uppercase.
Syntax:- <string>.upper()
14 title():- It returns a title-cased version of the string
where all words starts with uppercase characters
and all are remaining in lower case.
Syntax:- <string>.title()
15 replace():- It returns a copy of the string with all
occurrences of the substring ‘old’.
Syntax:- <string>.replace(old, new)

16 strip():- It returns a copy of the string with leading


and trailing white spaces removed; ie, white spaces
from both leftmost and right most ends are
removed.
Syntax:- <string>.strip()
17 lstrip():-It returns a copy of the string with leading
white spaces removed; ie, white spaces from
leftmost end is removed.
Syntax:- <string>.lstrip()
18 rstrip():-It returns a copy of the string with trailing
white spaces removed; ie, white spaces from
rightmost end is removed.
Syntax:- <string>.rstrip()
19 split():- It splits a string based on a given character or
a string and returns a list containing split strings as
members.

Syntax:- <string>.split(character/string)
20 partition():- This method (function) splits the string
at first occurrence of separator and
returns a tuple containing three
items. They are
 The part before the separator
 The separator itself
 The part after the separator
Syntax:- <string>.partition(separator/string)
7.LIST MANIPULATION
List is a collection of comma-separated heterogeneous (different
types) values that are enclosed with in square brackets. It is a
sequenced data type in Python.
Creating a list
Syntax:-
<list-name>=[value1, value2, value3,----]
Eg: >>>list1=[10,20,30,40] #list of integers
>>>list2=[“blue”,”red”,”orange”,”green”] # list of strings
>>>list3= [‘a’,’e’,’I’,’o’,’u’] # list of characters
>>>list4=[10,”red”,450.60,’a’,100.3] # list of multiple data types
>>>list5=[10,[1,2,3,4],20,40] # a list containing another list- Nested
List.
>>>list6=[ ] # empty list – list with no elements
Traversing a list
Traversing a list means accessing each element of a list. Traversing
can be done in two ways:-
1. Using in operator inside for loop
The elements of a list can be accessed individually using for
loop as follows:-
2. Using range() function
The range() function can also be used for accessing the
individual elements in a list as follows:-
LIST OPERATIONS
Python provides some basic operations which can be performed on
lists as follows:-
1. Concatenation (+)
It is a process in which multiple sequences/lists can be
combined together with the help of concatenation operator
(+). Python allows adding (joining) of two lists using +
operator. For eg:-
2. Replication (*)
The replication operator(*) replicates the list for a specified
number of times.
3. Membership operators (in & not in)
Membership testing is an operation carried out to check
whether a particular element is a member of that list or not.
LIST FUNCTIONS AND METHODS
Python offers may built-in functions and methods for list
manipulation. The following are the list manipulation methods in
Python.
1. len() :- It returns the length of its argument list. i.e, it returns
the total number of elements in the list passed. Syntax:-
len(<list>)
2. index () :- This function returns the index of first matched item
from the list.
Syntax: - <list>.index (Item)
3. append():- The append() method adds a new item to the end
of the list.
Syntax:- <list>.append(<item>)
4. extend ():- This method is used for adding multiple elements
(given in the form of a list) to an already existing list. Syntax: -
<list>.extend (<list>)
5. insert () :- This function can be used to insert a new element
at a specified index. It takes two arguments: one is the index
where an item is to be inserted and other is the item itself.
Syntax:- <list>.insert(index_number, item)
6. count() :-This function returns the number of occurrences of a
particular item present in the list. Syntax :-
<list>.count(<item>)
7. reverse():- This function reverses the order of elements in a
list. It places a new value ‘in place’ of an item that already
exist in the list. i.e, it does not create a new list Syntax
:- <list>.reverse()
8. clear() :- This method removes all items from the list. It
doesn’t take any parameters. It only empties the given list. It
doesn’t return any value. Syntax:- <list>.clear()
9. sort() :- This function sorts the items of the list either in
ascending order or in descending order. The default order is
ascending.
Syntax:- <list>.sort()
To sort a list in descending order we can write the sort ()
function as
<list>.sort(reverse=True)
10 sorted ():- The sorted() function takes the name of the
list as an argument and returns a new sorted list with
sorted elements in it. Syntax:- sorted(<list>)
Deletion operations in a List
Python provides functions for deleting or removing an item
from a list. There are three methods for deletion
1. If index of the item is known, use pop() or del statement
2. If the element is known, not the index, remove() can be
used
3. To remove more than one element, del with list slice can be
used.
11. pop() :- It removes the element from a specified index
and also returns the element which was removed.If no index
value is provided in pop() function , then the last element is
deleted from the list.
Syntax:- <list>.pop(index)
12. remove():- It is used when we know the element to be
deleted but not the index of the element.
Syntax:- <list>.remove(<element>)
13. del statement:- It removes a specified element or a
range/slice of element from the list. Syntax:- del
list[range/slice] The max(), min() and sum() functions
max() :- It returns the element with a maximum value from
the list.
Syntax:- max(<list>)
min():- It returns the element with a minimum value from the
list.
Syntax:- min(<list>) sum():- It returns the sum of all
elements from the list.
Syntax:- sum(<list>)

TUPLES
Tuple is a sequence data type in python which is similar to a list.
A tuple consists of different types (heterogeneous) of values separated
by commas and are enclosed with in simple parentheses.
The main difference between lists and tuples are:
Lists are enclosed with in square brackets [], and their elements and size
can be changed; while tuples are enclosed with in simple parentheses (),
and their elements cannot be updated.
Creating Tuples
A tuple is enclosed in parentheses () for creation and each item is
separated by comma.
Creating tuple with a single element
To create a tuple with a single element, we have to include the final
comma. The final comma is mandatory, otherwise it is not considered as
a tuple, rather treated as a string or an integer.
WAP to create a tuple by accepting user input.(use tuple () function)

Accessing and traversing a tuple


The individual elements of a tuple can be accessed through their indices
given in square brackets. For example a tuple, T=(10,20,30,40,50) can be
accessed as:
Forward 0 1 2 3 4
index(Positive
indexing)
10 20 30 40 50
Backward -5 -4 -3 -2 -1
index
(Negative
indexing)

T [1] = 2o, T[-2]=40, T[-5]=10


Traversing a tuple means accessing each element in the tuple. This can
be done by either for or while loop.

1. Using in operator (for loop)


2. Using range() Function
TUPLE OPERATIONS

1. Slicing
Slicing is used to retrieve a subset of values. A slice of a tuple basically
its sub-tuple.
Syntax:-
Tuple-name [start: stop: step-value]
Where start is the starting point
Stop is the ending point
Step is the step-size (stride)
2. Tuple Addition(concatenation)
New elements can be added to a tuple using ‘+’ operator.
3. Tuple Multiplication(Replication)
The operator (* ) is used for replication of the tuple
4. Membership operators (in and not in)
The in operator checks whether a given element is contained in a
tuple. It returns True if element is present in the tuple. Otherwise it
returns False.

The not in operator returns True, If the element is not found in the
tuple. Otherwise it returns False.

TUPLE FUNCTIONS AND METHODS


Python offers may built-in functions and methods for TUPLE
manipulation. The following are the tuple manipulation methods in
Python.
1. len():- This function returns the length of the tuple,
i.e., the count of elements in the tuple. Syntax: -
len(<tuple>)
2. count:- This function is used to count the occurrences of an
item in a tuple.
Syntax:- <tuple>.count(<item>)
3. index():- It returns the index of an existing element of a tuple.
Sytax:- <tuple>.index(<item>)
4. sorted():-The sorted() function takes the name of the
tuple as an argument and returns a new sorted list
with sorted elements in it.
Syntax:- sorted(<tuple>)
5. min() :- It returns the element with a minimum value
from the tuple.
Syntax:- min(<tuple>)

6. max() :- :- It returns the element with a maximum


value from the tuple
Syntax:- max(<tuple>)
7. sum():- It returns the sum of all elements from the
tuple. For sum() to work, all elements must have
numeric values.
Syntax:- sum(<tuple>)
Deleting a Tuple
The del statement is used to delete a tuple.
Syntax:- del <tuple>

MUTABLE AND IMMUTABLE DATA TYPES


The Python data objects can be broadly categorized into two types:-
1. Mutable types
The mutable types are those types whose values can be
changed in place. The mutable data types in python are Lists
and Dictionaries.
Even after changing the value in the list (updated the list using
append function), the memory address of the list ‘l’ remains
the same. That means the change has taken place in the list.

2. Immutable types
The immutable types are those types that can never change
their value in place. The immutable data types in python are
Numbers (Integers, floating point and booelan), Strings and
Tuples.

Note:-
Mutability means that, new value can be stored in the same
memory address as and when we want. But in immutable
types we cannot update the value once it is defined.
DICTIONARY
Dictionary is a very versatile data type in Python. It is an
unordered collection of items where each item is represented
as a key: value pair.
Features of a dictionary
1. Each key map to a value. The association of a key and a value
is called a key-value pair.
2. Each key is separated from its value by a colon (:), the items
are separated by commas, and the entire dictionary is
enclosed with in curly brackets. { }
3. Keys are unique (Immutable types) with in a dictionary while
values may not be.
4. The value of a dictionary can be of any type, but the keys
must be of an immutable types such as numbers, strings or
tuples.
5. Dictionary is a Mutable type. We can add new items or
change the value of existing items.
Creating a dictionary
A dictionary can be created by placing items as key: value pairs
inside curly braces separated by comma.
Syntax:
<dictionary_name> =
{key1: value1, key2:value2, key3:value3, key n: value n}
Methods to create a dictionary
Method 1:-
To create an empty dictionary, put two curly braces.
>>>d1 = { }
>>>type(d1)
<class ‘dict’>
Method 2:-
To create a dictionary, key-value pairs are separated by comma
and are enclosed in curly brackets, { }
Method 3:- using built-in Function dict()
The function dict() is used to create an empty dictionary, that is
a dictionary with no items.
Accessing Elements in a dictionary
To access dictionary elements, we can use the square brackets
along with the key to obtain its corresponding value. Traversing
a Dictionary
Traversing a dictionary means accessing each element of a
dictionary. This can be done by using a for loop.

Appending Values in a dictionary.


We can add new elements to the existing dictionary, extend it with
a pair of values. If we want to add only one element to the
dictionary, Then the syntax is as follows:- <dictionary
name>[key]=value
Updating elements in a dictionary
We can update a dictionary by modifying existing key-value pair or
by merging another dictionary to the existing one.
Two dictionaries can be merged into one using update () method. It
merges the keys and values of one dictionary into another and
overwrites values of same key.
Membership operators (in and not in)
The in operator checks whether a particular key is there in the
dictionary. It returns True, if the element appears in the dictionary.
Otherwise returns False.
Dictionary Functions and Methods
1. len() :- It returns the number of key-value pairs (items) in the
dictionary.
2. clear() :- It removes all items from the particular dictionary.
Syntax:- <dictionary>.clear()
3. get() :- The get () method returns a value for the given key. If
key is not available , then returns ‘None’ value. Syntax:-
<dictionary>.get(key, default=None) where key- This
is the key to be searched
default- This is the value to be returned in case the key
does not exist.
4. Items ():- It returns the content of dictionary as a list of
tuples having key-value pairs. Syntax:- <dictionary>.items()
5. Keys():- It returns a list of keys in a dictionary. Syntax:-
<dictionary>.keys()
6. Values():-It returns a list of values from key-value pairs in a
dictionary.
Syntax:- <dictionary>.values()
Deleting elements from a dictionary
1. del statement:- To delete a dictionary element or an entire
dictionary, i.e, a key: value pair, we can use del command.
Syntax:- del <dictionary>[key]
If we want to delete the whole dictionary, then Syntax is:- del
<dictionary name>
2. pop() :- This method will delete the specified item from the
dictionary and also return the deleted value.
Syntax:-
<dictionary>.pop(key)
3. popitem():- The popitem() method removes and returns a
tuple of (key,value) pair from the dictionary.
Some important things to notice about popitem() are
• It returns the item which was the last item entered in the
dictionary. This function follows a LIFO (Last In First Out)
structure for removing items from a dictionary.
• It returns the deleted element (key:value pair) in the form
of a tuple as (key,value)
• If the dictionary is empty, popitem() method will raise a
KeyError.
Syntax:-
<dictionary>.popitem()
The fromkeys() Method
The fromkeys() method is used to create a new dictionary from a
sequence containing all the keys and a common value, which will be
assigned to all the keys.
Syntax: - dict.fromkeys (<Key sequence>, [value]) where
Key sequence is a python sequence (list, string or tuple) containing
the keys for new dictionary.
Value is the common value that will be assigned to all the keys. If
value is skipped ‘None’ is assigned to all keys.
The setdefault() Method
The setdefault() method inserts a new key: value pair in an existing
dictionary ONLY IF THE KEY DOESN’T ALREADY EXIST. If the KEY
ALREADY EXISTS, it returns the current value of the key.
Syntax:-
<dictionary>.setdefault(<key>,<value>) where
Key and value are the key: value pair added to the dictionary. If value
is not passed, then ‘None’ value is used.
This function works in two ways:-
i. If the given key is NOT ALREADY PRESENT in the dictionary, it
will add the specified new key: value pair to the dictionary and
return the value of the added key.
ii. If the given key is ALREADY PRESENT in the dictionary, the
existing value will not be updated, but the current value
associated with the specified key is returned.

You might also like