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

Python Notes 2021

The document discusses various Python data types including strings, lists, tuples, sets and dictionaries. It provides examples and explains different methods that can be used for each data type.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Notes 2021

The document discusses various Python data types including strings, lists, tuples, sets and dictionaries. It provides examples and explains different methods that can be used for each data type.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

1.

Python and its features:


Python is the world's most popular and fastest-growing computer
programming language. It was developed by Guido van Rossum in
1991.

Features of Python:
1. Python is a widely used general-purpose, high level programming
language.

2. Python a procedure, object oriented and functional programming


language.

3. Python is a scripting language used to design dynamic web


applications.

4. Python is a dynamic typed programming language.

5. Python is a cross-platform independent programming language.

6. Python is an extensible and embedded programming language.

7. Indentation is one of the greatest feature in python.

8. Python is a free and open-source programming language.

9. Python is a powerful and it is easy to learn and use.

10. Python is a portable programming language.

11. Python is an interpreted programming Language.

12. Python is an interactive programming Language


2.String data type and its methods in Python:
A string is a collection of one or more characters enclosed within a
single quote, double-quote or triple quote.
In python there is no character data type and it is represented by str
class.

Examples:

String1='Welcome to the World'


print(String1)

String methods in Python:

1.isalnum():
The isalnum() method returns True if all the characters are
alphanumeric, meaning alphabet letter (a-z) and numbers (0-9),
otherwise returns False.
Syntax:
string.isalnum()
Example:
>>> string="123alpha"
>>>string.isalnum()
True

2.isalpha():
The isalpha() method returns True if all the characters are alphabet
letters (a-z), otherwise returns False.
Syntax:
string.isalpha()
Example:
>>> string="nikhil"
>>>string.isalpha()
True

3.isdigit():
The isdigit() method returns True if all the characters are digits,
otherwise returns False.
Syntax:
string.isdigit()
Example:
>>> string="123456789"
>>>string.isdigit()
True

4.islower():
The islower() method returns True if all the characters are in lower case,
otherwise returns False.
Syntax:
string.islower()
Example:
>>> string="nikhil"
>>>string.islower()
True

5.isnumeric():
The isnumeric() method returns True if all the characters are numeric (0-
9), otherwise returns False.
Syntax:
string.isnumeric()
Example:
>>> string="123456789"
>>>string.isnumeric()
True

6.isspace():
The isspace() method returns True if all the characters in a string are
whitespaces, otherwise returns False.
Syntax:
string.isspace()
Example:
>>> string=" "
>>>string.isspace()
True

7.istitle()
The istitle() method returns True if all words in a text start with a upper
case letter, and the rest of the word are lower case letters, otherwise
returns False.
Syntax:
string.istitle()
Example:
>>> string="Nikhil Is Learning"
>>>string.istitle()
True

8.isupper()
The isupper() method returns True if all the characters are in upper case,
otherwise returns False.
Syntax:
String.isupper()
Example:
>>> string="HELLO"
>>>string.isupper()
True

9.replace()
The replace() method replaces a specified old string with another new
string.
Syntax:
string.replace()
Example:
>>> string="Nikhil Is Learning"
>>>string.replace('Nikhil','Neha')
'Neha Is Learning'

10.split()
The split() method splits a string into a list according to delimiter string.
Syntax:
string.split()
Example:
>>> string="Nikhil Is Learning"
>>>string.split()
['Nikhil', 'Is', 'Learning']

11.count()
The count() method returns the number of times a specified value
appears in the string.
Syntax:
string.count()
Example:
>>> string='Nikhil Is Learning'
>>>string.count('i')
3
12.find()
The find() method searches the string for a specified value and returns
the position of where it was found.
Syntax:
string.find(“string‟)
Example:
>>> string="Nikhil Is Learning"
>>>string.find('k')
2

13.swapcase()
The swapcase() method is used for converting lowercase letters in a
string to uppercase letters and vice versa.
Syntax:
string.swapcase()
Example:
>>> string="HELLO"
>>>string.swapcase()
'hello'

