python_data_Science_05_06_23 (24)
python_data_Science_05_06_23 (24)
#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:
prequsites - python
float n = 10.5;
n = 10.5
compiler -
7 - Extensible libraries -
8 -
limitations of python
pydriod
Flavours of python
- cpython or cython
- Java - Jython
- Ruby - RubyPython
c#,.NET- IRON python
Python Versions:
java - 1995
14feb -
date - 20 Feb 1993
NRI netherland
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:
for e.g
a = 10
123cash = 10
print(123cash)
'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:
var = 10
var = 10
2 - float
var = 10.5
s = "rushi"
s = 'rushi'
s = '''rushi'''
a - real part
b - imaginary part
var = 10+20j
var1 = 5+10j
var + var1 = 15+30j
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])
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'))#
float():
float(10)#10.0
float(10+5j)#TypeError
float(True)#1.0
float('ten')# ValueError
float('10')#10.0
3 - Complex()
print(complex(10))
print(complex(10.5))
print(complex(True))
print(complex('10'))
print(complex('ten'))
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))
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)
l = [10,10.5,'Faizal',True]
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
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
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)
- it is mutable collection
- Duplicates are not allowed
- order is not preserved
- slicing and indexing not applicable
- it is declared by {}
None -
def m1():
None
Escape charecters:
\n - new line
\t - Horizantal tab
\b - back space
\' - single quote
\\ - double quote
Constants:
MAX_VALUE = 10
Operators:
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.
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
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)
2 - Membership operator
in, not in
s = "ShriHari"
print('r' in s)#True
print('z' in s)#False
a = 10
b = 20
c = 30
walrus operator ?
output - print()
eval() -
s = 10//20+30*5
String formatting:
name = 'Rushi'
age = 22
address = 'pune'
print("my name is " + name + " my age is " + str(age) + " and living at "+ address)
Control Flow:
Flow control describes the order in which statments will execute at runtime.
1 - Conditional Statements
2 - Transfer Statements
3 - Iterative Statements
for , while
1 - Conditional Statements
a) if -
syntax: if condition:
statement
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')
if n1>n2:
print('The biggest number is ', n1)
else:
print("The biggest number is ", n2)
user == 0:
print('Zero')
user == 3:
print('Three')
user == 9:
print('Nine')
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.
l = [10,20,30,40]
syntax :
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)
for x in range(10):
print('Hello World')
range(start,end,step)
while condition:
body
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')
Nested loops:
*
* *
* * *
* * * *
* * * * *
n = 5
use of end parameter - to skip new line
N = 5
* * * * *
* * * *
* * *
* *
*
*
*
* *
*
*
0
1 2
3 4 5
6 7 8 9
3 - Transfer Statements
break
continue
pass
for i in range(10):
if i==7:
print('Processing is enough...plz break')
break
print(i)
pass - print(10/0)
var = 10
var = ""
or
1 - By using indexing
2 - By using slicing
s = 'rajkumar'
take a string input from user then display its charecters by index wise (both +ve
and -ve)
slcing - [start:end:step]
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 city name from user and remove unneccessary space from city name
city = ' pune '
Finding Substring:
find()
syntax : variableName.find(sub-string,begin,end)
index()
rfind()
rindex()
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)
Joining of strings:
we can join group of strings (list,tuple etc) w.r.to. given separator
syntax: separator.join(group_name)
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.
s = 'data_science.txt'
startswith()-
endswith()-
import os
path = "C:/Users/91986/Downloads/"
for each_file in os.listdir(path):
if each_file.startswith('extra'):
print(each_file)
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.
***********************************************************************************
******
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]
l = []
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
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']
remove():
syntax: variableName.remove(value)
pop()-
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]
syntax: variableName.reverse()
l = ["Dog",'Cat','Apple','Banana']
synatx: variableName.sort()
l = [10,20,'A','B']
will thrown TypeError: '<' not supported between instances of 'str' and 'int'
Descending order -
variableName.sort(reverse=True)
l1 = [10,20,30]
l2 = [40,50,60]
+ (concatenation Operator)
l1 = [10,20,30] * 10
print(l1)
l1 = [10,20,30]
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
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))
3rd way:
s = "raj"
i = len(s)-1
target = []
while i>=0:
target.append(s[i])
i = i-1
print(''.join(target))
***********************************************************************************
****
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))
1 - by using index
2 - By using slicing
t = (10,20,30,40,50,60)
print(t[5])
print(t[::-1])
5 - min() and max() - to return maximum and minimum number from tuple
a = 10
b = 20
c = 30
d = 40
t = (a,b,c,d)
t = (10,20,30,40)
a,b,c,d = t
list tuple
it is declared by [] it is declared by ()
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 ?
t = (10,20,30,40)
avg = 100//4 = 25
***********************************************************************************
*************
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()
s = set()
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)
1 - union()
x = {10,20,30,40}
y = {30,40,50,60}
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
{'raj','pune',22,415512,9860382818,'100.57'}
name:'raj'
home_address:pune
age : 22
raj_address_pin_code = 413512
mob : 9860382818
balance: 100.57
d = {'name':'raj',"age":22}
d = {}
or
d = dict()
d = {}
d['name'] = 'raj'
d['age'] = 22
print(d)
syntax: dictionary_variable_name[key]
dictionary_variable_name[key] = value
d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}
d[100]= 'aarti'
print(d)
del dictionary_variable_name[key]
d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}
del d[100]
print(d)
clear()
- 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)
d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}
print(d.keys())
d = {100:'raj',200:"sandya",300:'shrihari',400:'faizal'}
# print(d[500])
print(d.values())
items():
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: 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........]
l = []
for i in range(10):
l.append(i)
print(l)
list comprehension:
l = [0,1,4,9,16,25,36,49,64,81]
e.g
l = ['raj','sandhya','shrihari','faizal','aarti']
output - ['r','s','s','f','a']
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)
***********************************************************************************
******************
dictionary comprehension:
it is very easy and compact way to create dictionary objects from any iterable
objects like(list,tuple,dictionary,range etc)
***********************************************************************************
******************
tuple comprehension:
***********************************************************************************
******************
Functions:
raj - function -
hello good morning shri
hello good morning sandhya
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
the functions which are developed by programmer which is nothing but a user defined
functions.
def function_name(parameters):
"statements 1"
return value
def wish():
print('hello good morning')
wish()
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.
def square(number):
return number*number
def add(x,y):
return x+y
def even_odd(num):
if num%2==0:
print(f"given number {num} is even")
else:
print(f"given number {num} is odd")
factorial -
0! - 1
5! - 5*4*3*2*1 = 120
2! - 2*1
3! - 3*2*1
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 calc(x,y):
return x+y, x-y, x*y, x//y
Types of arguments:
def sub(x,y):
print(x-y)
sub(100,50)
sub(50,100)
2 - Keyword Aruguments:
def sub(x,y):
print(x-y)
3 - Default argument:
def sub(x,y=50):
print(x-y)
if we are not passing any value then only default value will come.
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.
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
a = 10
def f1():
print(a)
def f2():
print(a)
2 - local
a = 10
def f1():
b = 20
print(a)
print(b)
def f2():
print(a)
print(b)
Global Keyword:
a = 10
def f1():
global a
a = 100
print(a)
def f2():
print(a)
f1()
f2()
Recursive function:
1 - factorial
HW - 2 - fibonacci
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 :
def bigger_number(n1,n2):
if n1>n2:
return n1
else:
return 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)
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
seq = [0,1,2,3,4,5,6,7,8,9]
def square(n):
return n*n
map(sqaure,seq)
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.
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]))