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

python_data_Science_05_06_23 (24)

The document provides an overview of various programming languages, focusing particularly on Python, its features, data types, and usage in different applications. It discusses Python's history, versions, and key concepts such as identifiers, data types, operators, and control flow statements. Additionally, it includes examples of code snippets and explanations of Python's syntax and functionality.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

python_data_Science_05_06_23 (24)

The document provides an overview of various programming languages, focusing particularly on Python, its features, data types, and usage in different applications. It discusses Python's history, versions, and key concepts such as identifiers, data types, operators, and control flow statements. Additionally, it includes examples of code snippets and explanations of Python's syntax and functionality.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 62

Good Morning to everyone

Welcome to E page solutions

Java - Object oriented programming lang


html - Frontend technology
c - Functional procedure orinted lang.
C++ - Object oriented programming lang
.NET - Object oriented programming lang
PHP - Object oriented programming lang
R - Scripting lang
Ruby - Scripting lang
Perl - Scripting lang
Javascript - Scripting lang
react js - Object oriented programming lang
node js - Object oriented programming lang
Sql - query language
Julia - Scripting lang
shell - Scripting lang
golang - Object oriented programming lang
kotlin - Object oriented programming lang
ABC - Modular lang
Scaala - Modular lang

python -Scripting language


Modular language
Object oriented programming lang
Functional procedure orinted lang.

#include <stdio.h>
{
void main();
{
printf("Hello world");
}
}

class Student:
{
public static void main(string args[]);
{
system.out.println("Hello world");
}
}

print('Hello world')

what is python:

Python is a general purpose high level programming language.

1 - High Level - easy to understand for user


2 - Low level - difficult to understand,machine level - assembly
general purpose :
we can use python as per our daily need.

prequsites - python

where we can use python?


- Web Applications, facebook.com, instagram.com etc
- Desktop applications, notepad , calculator
- Data science -
- Machine learning -
- Deep Learning - google assistant,
- AI -
- IOT applications -
- Database applications - mysql,
- Gaming -
- Networking -
- Mobile applications apk file
features of python:

1 - simple and easy to learn


2 - open source
3 - High level
4 - Platform indepenedent
5 - Dynamically Typed - *****
- Static -
- Dynamic -
data types - int, float , string, bool, complex

float n = 10.5;
n = 10.5

6 - Interpreted language - *****

compiler -

java - compile- run - output


python - run - output

pvm - python virtual machine

7 - Extensible libraries -

rama international - hotel - menu card - order - foods - ready -


python library - sum([1,3,4,5,7,6])

8 -

limitations of python

not recommended for mobile applications

pydriod

Flavours of python
- cpython or cython
- Java - Jython
- Ruby - RubyPython
c#,.NET- IRON python

Python Versions:

Father - Guido Van rossam

java - 1995

14feb -
date - 20 Feb 1993

NRI netherland

Python 1.0 introduced in Jan 1994


java - 1995 - 6 - 2000
Python 2.0 introduced in Jan 2000
2015 - 2.7
python3 - backward compatibility -
python2 - 2019 -

Python 3.0 introduced in Jan 2008


python 3.11

java- google - partnership -


python - google - 2016-17

java - developement - maintanance


python2 python3

1 - print "hello world" print('Hello world')


- print('Hello world') #print'hello world'

parenthesis is optional parenthesis must be required

2 - to take dynamic input from only input() method is available.


user, there have two methods
input(), raw_input()

3 - long data type was available is no longer

4 - / operator return int it will return float value


print(10/5) = 2 print(10/5)=2.0

stable and recommended version - 3.8.0

installation
search pycharm on google
https://www.jetbrains.com/pycharm/download/#section=windows
download Community
https://www.python.org/ftp/python/3.8.6/python-3.8.6-amd64.exe
Identifires:

Any name in python program called as indetifier.

it can be class name, function name, module name, variable name

for e.g
a = 10

rules to define identifires:

- special symbols are not allowed


ca$h = 10
print(ca$h)

- starting digits are not allowed


cash123 = 10
print(cash123)

123cash = 10
print(123cash)

- underscores (_)are allowed


_123cash = 10
_cash123 = 10

reserved keywords are not allowed ==> Total 35.


'False', 'None', 'True', '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', 'while',
'with', 'yield']

'False', 'None', 'True' - only this reserved keywords first letter is capital

continue = 10
cash = 10

total123 = 10 - valid
123total = 10 - invalid
java2share = 10 - valid
__ABC_abc_XYZ = 10 - valid
ca$h = 10 - invalid
True = 10 - invalid
true = 10 - valid
if = 10 - invalid
_if = 10 - valid