14.startswith()
The startswith() method returns True if the string starts with the
specified value, otherwise returns False.
Syntax:
string.startswith(“string‟)
Example:
>>> string="Nikhil Is Learning"
>>>string.startswith('N')
True

15.endswith()
The endswith() method returns True if the string ends with the specified
value, otherwise returns False.
Syntax:
string.endswith(“string‟)
Example:
>>> string="Nikhil Is Learning"
>>>string.endswith('g')
True

3. List data type and its methods in Python:


List is a collection of mixed data types which is ordered and changeable.
List allows duplicate members.
List is written with square brackets.

Example:
list=[501,"Raju", “1st Year”, "CSE"]
print(list)

List methods in Python:

1.append:
The append() method adds an item to the end of the list.
Syntax:
list.append(item)
Example:
>>> x=[1,5,8,4]
>>>x.append(10)
>>> x
[1, 5, 8, 4, 10]

2.extend:
The extend() method adds the specified list elements to the end of the
current list.
Syntax:
list.extend(newlist)
Example:
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>>x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]

3.insert:
The insert() method inserts the specified value at the specified position.
Syntax:
list.insert(position,item)
Example:
>>> x=[1,2,4,6,7]
>>>x.insert(2,10)
>>> x
[1, 2, 10, 4, 6, 7]

4.pop:
The pop() method removes the item at the given index from the list and
returns the removed item.
Syntax:
list.pop(index)
Example:
>>> x=[1, 2, 10, 4, 6]
>>>x.pop(2)
10
>>> x
[1, 2, 4, 6]

5.remove:
The remove() method removes the specified item from a given list.
Syntax:
list.remove(element)
Example:
>>> x=[1,33,2,10,4,6]
>>>x.remove(33)
>>> x
[1, 2, 10, 4, 6]

6.reverse:
The reverse() method reverses the elements of the list.
Syntax:
list.reverse()
Example:
>>> x=[1,2,3,4,5,6,7]
>>>x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]

7.sort:
The sort() method sorts the elements of a given list in ascending order.
Syntax:
list.sort()
Example:
>>> x=[10,1,5,3,8,7]
>>>x.sort()
>>> x
[1, 3, 5, 7, 8, 10]
8.clear:
The clear() method removes all items from the list.
Syntax:
list.clear()
Example:
>>> x=[1,2,3,4,5,6,7]
>>>x.clear()
>>> x
[]

9. length():
The len() method is used to find the number of items or values present in
a list.
Syntax:
len(list)
Example:
>>> x=[1,2,3,4,5]
>>> len(x)
5

4.Tuple data type and its methods in Python:


Tuple is a collection of mixed data types which is ordered and
unchangeable.
Tuple allows duplicate members.
Tuples are written with rounded brackets.

Example:
tuple=(501,"Raju", “1st Year”, "CSE")
print(tuple)

Tuple methods in Python:

1.count():
The count() method returns the number of times a specified value
appears in the tuple.
Syntax:
tuple.count(value)

Example:
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>>x.count(2)
4
2.index():
The index() method searches the tuple for a specified value and returns
the position of where it was found.
Syntax:
tuple.index(value)

Example:
>>> x=(1,2,3,4,5,6)
>>>x.index(2)
1
3. length():
The len() method is used to find the number of items or values present in
a tuple.
Syntax:
len(tuple)
Example:
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> len(x)
12

5.Set data type and its methods in Python:

Set is a collection of mixed data types which are unordered and


unindexed.
Set doesn‟t allow duplicate members.
Sets are written with curly brackets.

Example:
set={501,"Raju", “1st Year”, "CSE"}
print(set)

Set methods in Python:

1.add():
The add() method adds an element to the set.
Syntax:
set.add(element)

Example:
>>> x={"mrcet","college","cse","dept"}
>>>x.add("autonomous")
>>> x
{'mrcet', 'dept', 'autonomous', 'cse', 'college'}

2.remove ():
The remove() method removes the specified element from the set.

Syntax:
set.remove(element)

Example:
>>> x={1, 2, 3, 'a', 'b'}
>>>x.remove(3)
>>> x
{1, 2, 'a', 'b'}

