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

Introduction To Python For Data Science 1672630478

Uploaded by

Nodes Hunt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
25 views

Introduction To Python For Data Science 1672630478

Uploaded by

Nodes Hunt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 14
Python Introduction Installations installation: 1) Download and install python from python.org 2) Download and install PyCharm from jetbrains.com/pycharm 3) Install jupyter-lab from command prompt using the command >> pip instal jupyterlab ritialisation: 1) Open jupyter lab from shell command prompt using the command >>jupyter-lab Note: 1) All jupyter notebook files are stored with jynb extensior 2) Unlike python code editor, the notebook editor shows output (of the last code line only) even without print Getting Started 12343445.12 # int and float 24 6 "I an jupyter notebook 345978 @e "I am jupyter notebook 345978 @tS" 683 1085-2 48 print (6+3) print(10*5-2) print (32/5+2.1) 9 48 8.5 type(332) int Basic data types in python: in, float, string (st), boolean, etc Strings can be defined using Single-quotes or Double-quotes print("Hello World!") print(*I'm a simple print statenent.*) print(3 > 5) Hello World! I'm a simple print statement. FalseVariables types and operators: name = "Nitin Thokare" ‘age = 20 height = 10.5 favorite sport = “Racing” print (name) print (type(nane)) print (age) print (type(age)) Nitin Thokare 26 Basic arithmetic operations print (a+b) print (b/a) print(at*3) # poner print(25//4) # integer part print(25%4) # remainder 4s 1.25 3008 6 1 Comparison operators print (acb) print(a>b) print(a: print(a print(20 # print(1 @ = is an assignment operator True False False True True Logical operators: print(10c22 or ‘a print (19e12 and "a= print(not ‘a'-="b") True False True Combining String with other variables:name = "Nitin Thokare" age = 20 print("My name is "tname) # "My name isWitin Thokare” print("My name is",name) print("I'n",age, "years old.") 4 Note the extra space in first print My name is Nitin Thokare My name is Nitin Thokare I'm 28 years old. festrings line = "My name is {name}.” print(line) age = 22 print(f"I'm {age} years old.") My name is Nitin Thokare. I'm 22 years old. is_student = True is employed = False print(is_student) print(f*An I enployed?: {is_employed}") True An I employed?: False Taking input from user: saving = input("what is your current saving?: ") credit = input("How much you have credited?: " print (type(saving)) print(#"Your old saving was {saving}.\nYour new saving is {saving+credit} Your old saving was 2300. Your new saving is 2300100. Type conversion Above code took the input as strings and hence + operation printed the numbers concatenated as strings To use them as numbers, we need to convert their types saving = input ("what is your current saving?: print (type(saving)) saving = int(saving) print (type(saving)) credit = int(input("How much you have credited?: ")) print(f*Your old saving was (saving}.\nYour new saving is (savingscredit). Your old saving was 2300. Your new saving is 2500. n= float("13.5") print(n*2) ni = "abcd" print(5¢nt) 27.8 abcdabcdabcdabcdabcd indexing, negative indexing, length of string 5 = "This is a sample string." print(s) print(s[o]) # T print(s[2]) # 7 print(s[8]) # a print(s[3:13]) #s is a sam print (F"length of the string is {len(s)}.") print(s[-1]) #. print(s[-4]) # i print(s[-(len(s)-1)]) #h This is a sample string. T i a s is a san length of the string is 24 i h Operations on strings: s = "This is a sample string." print(s) print(s.upper()) # s = s.upper() print(s.lower()) print(s.title()) print(s) This is a sample string. THIS IS A SAMPLE STRING. this is a sample string. This Is A Sample String, This is a sample string. 4 find print(s.find('a")) print(s.find("b*)) print(s.find('Sample*)) print(s.find(’sample')) 8 “1 1 18 # replace S = "This is a sanple string." print(s.replace('is’, ‘are'))print(s) # original string remain unchanged print(s.replace('Is', ‘are')) # not found due to case mismatch Thare are a sample string. This is a sample string. This is a sample string, tin # in keyword check for availability of one string into another s = "This is a sample string. print("is* in s) print("in’ in s) print(‘are’ in s) True True False Conditional statements if-elif-else name = ‘nitin’ # name = ‘thokare* if name == ‘nitin’: print("Valid person. You can enter into the house.") print(“Another line.") a= 244 else: print("Invalid person! You are not allowed to enter the house.") Invalid person! You are not allowed to enter the house. age = 3 # in years if age 24: break print(a, end: print("Exit done.") 25 45 6; 8} 10; 16; 18; 20; 225 243 Exit done. Tupl * Ibis immutable (cannot be modified) © Ibis represented by circular brackets () marks = (73, 82, 91, 78, 73, 91, 91, 80) print (narks) print (type(marks)) print (narks(@]) print (narks(3]) print (narks{-1)) print (narks{-2]) (73, 82, 91, 78, 73, 91, 91, 80) B 7 86 91 4 List without brackets is considered as a tuple num = 2, 21, 22, 23 print (num) print(type(num)) (20, 21, 22, 23) # marks[@] = 19 # error Methods on tuple © count(x) : Returns the number of times 'x’ occurs in a tuple * index(x) : Searches the tuple for ‘x’ and returns the position of where it was first found print (narks.count(91)) print (narks.index(78)) 3 3 Set:® It isa collection of unique elements (no duplicates are stored) © It is represented by {} ids = (12, 13, 14, 15, 15) print(ids) print(type(ids)) (12, 13, 14, 15) ids..add(12) print (ids) ids .add(16) print (ids) (12, 13, 14, 15) (12, 13, 14, 15, 16) # indexing is not applicable on set. 4 Elenents are stored in any order (they are unordered) # print(ids[@]) # error: ‘set’ object is not subscriptable Methods on set: * add() #Adds an element to the set * clear() #Removes all the elements from the set. * copy) #Returns a copy of the set © difference() #Retums a set containing the difference between two or more sets * difference_update() #Removes the items in this set that are also included in another, specified set * discard() #Remove the specified item ® intersection() #Returns a set, that is the intersection of two or more sets * intersection_update() #Removes the items in this set that are not present in other, specified set(s) * sdisjoint() #Returns whether two sets have a intersection or not * ‘ssubset() #Returns whether another set contains this set or not * ‘ssuperset() #Retums whether this set contains another set or not * :0p() #Removes an element from the set * -emovel) #Removes the specified element * symmetric_difference() #Retums a set with the symmetric differences of two sets + symmetric difference_update( #inserts the symmetric differences from this set and another * union() #Return a set containing the union of sets * updated) #Update the set with another set, or any other iterable Dictionary: * Itis a collection of key-value pairs * Keys are unique in the dictionary, value can be repeatec ® They are represented like { key1 : value', key2 : value2 } marks = {"physics": 81, “chemistry”: 85, "maths": 78, “english":81) # roLl_number: name print(marks["physics"]) # access by key 4 print(marks[@]) # such type of indexing is not applicable in dictionary print(marks.keys())print(marks) marks["physics"] = 98 print(narks) print narks tens ()) 81 dict_keys(['physics', ‘chemistry’, ‘maths', ‘english']) {‘physics': 81, ‘chemistry’: 85, ‘maths': 78, ‘english’: 81} {‘physics': 90, ‘chemistry’: 85, ‘maths’: 78, ‘english': 81} dict_items([(‘physics', 98), (*chemistry’, 85), (‘maths', 78), ‘english’, 81)]) for k,v in marks.items(): print(f"key is {k} and value is {v}") key is physics and value is 9¢ KeyisIchesistryZandiveluelisis key is maths and value is 78 key is english and value is 81 Methods on dictionary: + clear() #Removes all the elements from the dictionary * copy() #Returns a copy of the dictionary # fromkeys0 #Retums a dictionary with the specified keys and value ® get() #Returns the value of the specified key * ‘tems() #Returns alist containing a tuple for each key value pair + eys() #Retums a list containing the dictionary's keys * 00p0) #Removes the element with the specified key * oopitem() #Removes the last inserted key-value pair * setdefault0) #Returns the value of the specified key. Ifthe key does not exist: insert the key, with the specified value * update) #Updates the dictionary with the specified key-value pairs * values() #Returns a list ofall the values in the dictionary Functions in python: © In-built functions ® User-defined functions * Module functions In-built functions print("I'm an in-built function!") int(4.5) I'm an in-built function! 4 Module functions import math fmath. sqrt(22) from math import sqrt as square_root square_root(27)5.196152422786632 from math import pow pow (3,4) 81.0 # to see all the function defined in a module, use dir(module_name) print (dir (math)) *_doc_', ‘_loader_', * _', '_package_', ‘_spec_', ‘acos', ‘acosh', ‘asin’, ‘asin fn’ ‘atan’, ‘atan2", Tatanh®, ‘ceil’, ‘comb’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘dist’, ‘e', "erf', ‘erfc', ‘exp’, ‘expml', ‘fabs’, ‘factorial’, ‘floor’, 'fnod’, ‘frexp', 'fsum’, ‘ganna’ "gcd", ‘hypot', ‘inf', ‘isclose', ‘isfinite’, ‘isinf', ‘isnan', ‘isgrt', ‘lem', ‘Idexp', ‘Iganm a', ‘log’, 'logie", ‘logip’, ‘log2", ‘modf', ‘nan’, ‘nextafter', ‘perm’, ‘pi', ‘pow’, ‘prod’, 'r adians’, ‘remainder’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan', ‘tanh', ‘tau’, ‘trunc’, ‘ulp* User-defined functions syntax: def function_name(parameters) : function body return something # default return value is null Note: Function should be defined (and a module should be imported) before it is being used (called). def add(a,b): return a+b print (add (10, 12)) 2 def say_hello(nane): print (f*Hello {name}!") say_hello("Nitin") print(say_hello("Thokare")) Hello Nitin! Hello Thokare! None Classes and objects * Classis the most fundamental piece of Python. The reason lays behind the concept of object oriented orogramming * Everything in Python is an object such as integers, lists, dictionaries, functions and so on. Every object nas a type and the object types are created using classes. ® Classes have = Data attributes: Define what is needed to create an instance of a class = Methods (ie, procedural attributes): Define how to interact with the instances of a class = Methods are just like functions but they belong to a particular class, The attributes can be considered as an interface to interact with a class.* An advantage of classes is that we do not need to know how it is created. We can just use it through data attributes and methods. Syntax of class definition: class class_name(parent_class) def _init_(self, parameters): # attributes # attribute initialisation # class methods class Person(): def _init_(self, name, age): Self.name = nane self.age = age def get_name(self): return self.nane def update_name(self,new_name): # by default it returns null (None) self.name = new_nane P= Person(“Amish Sinha", 35) print(p.get_name()) print(p-update_name("Amisha Sinha")) print(p.get_name()) Anish Sinha None Amisha Sinhe Class Inheritance: class Person(): def _init_(self, name, age): self.name = name self.age = age def get_nane(self): return self.name def update_nane(self,new_name) : self.name = new_nane lass Student (Person): def _init_(self, nane, age, roll_number): Super()._init_(name, age) self.roll_nunber = roll_nunber def get_roll_rumber(self): return self.roll_nunber Person("Anish Sinha”, 35) Student("Sumit Singh", 16, 21003) Pp print(p.get_name()) print(p-update_name("Amisha Sinha")) print(p.get_name()) # print(p.get_roll_number()) # error: ‘Person’ object has no attribute ‘get_roLl_nunber’ print(s.get_name()) print(s.get_roll_number())Amish Sinha None Amisha Sinhe Sumit Singh 21003

You might also like