Function¶
In [1]:
## Built-in function
a= [1,2,3,4] ## list
print(type(a))
## Now going to convert into tuple
b= tuple(a)
print(type(b))
<class 'list'> <class 'tuple'>
In [3]:
## User defined function
## Simple syntax
def function_name(): ## Use def keyword to define the function
pass
## We can define function in four ways: -
## 1. Without Parameter and Without Return Type
## (Parameter: the element passes to the function for the operation)
## (Return Type: after operation what we have to return to the object)
## Example:
def summation():
## Define the operations
a= 5
b= 6
print(a+b)
## Calling the function summation
summation()
11
In [4]:
## On the above summation function we see that we didn't provide any parameter as well as we didn't return anything
## 2. With Parameter and Without Return Type
def summation(a): ## Here, I'm passing the parameter (a) to the function
## Defining function
b= 10
print(a+b)
## Calling the function
summation(5)
15
In [5]:
## 3. Without Parameter and With Return Type
def summation():
a= 5
b= 6
return a+b
## Calliing function with Object
sum_1= summation()
In [6]:
## When we print the sum_1
## We get the result of sum of
print(sum_1)
11
In [7]:
## 4. With Parameter and With Return type
def summation(a):
b= 10
return a+b
## Calling function with object
sum_2= summation(10)
In [8]:
print(sum_2)
20
0 Comments
In case of data science we generally, used 5 type of Data Structure¶
1. Tuple¶
In [1]:
## Let's define the tuple
tup1= ()
print(tup1)
print(type(tup1))
() <class 'tuple'>
In [2]:
### It's automatically, understand we defined the tuple type of data structure
In [3]:
tup1= (1,2,3,4)
In [4]:
tup2= (1, 'M', 2, 'A')
In [5]:
print(tup1, tup2)
(1, 2, 3, 4) (1, 'M', 2, 'A')
In [6]:
tup3= (1,2,3,4)
In [7]:
print(tup1+tup3)
(1, 2, 3, 4, 1, 2, 3, 4)
In [8]:
print(tup1+tup2)
(1, 2, 3, 4, 1, 'M', 2, 'A')
In [9]:
## On adding the two or more tuples it's just concatenate them
## Let's check what happened when using (-) between the two tuples
print(tup1-tup3)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-9-9ea0f1f58162> in <module> 1 ## On adding the two or more tuples it's just concatenate them 2 ## Let's check what happened when using (-) between the two tuples ----> 3 print(tup1-tup3) TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'
In [10]:
## Slicing the tuple
## Get the 1st element
print(tup1[0])
1
In [11]:
## Get the last element
print(tup1[-1])
4
In [12]:
print(tup1[1:3])
(2, 3)
In [15]:
print(tup1[-3:-1])
(2, 3)
In [18]:
## We can do slicing from both the side
## Let's check what are the built-in used in case of tuple operation
print(tup1.index(3))
2
In [20]:
print(tup1.count(1))
1
In [21]:
tup4= tup1 + tup2
In [22]:
print(tup4.count(1))
2
In [23]:
## Here, 1 occurs twice in tuple tup4
In [24]:
tuple.__doc__
Out[24]:
"Built-in immutable sequence.\n\nIf no argument is given, the constructor returns an empty tuple.\nIf iterable is specified the tuple is initialized from iterable's items.\n\nIf the argument is a tuple, the return value is the same object."
In [25]:
## What happen if you want to manipulate the tuple?
tup1[1]= 4 ## I just tried to assign value 4 to the 1st index of tuple
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-25-1ca8a93f6d40> in <module> 1 ## What happen if you want to manipulate the tuple? ----> 2 tup1[1]= 4 ## I just tried to assign value 4 to the 1st index of tuple TypeError: 'tuple' object does not support item assignment
In [36]:
## Yes, the tuple doesn't support the external assignment!
## How to add two numeric tuple?
tup5= tuple(i+j for i,j in zip(tup1, tup3))
In [37]:
tup5
Out[37]:
(2, 4, 6, 8) 2. List¶
In [38]:
## Let's define list
lyst1= []
type(lyst1)
Out[38]:
list
In [42]:
lyst1= [1,2,3,4]
lyst2= [1,2,3,4]
lyst3= [1, 'A', 2, 'M']
In [43]:
lyst1+lyst2
Out[43]:
[1, 2, 3, 4, 1, 2, 3, 4]
In [44]:
## Work Same as the tuple, it just concatenate the two lists in place of adding both of them
## Let's check is it mutable or not??
print('Before Manipulation: {}' .format(lyst3))
lyst3[1]= 'B' ## Going to change the 2nd index element from the lyst3
print('After Manipulation" {}' .format(lyst3))
Before Manipulation: [1, 'A', 2, 'M'] After Manipulation" [1, 'B', 2, 'M']
In [45]:
### Hurray!! Now here we seen that we can easily change and manipulate the values in the list!
## Adding to List
lyst4= list(i+j for i,j in zip(lyst1, lyst2))
print(lyst4)
[2, 4, 6, 8]
In [46]:
## zip a function which parallely pick 1-1 element from series of data in sequential manner
print(zip.__doc__)
zip(iter1 [,iter2 [...]]) --> zip object Return a zip object whose .__next__() method returns a tuple where the i-th element comes from the i-th iterable argument. The .__next__() method continues until the shortest iterable in the argument sequence is exhausted and then it raises StopIteration.
In [47]:
## built-in function for in the list
print(list.__doc__)
Built-in mutable sequence. If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.
In [48]:
lyst1.append(5) ## Can easily add element using the append function
lyst1.remove(5) ## Can easily remove the element using remove function
In [49]:
lyst1
Out[49]:
[1, 2, 3, 4]
In [50]:
## We can also extend the list
lyst1.extend(1,2)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-50-e2ffec0d719a> in <module> 1 ## We can also extend the list ----> 2 lyst1.extend(1,2) TypeError: extend() takes exactly one argument (2 given)
In [51]:
## It gives error because the same type of data structure should be extended
lyst1.extend([5,6])
In [53]:
lyst1 ## See how can easily extend the list of list
Out[53]:
[1, 2, 3, 4, 5, 6]
In [54]:
## Copy the one list to another list object
lyst5= lyst1.copy()
In [55]:
lyst1, lyst5
Out[55]:
([1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6])
In [56]:
lyst1.extend([1,1,2,1])
## Count, how many time 1 occurs?
print(lyst1.count(1))
4
In [64]:
lyst1.reverse() ## Can easily reverse the list without using any kind of explicit loop or function
print(lyst1)
[1, 2, 1, 1, 6, 5, 4, 3, 2, 1]
In [65]:
## sort the list
lyst1.sort()
In [66]:
lyst1
Out[66]:
[1, 1, 1, 1, 2, 2, 3, 4, 5, 6]
In [67]:
## In case of list the built-in function are pretty useful and fast in opertion
In [76]:
## How can we add +1 in every elements of lyst1
## For that we need to use for loop
for i in range(len(lyst1)):
lyst1[i]= lyst1[i]+1
In [77]:
lyst1
Out[77]:
[3, 3, 3, 3, 4, 4, 5, 6, 7, 8]
In [78]:
## Using the list comprehension method
lyst1= [i+1 for i in lyst1]
In [79]:
lyst1
Out[79]:
[4, 4, 4, 4, 5, 5, 6, 7, 8, 9]
In [80]:
## List comprehension is quite easy to use and usually do fast operation
Dictionary¶
In [69]:
dict1= {}
print(dict1)
print(type(dict1))
{} <class 'dict'>
In [81]:
print(dict.__doc__)
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
In [82]:
## Creating list and doin operations
dict1= {'A': 1, 'B': 2, 'C': 3, 'D': 4}
In [83]:
dict2= {'A': 2, 'B': 3, 'C': 4, 'D': 5}
In [84]:
print(dict1, dict2)
{'A': 1, 'B': 2, 'C': 3, 'D': 4} {'A': 2, 'B': 3, 'C': 4, 'D': 5}
In [85]:
## See the dictionary always present in key value pairs
## Let's see what happened when we create dictionary without providing the value
dict3= {'A': 1, 'B': , 'C': 4}
File "<ipython-input-85-1205e9113181>", line 3 dict3= {'A': 1, 'B': , 'C': 4} ^ SyntaxError: invalid syntax
In [86]:
## Let's check is it mutable or not
dict3= dict1.copy()
dict3['A']= 10
In [87]:
print(dict3)
{'A': 10, 'B': 2, 'C': 3, 'D': 4}
In [88]:
## Yes, dictionary is mutable in nature thus it means we can easily manipulate as per the requirements
In [89]:
dict1.items() ## Get the items of dictionary
Out[89]:
dict_items([('A', 1), ('B', 2), ('C', 3), ('D', 4)])
In [90]:
## Items means the combined pair of key and value
dict1.keys() ## Getting keys
Out[90]:
dict_keys(['A', 'B', 'C', 'D'])
In [91]:
dict1.values() ## Getting values
Out[91]:
dict_values([1, 2, 3, 4])
In [101]:
dict1.fromkeys('B', 4) ## Getting the key withot value, here you can randomly provide any value to the key
Out[101]:
{'B': 4}
In [102]:
dict1.pop('A')
Out[102]:
1
In [103]:
dict1
Out[103]:
{'B': 2, 'C': 3, 'D': 4}
In [104]:
## Pop function basically, remove the items from the dictionary
In [107]:
dict1.update({'E': 5})
In [108]:
dict1
Out[108]:
{'B': 2, 'C': 3, 'D': 4, 'E': 5}
In [109]:
## We can update the dictionary like that
In [115]:
dict1.clear()
In [117]:
dict1 ## It's delete all the values from the dictionary
Out[117]:
{} Basic Python for the Data Science¶In case of python there is no need to assign the variable explicitly, in case of python we can use dynamically¶
In [1]:
## Here, Just print
2
Out[1]:
2
In [2]:
## Add two number
2+3
Out[2]:
5
In [3]:
## Priniting caharacter you need to write the character under single or double inverted comma
'Hello! Python'
Out[3]:
'Hello! Python'
In [6]:
## How to create object in python?
## In case python we didn't need to define the data type because it's explicitly understand what type of data type it is
a= 2
print(type(a))
print(type(2))
b= 'Hello'
print(type(b))
print(type('Hello'))
<class 'int'> <class 'int'> <class 'str'> <class 'str'>
In [7]:
## As you saw the above example the object type automatically, under stand what type of data type is it
## Let's take another example of date
## For that I have to import the date time function
import datetime
date= datetime.datetime.now()
print(date)
print(type(date))
2019-12-30 15:04:42.199856 <class 'datetime.datetime'>
In [8]:
## Here, the object already understand what type of the data type is it.
In [9]:
## How to covert the data from one data type to another data type
## Let's create the object
obj1= 2
obj2= 2.5
obj3= 'Hello!'
print(obj1, type(obj1))
print(obj2, type(obj2))
print(obj3, type(obj3))
2 <class 'int'> 2.5 <class 'float'> Hello! <class 'str'>
In [10]:
## Now I'm going to convert from one data type to another data type
obj1= float(obj1)
obj2= str(obj2)
obj3= int(obj3)
print(obj1, type(obj1))
print(obj2, type(obj2))
print(obj3, type(obj3))
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-10-6ff3ed57ef6a> in <module> 2 obj1= float(obj1) 3 obj2= str(obj2) ----> 4 obj3= int(obj3) 5 6 print(obj1, type(obj1)) ValueError: invalid literal for int() with base 10: 'Hello!'
In [11]:
## Now, here we got the error message from the entire cell
## So, this error arised because we can't convert the "String type to Integer or Float Type"
## So, I'm going to Run without changing the data type of obj3
obj1= float(obj1)
obj2= str(obj2)
obj3= str(obj3)
print(obj1, type(obj1))
print(obj2, type(obj2))
print(obj3, type(obj3))
2.0 <class 'float'> 2.5 <class 'str'> Hello! <class 'str'>
In [12]:
## Now, it's work, so simple I can say be careful on converting from data type to another data type
In [13]:
## What happend when I print the object which is not defined?
print(obj4)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-13-8221e11239db> in <module> 1 ## What happend when I print the object which is not defined? ----> 2 print(obj4) NameError: name 'obj4' is not defined
In [14]:
## Now it's clearly understood that obj4 is not defined
obj2= obj4 + obj1
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-14-6198a1d7743b> in <module> 1 ## Now it's clearly understood that obj4 is not defined ----> 2 obj2= obj4 + obj1 NameError: name 'obj4' is not defined
In [15]:
## Using the Math library
import math
In [16]:
## Let's check what type of object "math" is
print(type(math))
<class 'module'>
In [18]:
## Exactly this is a complete module or library
## Module or Library: A wrapper which consist of multiple functions in it.
## Let's define the object called add
sin= math.sin
print(type(sin))
<class 'builtin_function_or_method'>
In [24]:
## Now it's clear that the module consist of the multiple functions which used for the different operations
## How to get the doc of the module??
print(math.__doc__)
This module is always available. It provides access to the mathematical functions defined by the C standard.
In [25]:
## Now, doc of the builtin function or method
print(sin.__doc__)
Return the sine of x (measured in radians).
In [27]:
## Let's print the doc of the datetime
print(datetime.__doc__)
Fast implementation of the datetime type.
In [28]:
## Now print the sin of 90
print(sin(90))
0.8939966636005579
In [29]:
print(sin(math.pi/2))
1.0 If-else Statement¶
In [30]:
## Here, used identation and (:) in place of semi-colon (;)
## Let's take an example
str1= 'Hello! Python'
## Let's check is Python present in str1 or not..
## So, here we can use the if-statement
## Check...
if 'Python' in str1:
print(True)
True
In [31]:
## Let's use bothe the if-else and statement
if 'Hello' in str1:
print('Hi')
else:
print('Not Present')
Hi
In [32]:
if 'World' in str1:
print('Hi')
else:
print('Not Present')
Not Present Looping¶
For Loop¶
In [33]:
## How to use?
str2= 'Learning Data Science Basics!'
## Let's iterate and print the each and every character on str2
for i in str2: ## Here, 'i' is basically the iterable character on str2
print(i)
L e a r n i n g D a t a S c i e n c e B a s i c s !
In [34]:
## Another! Way to print it!
for i in range(len(str1)):
print(str1[i])
H e l l o ! P y t h o n
In [35]:
str3= ''
for i in str2:
str3 += i
In [36]:
print(str3)
Learning Data Science Basics! While Loop¶
In [45]:
i= 0
while i<len(str1):
print(str1[i])
i= i+1
H e l l o ! P y t h o n
In [47]:
i= 0
str4= ''
while i<len(str1):
str4 += str1[i]
i= i+1
In [48]:
print(str4)
Hello! Python |
ArchivesCategories |