Data types:

what kind of type you are going to store inside variable

var = 10

fundamental data types:


1 - int
2 - float
3 - str
4 - bool
5 - complex

all fundamental data types are immutable.

immutable - non changable

Python contains several in-built methods

-type() - to check data type of variable


- id() - to check memory address
- print() - to print output
- input() - to get input from user

1 - int data type

var = 10

2 - float

var = 10.5

3 - str data type

s = "rushi"
s = 'rushi'
s = '''rushi'''

4 - bool data type


True and False
True - 1
False - 0

5 - Complex data type


complex number - a+bj

a - real part
b - imaginary part

var = 10+20j
var1 = 5+10j
var + var1 = 15+30j

to print real part from complex number we have real()


to print imag part from complex number we have imag()
Slicing :

slice - piece
s = "ShriHari"
if you want to access charecters from string collection as per their indexing which
is nothing but
a slicing.
positive and negative both indexing are allowed
+ve indexing means forward from left to right
-ve indexing means backward from right to left
[] - slice operator

syntax: [start:end:step]

-8 -7 -6 -5 -4 -3 -2 -1
S h r i H a r i
0 1 2 3 4 5 6 7

print(s[:-18:-1])

for end (n-1) - end value will not print


s = "ShriHari"
print(s[7:-6:-4])

Type Casting:

to conversion from one type to another type called type casting.

int()
float()
bool()
complex()
str()

print(int(10.5))# 10
print(int(10+5j)) #
print(int(True))# 1
print(int('10')) # 10
print(int('ShriHari'))#

- we can convert any type to int except complex type


- If we want to convert str to int type, compulsory str should be only integral
value otherwise
it will throw ValueError.

float():

float(10)#10.0
float(10+5j)#TypeError
float(True)#1.0
float('ten')# ValueError
float('10')#10.0

- we can convert any type to float except complex type


- If we want to convert str to float type, compulsory str should be only integral
value otherwise
it will throw ValueError.

3 - Complex()
print(complex(10))
print(complex(10.5))
print(complex(True))
print(complex('10'))
print(complex('ten'))

- we can convert any type to complex


- If we want to convert str to complex type, compulsory str should be only integral
value otherwise
it will get ValueError.

4 - Bool

print(bool(0)) # False
print(bool(1)) #True
print(bool(10))#True
print(bool(10.5))#True
print(bool(10-2j))#True
print(bool(0+1.5j))#True
print(bool(0+0j))#False
print(bool('True'))#True
print(bool('False'))#False
print(bool(''))#False

if var is empty string then the result is False otherwise the result is True

5 - Str()

print(str(10))
print(str(10.5))
print(str(10-2j))
print(str('ten'))
print(str('10'))
print(str(True))

Hence, We can convert any type to str type.

Sequencial Data Types: 9


- Bytes
- Bytearray
- List
- Tuple
- Dictionary
- Set
- Frozenset
- Range
- None
1 - Bytes - Immutable
byte data range 0 to 256

Bytes data type represents a group of byte numbers just like an array.

l = [10,20,30,40]
b = bytes(l)
2 - Bytearray - mutable
exactly same as bytes except it is mutable

l = [10,20,30,40]
b = bytearray(l)

3 - list data type: Mutable


If we want to represent a group of values as a single entity.

- list declared by [] - square brackets


- Insertion order is preserved
- Hetrogenous elements are allowed
- it is mutable collection
- duplicates are allowed

l = [10,10.5,'Faizal',True]

4 - Tuple Data type: immutable


exactly same as list except it is immutable

1 - it declared by () (parenthesis)
2 - order is preserved
3 - Duplicates are allowed
4 - Hetrogenous elements are allowd

t = (10,20,30,40,10)

5 - Range - immutable
it represents a sequence of numbers

[start:end:step] - slicing syntax


(start,end,step) - range syntax

6 - set - mutable
if we want represent a group values without duplicates where order is not preserved
then
we should go with set data type

it is declared by {} - (flower bracket, curly bracket)

1 - order is not preserved


2 - Duplicates are not allowed
3 - Hetrogenous elements are allowed
4 - Indexing and slicing concept are not applicable
5 - it is mutable collection

7 - Frozenset
exactly same a set except it is immutable

s = {10,20,30,40,10,10,10,10,10,10.5,'raj',True}
# print(type(s))
fs = frozenset(s)
fs.remove(100)
print(fs)

8 - dict data type -mutable


if we want to represent a group of values a key-value pairs then we should go with
dict data type.

shrihari 22 pune MIT BE


{name:'shrihari',age:22}