3. length():
The len() method is used to find the number of items or values present in
a set.
Syntax:
len(set)
Example:
>>> z={'mrcet', 'dept', 'autonomous', 'cse', 'college'}
>>>len(z)
5
4.clear:
The clear() method removes all items from the set.
Syntax:
set.clear()
Example:
>>> x={1,2,3,4,5,6,7}
>>>x.clear()
>>> x
set()

5.pop():
The pop() method removes a random item from the set. This method
returns the removed item.

Syntax:
set.pop()
Example:
>>> x={1, 2, 3, 4, 5, 6, 7, 8}
>>>x.pop()
1
>>> x
{2, 3, 4, 5, 6, 7, 8}
6.Dictionary data type and its methods in Python:
A dictionary is a collection of mixed data types which is unordered,
changeable and indexed.
In Python dictionaries are written with curly brackets, and they have
keys and values.

Example:
dict={"Name":"Raju","Rollno":501,"Year":"1st Year":,"Branch":"CSE"}
print(dict)

Dictionary methods in Python:

1.update():
The update() method inserts the specified items to the dictionary.

Syntax:
dictionary.update({“keyname”:”value”})
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.update({"cse":"dileep"})
>>> dict
{'brand': 'mrcet', 'model': 'college', 'year': 2004, 'cse': 'dileep'}

2.pop():
The pop() method removes the specified item from the dictionary.

Syntax:
dictionary.pop(keyname)
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.pop("model"))
college
>>> dict
{'brand': 'mrcet', 'year': 2005}

3.items():

Returns all the items present in the dictionary. Each item will be
inside a tuple as a key-value pair.

Syntax:
dictionary.items()
Example:
dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.items()
dict_items([('brand', 'mrcet'), ('model', 'college'), ('year', 2004)])
4.keys():
Returns the list of all keys present in the dictionary.

Syntax:
dictionary.keys()
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.keys()
dict_keys(['brand', 'model', 'year'])
5.values():
Returns the list of all values present in the dictionary
Syntax:
dictionary.values()
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.values()
dict_values(['mrcet', 'college', 2004])

6.Length():
The len() method is used to find the number of items present in a
dictionary.
Syntax:
len(dictionary)
Example:
>>>x={1: 1, 2: 4, 3: 9, 4: 16}
>>> len(x)
>>> 4

7.clear():
The clear() method removes all the elements from a dictionary.
Syntax:
dictionary.clear()
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.clear()
>>> dict
{}
8.get():
The get() method returns the value of the item with the specified key.
Syntax:
dictionary.get(“keyname”)
Example:
>>> dict={"brand":"mrcet","model":"college","year":2004}
>>> dict.get("model")
'college'

7.Operators in Python:

Operators are special symbols that perform specific operations on one or


more operands (values) and then return a result.

Python has seven types of operators that we can use to perform different
operation and produce a result.

1.Arithmetic operator
2.Relational operators
3.Assignment operators
4.Logical operators
5.Membership operators
6.Identity operators
7.Bitwise operators

1.Arithmetic operators:
Arithmetic operators are used to perform different mathematical
operations between the operands.

Python has the following seven arithmetic operators.

+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
// Floor division)
℅ (Modulus)
** (Exponentiation)

2.Relational (Comparison) operators:


Relational operators are also called comparison operators. It performs a
comparison between two values. It returns a boolean True or False
depending upon the result of the comparison.

Python has the following six relational operators.

> (Greater than)


< (Less than)
== (Equal to)
!= (Not equal to)
>= (Greater than or equal to)
<= (Less than or equal to)

3.Assignment operators:
In Python, Assignment operators are used to assigning value to the
variable. Assign operator is denoted by = symbol. For example, name =
"Raju" here, we have assigned the string literal „Raju‟ to a variable
name.

Also, there are shorthand assignment operators in Python.


Python has the following assignment operators.
= (Assign)
+= (Add and assign)
-= (Subtract and assign)
*= (Multiply and assign)
/= (Divide and assign)
%= (Modulus and assign)
**= (Exponentiation and assign)
//= (Floor-divide and assign)