- it is mutable collection
- Duplicates are not allowed
- order is not preserved
- slicing and indexing not applicable
- it is declared by {}

None -

None means nothing or no value associated

def m1():
None

Escape charecters:

\n - new line
\t - Horizantal tab
\b - back space
\' - single quote
\\ - double quote

s = "E page Infotech"


print(s)

Constants:

this is concept is not applicable in python:

MAX_VALUE = 10

But it is convention to use only in uppercase if we don't want to change value

Operators:

operator is a symbol that performs a certain operations

1 - Arithmetic operators

+ - addition
- - sub
* - Multiplication
/ - Division
% - Modulo operator
** - power
// - Floor Division

print(10+10)#20
print(10-5)#5
print(10*2)#20
print(10/5)#2
print(10%5)#0
print(10**2)#100
print(10//5)#2
what is diff between / and // ?
/ return float value
// returns int value

s = "shrihari" + "10"
print(s)

if we want to use + operator for str type then compulsory both arguments should be
str type only

s = "shrihari" * 10

if we use * operator for str type then compulsory one argument should be int and
other argument
should be string

Relational operators:

>
>=
<
<=

a = 10
b = 5

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

Equality Operators:
==, !=

print(10==10)
print(10!=10)

Logical Operators:
and , or , not

and - if both arguments are True then result is True otherwise result is False.
or - atleast one argument is True then result is True
not - complement - True to False
False to True

a = False
b = False
print(a or b)
print(True and False)
print(True or False)
print(not True)
print(not False)
print(True and True)

Bitwise operators:
&, and - if both arguments are True then result is True otherwise false
|, or - at least one argument True then result is True
^, ex-or - if both arguments are different then result is True otherwise result is
False
~,complement - False to True / True to False Vice-versa.

print(True & True)


print(True & False)
print(True | False)
print(False | False)
print(~False)
print(~True)
print(True ^ False)
print(True ^ True)

0
+ -1
= -1

-1
-1
= -2

Assignment Operators:

i++
j++
i--
j--

to increment
x = 10
x = x + 1 or
x += 1

to decrement
x = 10
x = x - 1
x -=1

Ternery Operator: ?|

it is not available

syntax : firstValue if condition else secondvalue

f = 10
s = 5

x = f if f>s else s
print(x)

special operators:

1) Identity operators:
is , is not
a = 10
b = 10

print(a is b)

what is difference between is operator and == operator ?

== operator compares the values


is operator compares the memory object address

2 - Membership operator
in, not in

s = "ShriHari"

print('r' in s)#True
print('z' in s)#False

a = 10
b = 20
c = 30

find biggest number in among above ?

walrus operator ?

Input and Output Statements:

Reading dynamic input from user


in python2 : raw_input() and input()
python3 - input() - string

WAP to addition two numbers ?

output - print()

eval() -
s = 10//20+30*5

WAP to take dynamic expression from user and evaluate it.

String formatting:

name = 'Rushi'
age = 22
address = 'pune'

print("my name is " + name + " my age is " + str(age) + " and living at "+ address)

.format() - method is available for string formatting.

print("my name is {} and my age is {} and I am living at


{}".format(name,age,address))

print(f"my name is {name} and my age is {age} and I am living at {address}")


WAP to take three inputs from user(name, salary , age, address) and write output
with help of string
formatting.

Control Flow:

Flow control describes the order in which statments will execute at runtime.

1 - Conditional Statements

if, else, elif

2 - Transfer Statements

break, continue, pass

3 - Iterative Statements

for , while

1 - Conditional Statements

if, else, elif

a) if -
syntax: if condition:
statement

if the condition is true then only statement will execute

name = input('Enter Your Username : ')


if name == 'ShriHari':
print('Hello You are valid user ', name)
else:
print('You are not valid user', name)

elif - if we want write more than one condition then you should have to go with
elif keyword.

synatx:

if condition1:
statement

elif condition2:
statement
'
'
'
elif condition n:
statement n

else:
statement
brand = input('Enter Your Brand Name : ')
if brand == "KF":
print('it is good brand')
elif brand == "TB":
print('it is childrens brand')
elif brand == "RC":
print('it is not that much kick')
elif brand == 'vodka':
print('it is good kick')
elif brand == "Whisky":
print('buy one get one free')
else:
print('other brand are not recommended')

n1 = int(input('Enter 1st number : '))#10


n2 = int(input('Enter 2nd number : '))#5

if n1>n2:
print('The biggest number is ', n1)
else:
print("The biggest number is ", n2)

WAP to find biggest number of 3 given numbers:


WAP to check wheather the given number is in between 1 to 100:
WAP tp take single digit from user and prints its English word
0 - 9 take as user input

user == 0:
print('Zero')
user == 3:
print('Three')
user == 9:
print('Nine')

Iterative Statements:

If we want to execute a group of statments multiple times then we should go for


iterative statements:

for loop - if we want to execute some action for every element present in some
sequence
then we should go for for loop.

list,tuple, set, dict, str

l = [10,20,30,40]

syntax :

for each_value in sequence:


body

for , in , :- must
each_value - variable
sequence - list, tuple, str etc
1)
s = 'Python Learning Is Very Easy'

for each_alpha in s:
print(each_alpha)

2)
l = [10,20,30,40]

for each_value in l:
print(each_value*2)

3)to print hello world 10 times:

for x in range(10):
print('Hello World')

range(start,end,step)

4)display odd numbers from 0 to 20:

for each_odd_value in range(1,20,2):


print(each_odd_value)

5)display even numbers from 0 to 20:

for each_odd_value in range(0,20,2):


print(each_odd_value)

6)display odd numbers from 0 to 20 without jump value:

for each_odd_value in range(21):


print(each_odd_value) = 3
if each_odd_value%2!=0:
3%2 != 0
1 != 0
print(each_odd_value)
3

7)display odd numbers from 0 to 20 without jump value:

for each_odd_value in range(21):


if each_odd_value%2==0:
print(each_odd_value)

WAP to display numbers from 10 to 1 in descending order.


WAP to print square of each number in between 0 to 10.
WAP to print cube of each number in between 0 to 10.

While Loop - if we want to execute group of statements iteratively until some


condition
is false, then we should have to go with while loop.
syntax :

while condition:
body

1) to print numbers from 1 to 10 by using while loop.

for i in range(1,11):
print(i)

x = 1
while x<=10:
print(x)
x = x+1
x+=1

2)door - raj -

name = ""
while name!='raj':
name = input('Please tell your name : ')
print('Thanks for the confirmation. I am ready to open door')

3)to display the sum of first n numbers:


user = input = 4
0+1+2+3
HW

Nested loops:

loop inside loop:


for i in range(5):
for j in range(5):
print(i,j)

*
* *
* * *
* * * *
* * * * *

n = 5
use of end parameter - to skip new line

n = int(input('Enter a Number :'))#4


for i in range(n):#n=4 i = 0,1,2,3
for j in range(i+1):#(0)
print("*",end='') #*
print()# empty space
*
* *
* * *
* * * *
* * * * *

N = 5

n = int(input('Enter a Number :'))#5


for i in range(n):#5, i= 0,1,2,3,4
print(""*(n-i))
print("*"*i)

* * * * *
* * * *
* * *
* *
*

*
*
* *
*
*

0
1 2
3 4 5
6 7 8 9

3 - Transfer Statements
break
continue
pass

break - to stop iteration

for i in range(10):
if i==7:
print('Processing is enough...plz break')
break
print(i)

Faizal_cart = [400,600,999,10000,250] # above 1000 insurance must be required