4.Logical operators:
Logical operators are useful when checking a condition is true or not.
Python has three logical operators. All logical operator returns a boolean
value True or False depending on the condition in which it is used.

Python has the following three relational operators.


and (Logical and)
or (Logical or)
not (Logical not)

5.Membership operators:
Membership operators are used to check for membership of objects in
sequence, such as string, list, tuple. It checks whether the given value or
variable is present in a given sequence. If present, it will return True else
False.

Python has the following two membership operators.


in
not in

6.Identity operators:
Identity operators are used to check whether the value of two variables
are same or not. If same, it will return True else False.

Python has the following two identity operators.


is
is not.

7.Bitwise Operators:
In Python, bitwise operators are used to performing bitwise operations
on integers. To perform bitwise, we first need to convert integer value to
binary (0 and 1) value.

The bitwise operator operates on values bit by bit, so it‟s called bitwise.
It always returns the result in decimal format.

Python has the following 6 bitwise operators.

& (Bitwise and)


| (Bitwise or)
^ (Bitwise xor)
~ (Bitwise 1‟s complement)
<< (Bitwise left-shift)
>> (Bitwise right-shift)

8.Conditional statements in Python:

Conditional statements are used to execute either a single statements or a


group of statements based on the condition.

There are 3 types of conditional statements in python.


1.if statement
2.if else statement
3.elif statement

1.If statement:

In conditional statements, The if statement is the simplest form.


It takes a condition and evaluates to either True or False.
If the condition is True, then the True block of code will be executed,
and if the condition is False, then the block of code is skipped, and the
controller moves to the next line.

Syntax of the if statement


if(condition):
statement 1
statement 2
statement n

Example
a=int(input('Enter any no'))
if(a>25):
print('Given no is greater than 25')

2.if else statement:


The if else statement checks the condition and executes the „if‟ block of
code when the condition is True, and if the condition is False, it will
execute the else block of code.

Syntax of the if else statement


if(condition):
statement 1
else:
statement 2

Example
n=int(input('Enter any no'))
if(n%2==0):
print('given no is even')
else:
print('given no is odd')
3. if-elif-else statement/Chained multiple if statement:
In Python, the if-elif-else condition statement has an elif keyword used
to chain multiple conditions one after another. The if-elif-else is useful
when you need to check multiple conditions.

Syntax of the if-elif-else statement


if(condition1):
statement1
elif(condition2):
statement2
elif(condition3):
statement3
...
else:
statement

Example
a=int(input('Enter the value of a '))
b=int(input('Enter the value of b '))
c=int(input('Enter the value of c '))
if((a<b) and (a<c)):
print('a is largest')
elif((b>a) and (b>c)):
print('b is largest')
else:
print('c is largest')

9.Loop/Iterative statements in Python:

In Python, iterative statements allow us to execute a block of code


repeatedly as long as the condition is True. We also call it a loop
statements.
Python provides us the following two loop statement to perform some
actions repeatedly.

1.while loop
2.for loop

1.while loop:
It is used when a group of statements are executed repeatedly until the
specified condition is true.
It is also called entry controlled loop.
The minimum number of execution takes place in while loop is 0.
Syntax:
while(condition):
statement 1
statement 2
statement n

Example
i=1
print("The nos from 1 to 10 are ")
while(i<=10):
print(i)
i=i+1

2.for loop:
In Python, the for loop is used to iterate over a sequence such as a list,
string, tuple, other iterable objects such as range.

With the help of for loop, we can iterate over each item present in the
sequence and executes the same set of operations for each item. Using a
for loops in Python we can automate and repeat tasks in an efficient
manner.

Syntax:
for var in range/sequence:
statement 1
statement 2
statement n
Example
for i in range(1,11,1):
print(i)

10.Fibonacci Sequence program in Python:


n=int(input("enter any number"))
first=0
second=1
print("fibonacci series is ")
for i in range(1,n+1,1):
print(first)
nextterm=first+second
first=second
second=nextterm

You might also like