for each_item in Faizal_cart:
if each_item > 1000:
print(f'To place {each_item} amount value order for that insurance must be
required')
break
print(each_item)
continue - to skip perticular iteration

Faizal_cart = [400,600,999,10000,250] # above 500 delivary charges must be required


for each_item in Faizal_cart:
if each_item < 500:
print(f'To place {each_item} order delivery charges must be required')
continue
print(each_item)

pass - print(10/0)

String Data Structure:

var = 10

How to declare empty string:

var = ""

or

str() we can convert any data type into str.

How to access charecters from string ?

1 - By using indexing
2 - By using slicing

Python supports both +ve and -ve index.


+ve indexing start from 0 and last value(n-1)(forward)
-ve start from -1 (backward)

s = 'rajkumar'

take a string input from user then display its charecters by index wise (both +ve
and -ve)

r positive index 0 and negative index -8


a
j

slcing - [start:end:step]

- To find number of charecters from string


- len()(in-built method) method is avialable

Checking membership:

s = 'rajkumar'
print('u' in s)#True
print('u' not in s)#False
print('raj' in s)#True

HW- take main string and sub-string from user, to check that sub-string is part of
main string ?
string - 'rajkumar'
sub-string - raj

Comparison Of strings

equality(==,!=)

s1 = 'raj'
s2 = 'raju'
print(s1!=s2)

Hw- take first string and second string from user


check both are equal
check who is greater if not equal

Removing Spaces from string

to remove unneccessary spaces from string - strip()


lstrip()
rstrip()

s1 = "Learning Python Is Very Easy"


s2 = " Learning Python Is Very Easy"
s3 = " Learning Python Is Very Easy "

HW. take city name from user and remove unneccessary space from city name
city = ' pune '

Finding Substring:

we have total 4 methods

to check from forward direction:

find()

syntax : variableName.find(sub-string,begin,end)

index()

exactly same as find

s1 = "Learning Python Is Very Easy"


print(s.find('python'))

to check from backward direction:

rfind()
rindex()

if single charecter is there then it will return forward index position


if charecters more than one then it will work based on forward and backward
direction

Counting substring in given string:

s = "aabbaabbbaabbbaabaasjkfhkahfquaYYFDU"
count() - to count particular charecter which occured how many times.
variableName.count(substring,begin,end)

Splitting of strings:
s = "Learing python is very easy"
we can split the given string according to specified separator by using
split()ethod.

syntax variableName.split(separator)

DOB = 25:07:1995
s1 = DOB.split('/')
print(s1)

The default separator is space.


return data type of split method is list.

Joining of strings:
we can join group of strings (list,tuple etc) w.r.to. given separator

to combine strings join method is there.

syntax: separator.join(group_name)

group = ['25', '07', '1995']

Replacing a string with another string:

s = 'Learning python is very hard'


s.replace('hard','easy')
replace()

syntax : variableName.replace(oldstring,newstring)

if the string data type is immutable , then how is it possible to change content of
string by using
replace method ?

once string object created is created. we can not change the content this non
changable behaviour is nothing
a immutability. If we are trying to change the content of string by using replace
method , those changes won't
happend in existing object, it will create new object.

changing Case of strings:

s = 'learning Python is very easy'

to convert all letters into upper case - upper()


to convert all letters into lower case - lower()
to convert all letters to title case. - title()
vice-versa - swapcase()
only first charecter will be converted into upper case - capitalize()

checking starting and ending of string:

s = 'data_science.txt'
startswith()-
endswith()-

HW - create one folder and put some files


and check txt files only
os module

import os
path = "C:/Users/91986/Downloads/"
for each_file in os.listdir(path):
if each_file.startswith('extra'):
print(each_file)

to check type of charecters present in given string:

s = "786"
isalnum() - returns true if all charecters are alphanumeric(a to z, A to Z, 0 to 9)
isalpha()- (a to z, A to Z)
isdigit() - (0 to 9)
islower()
isupper()
istitle()
isspace()

print('Faizal786'.isalnum())
print('Faizal786'.isalpha())
print('786'.isdigit())
print('786'.islower())
print('S'.isupper())
print(' '.isspace())

Program -
take any string from user and check its type.

***********************************************************************************
******

List Data Structure - Mutable

if we want to represent group of values as a single entity

insertion order is preserved:

then we can apply slicing and indexing

hetrogenous elements are allowed

duplicates are allowed

Creation of list:

l = []

or

l = list()
Accessing elements of list:

by using index
by using slicing

l = [10,20,30,40]
l[3]
l[-1]

Important methods of list:

l = []

to add elements inside list - append()


syntax: variableName.append(value)

l.append(10)
l.append(10.5)
l.append('raj')

hw
l = [1,2,4,5,10,20,25,.....]
add elements to empty list upto 100
0 to 10

insert() - to insert at particular index

synatx: variableName.insert(indexPosition,value)

l = []
print(l)
l.append(10)
l.append(10.5)
l.append('Raj')
l.append(True)
l.append(40)
l.insert(3,50)
print(l)

l1 = ['chicken','mutton','fish']
l2 = ['KF','TB','Vodka','Rum']

extend()- if we want to add entire list to another list


syntax: l2.extend(l1)

remove():

if we want to remove particular element from list

syntax: variableName.remove(value)

pop()-

it will remove last element and return it.

l = []
print(l)
l.append(10)
l.append(10.5)
l.append('Raj')
l.append(True)
l.append(40)
l.insert(3,50)
print(l)
l.remove(True)
print(l)
print(l.pop())
print(l)

l = [4,3,2,1]

reverse() - to reverse order of elements in list

syntax: variableName.reverse()

l = ["Dog",'Cat','Apple','Banana']

sort() - to sort default insertion order

synatx: variableName.sort()

default natural sorting order is ascending order.

l = [10,20,'A','B']

will thrown TypeError: '<' not supported between instances of 'str' and 'int'

but in python2 version it was possible

Descending order -

variableName.sort(reverse=True)

mathematical operations of list:

l1 = [10,20,30]
l2 = [40,50,60]

+ (concatenation Operator)

Repetition Operator (*)


s = "raj"*10
print(s)

l1 = [10,20,30] * 10
print(l1)

l1 = [10,20,30]

clear() - remove all elements from list


Nested lists - list inside list

l = [10,20,[40,50],[1,2,3]]

HW:
vowels = [a,e,i,o,u]
take word from user as a input
create empty list and check vowels in given words and append to empty list
print its length of empty list after adding vowels

word = 'nitin is a good boy'


l = [i,i,i,a,o,o,o]
lenght is 7

Q1 - WAP to reverse the given string

Input : Raj
output : jaR

s = 'Raj'

1st way :
by using slicing:

print(s[::-1])

2nd way:
l = "raj"
l1 = list(reversed(l))
print("".join(l1))

without using slicing and in-built method:

3rd way:

s = "raj"
i = len(s)-1
target = []
while i>=0:
target.append(s[i])
i = i-1

print(''.join(target))

***********************************************************************************
****

Tuple Data Structure: Immutable

Tuple is exactly same as list data structure except it is immutable

insertion order is preserved

slicing and indexing concept applicable.

Hetrogenous elements are allowed.

Duplicates are allowed


parenthesis are optional but recommended to use.

How to declare tuple:

t = () - (common bracket or parenthesis)

or

t = tuple()

t = (10)
print(type(t))

or

t = (10,)
print(type(t))

t = 10,
print(type(t))

t = (10,20,30,40)
print(type(t))

Accessing elements from tuple:

1 - by using index
2 - By using slicing

t = (10,20,30,40,50,60)
print(t[5])
print(t[::-1])

important methods of tuples:

1 - len() - to returnn number of elements in a tuple

2 - count() - to return count of particular element


t = (10,20,30,40,50,60,10,10,10)
print(t.count(40))

3 - index() - to return index position of particular element

4 - sorted() - in-built method - to sort tuple


return data type of sorted method is - list

5 - min() and max() - to return maximum and minimum number from tuple

Tuple packing and unpacking:

packing - Packing is nothing but a group of variables

a = 10
b = 20
c = 30
d = 40
t = (a,b,c,d)

unpacking - reverse of packing

t = (10,20,30,40)

a,b,c,d = t

What is difference between list and tuple

list tuple

It is mutable collection it is immutable collection

it is declared by [] it is declared by ()

hetrogenous elements are allowd hetrogenous elements


are allowd

insertion order is preserved insertion order is


preserved

duplicates values are allowed duplicates values are


allowed

growble in nature it is non-growble in nature

list is slower as compared to tuple. tuple is faster as compared


to list

slicing and indexing concept applicable slicing and indexing


concept applicable

to take list or tuple or dict or set input from user we have eval()

HW - WAP to take tuple numbers from user and print its sum and average ?

total numbers of addition / length of total numbers

t = (10,20,30,40)

avg = 100//4 = 25

***********************************************************************************
*************

Set Data Structure: Mutable

if we want to represent group of values as a single entity where duplicates are not
allowed and
insertion order is not preserved.

creation of set:

it is declared by -
s = set()

you can not declare emtpy set by {}

s = set()

to add elements in set we have add() method.

to add multiple items we have update() method.

pop() - it will remove random number and return it.

remove() - it will remove specified element (if the element is not present then it
will throw an error)

discard() - it will remove specified element(if the element is not present then we
won't get any error)

clear() - to remove all elements

mathematical operations on the set:

1 - union()

x = {10,20,30,40}
y = {30,40,50,60}

syntax : x.union(y) - use of union method to return all unique elememts

2 - intersection(): it will return common elements

list set
tuple

mutable mutable
immutable
duplicates allowed not allowed
allowed
denoted by [] denoted by {}
()
slicing and indexing concept applicable not applicable
applicable
insertion order is preserved not preserved
preserved

HW =
string = "the quick brown fox jumps over lazy dog"
output = a b c ----- z

string = "the quick brown fox jumps over lazy dog"


s = list(set(string))
s.sort()
final_str = " ".join(s)
print(final_str.strip())
***********************************************************************************
************************

Dictionary Data Structure: Mutable

{} - unordered collection- indexing and slicing concepts not applicable

{'raj','pune',22,415512,9860382818,'100.57'}

name:'raj'
home_address:pune
age : 22
raj_address_pin_code = 413512
mob : 9860382818
balance: 100.57

if we want reprsent group of values as a single entity then as per requirement we


should have to choose
list , tuple or set.

if we want to represent a group of values as a key-value pairs then we should go


for dictionary.

duplicate keys are not allowed but values can be duplicated.


insertion not preserved

note: c++, java - MAP


perl,ruby etc - Hash

d = {'name':'raj',"age":22}

How to create empty dictionary?

d = {}

or

d = dict()

How add elememts in dictionary?

syntax: dictionary_variable_name[key] = value

d = {}

d['name'] = 'raj'
d['age'] = 22
print(d)

How to access data from dictionary?

syntax: dictionary_variable_name[key]

d = {'name': 'raj', 'age': 22}


print(d['name'])

How to update dictionary?

dictionary_variable_name[key] = value
d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}

d[100]= 'aarti'

print(d)

How to delete elements from dictionary?


syntaX:

del dictionary_variable_name[key]

d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}

del d[100]

print(d)

- to remove all key-value pairs

clear()

Important methods of dictionary:

- len()

- get()

dictionary_variable_name.get(key,default_value)

d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}
print(d[200])
print(d.get(200))

- pop()
syntax : dictionary_variable_name.pop(key)
d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}
# print(d[500])
print(d.pop(100))
print(d)

- popitem():
d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}
# print(d[500])
print(d.popitem())
print(d)

keys() - to get all keys from dictionary

d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}

print(d.keys())

values() - to get all values from dictionary

d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}
# print(d[500])
print(d.values())
items():

it will returns key-value in list of tuples

d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}
# print(d[500])
print(d.items())

iterate on dictionary:
d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}
for key, value in d.items():
print(key,"=",value)

HW - merge two dictionary into single


d1 = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}
d2 = {'name': 'raj', 'age': 22}

HW: WAP to take dictionary from user and print the sum of values

user = {"A":100,"B":200,"C":300}

HW: WAP to take input string from user and find the occurances of each letter
present in given string:

s = "fibonacci"

d {'f':1,'i':2,....."c":2}'

WAP to take string from user and find number of occurances of each vowel present
iin given string:

s = "aaioooiehgkuauoai"

d = {"a":5,'o':4....}

***********************************************************************************
***********************

Comprehnesions techniques:

list comprehension:

it is very easy and compact way to create list objects from any iterable objects
like(list,tuple,dictionary,range etc)

[0,1,2,3,4,5,6,7,8,9]
[0,1,2,3,4,5,]
[0,1,4,9,16,25,36,49,64,81]
[0,1,8,27........]

syntax: [expression for each_item in iterable_object if condition]

l = []
for i in range(10):
l.append(i)
print(l)
list comprehension:

e.g - l = [each_value*each_value for each_value in range(10)]

e.g - print([each_value**3 for each_value in range(1,20,2)])

l = [0,1,4,9,16,25,36,49,64,81]

result = [each_value for each_value in l if each_value%2==0]


print(result)

e.g
l = ['raj','sandhya','shrihari','faizal','aarti']
output - ['r','s','s','f','a']

result = [for each_value in l]


print(result)

HW: string = "the quick brown fox jumps over lazy dog" (split the string)
using list comprehension

out = [('THE',3),('QUICK',5)........('DOG',3)]

***********************************************************************************
****************
set comprehension

it is very easy and compact way to create set objects from any iterable objects
like(list,tuple,dictionary,range etc)

syntax: {expression for each_item in iterable_object if condition}

s = {each_value**2 for each_value in range(20)}


print(s)

try all examples of list using set comprehension

***********************************************************************************
******************

dictionary comprehension:

it is very easy and compact way to create dictionary objects from any iterable
objects like(list,tuple,dictionary,range etc)

s = {each_value:each_value**2 for each_value in range(20)}

try all examples of list using dictionary comprehension

***********************************************************************************
******************

tuple comprehension:

it is not possible in python:

***********************************************************************************
******************

Functions:

raj - function -
hello good morning shri
hello good morning sandhya

if a group of statements is repeatedly required then it is not recommended to write


these statements
everytime separately.
we have to define these statements as a single unit and we can call that unit any
number of times based
on requirement. this unit is nothing but a function.

the main advantage of function is code resuability.

Note - java , c++ ,c - method , subroutine, procedures etc

Python supports two types of functions:

1 - built-in functions -

The functions which are coming along with python software automatically are called
built-in functions.

sum, len, reversed, id, type, input, eval, print, min, max etc

2 - User Defined Functions

the functions which are developed by programmer which is nothing but a user defined
functions.

syntax to create function:

def function_name(parameters):
"statements 1"

return value

while creating functions


mandotory: def , :
optional - function_name can be anything
- parameter is optional
- return is optional

1 -WAP to print hello good morning

def wish():
print('hello good morning')

wish()

parameters : it is input of function.

if we have declared parameter the value should have to pass otherwise typeError
will come.
1 -WAP to print hello good morning with particular name:

def wish(name):
print(f"hello good morning {name}")

WAP and take input a integer and return its square value.

the sqaure of 2 number is 4

def square(number):
return number*number

WAP to add two numbers:

def add(x,y):
return x+y

WAP to check given number is even or odd?

def even_odd(num):
if num%2==0:
print(f"given number {num} is even")
else:
print(f"given number {num} is odd")

HW - Write a function to find factorial of given number?

factorial -
0! - 1
5! - 5*4*3*2*1 = 120
2! - 2*1
3! - 3*2*1

returning multiple values from function:

note - in other languages like c++,java, c function can return atmost one value.
but in python we can return
multiple values.

def add(x,y):
return x+y

def sub(x, y):


return x - y

def mul(x, y):


return x * y

def div(x, y):


return x / y

def calc(x,y):
return x+y, x-y, x*y, x//y
Types of arguments:

there are 4 types of arguments


1 - positional arguments

def sub(x,y):
print(x-y)

sub(100,50)
sub(50,100)

if we change the order then result may be changed.


if we change the number of arguments then we will get TypeError.

2 - Keyword Aruguments:

def sub(x,y):
print(x-y)

sub(x = 100, y=50)


sub(y=50,x=100)

here the order of arguments is not important.


if we change the number of arguments then we will get TypeError.

3 - Default argument:

def sub(x,y=50):
print(x-y)

sub(x = 100, y=50)


sub(y=50,x=100)

if we are not passing any value then only default value will come.

4 - variable length argument:

def add(x,y):
return x+y

sometimes user don't know how many arguments he want pass, that time we should have
to use
variable length arguments.

what is *args, **kwargs ?

what is difference between *args, **kwargs?

*args will return tuple


**kwargs will return dictionary

instead of args and kwargs we can use any name

def sum(*args):
total = 60
for each_value in args:
total += each_value total = 30+30
print(total)

sum(10,20,30)
sum(10,20)
sum(100,200,30,40)

types of variables:

1 - Global

the variable declared outside of function are called global variable.


these variables can be accessed in all functions.

a = 10

def f1():
print(a)

def f2():
print(a)

2 - local

the variable declared inside of function are called local variable.


we can access these variables only inside function.

a = 10

def f1():
b = 20
print(a)
print(b)

def f2():
print(a)
print(b)

Global Keyword:

to declare global variable inside function:

a = 10

def f1():
global a
a = 100
print(a)

def f2():
print(a)

f1()
f2()

Recursive function:

A function that calls itself is called recursive function.

1 - factorial

HW - 2 - fibonacci

0, 0+1, 1+1, 2+1 ...... n

0, 1, 1, 2, 3, 5,8....n

parameter - n - 5 -

Anonymous Functions:

- sometimes we can declare a function without any name such functions are called
Anonymous functions
- Anonymous functions are called lambda function
- The main purpose of anonymous function is just to use for instant.

lambda function
- it is a anonymous function and it has no any specific name.
- The main purpose of lambda function is just to use for instant.
- it will create one liner function.

Normal function:

def add(x,y):
return x+y

lambda function :

syntax: lambda argument_list:expression

lambda x,y: x+y

def bigger_number(n1,n2):
if n1>n2:
return n1
else:
return n2

bigger = lambda n1,n2: n1 if n1>n2 else n2

Important functions:

filter function:

we can use filter() function for filter the values from the given sequence.

filter is a function which is going to take one function as a input and based on
requirement it will
filter the values from sequence.
syntax : filter(function_name, sequence)

seq = [0,1,2,3,4,5,6,7,8,9]

def Iseven(num):
if num%2==0:
return True
else:
return False

filter(Iseven, seq)

filter(lambda num: num%2==0, seq )

map() function -

it is a function which is going to take one function as a input and perform action
on every element of given seq

syntax : map(function_name, sequence)

without lambda function

seq = [0,1,2,3,4,5,6,7,8,9]

def square(n):
return n*n

map(sqaure,seq)

with lambda function:

sq = map(lambda n:n*n,[0,1,2,3,4,5,6,7,8,9])

reduce function:

seq = [0,1,2,3,4,5,6,7,8,9]
0 + 1
1 + 1
2 + 3
5 + 4 .....n

reduce is a function which is going to take one function as a input and perform
action on every pair of element
until get desired output.

reduce function available in functools.

we have should to import reduce function

from functools import reduce

syntax : reduce(function_name, sequence)


without lambda:

from functools import reduce

def add(n1,n2):
return n1+n2
reduce(add,seq)

with lambda
from functools import reduce

print(reduce(lambda n1,n2:n1+n2,[0,1,2,3,4,5,6,7,8,9]))

You might also like