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

Introduction To Python For Data Science 1672630478

Uploaded by

Nodes Hunt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
16 views

Introduction To Python For Data Science 1672630478

Uploaded by

Nodes Hunt
Copyright
© © All Rights Reserved
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. False Variables 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 <= 1: print("You are a Baby!") elif age print ("You are a Toddler!") elif age print ("You are a Preschool child!") elif age <= 12: print("You are a Gradeschool child!) elif age <= 18: print ("You are a Teen!) elif age <= 21: print ("You are a Young Adult!") elif age <= 60: print("You are an Adult!") els. print("You are in your Old Age!") You are a Toddler! year = 1988 is_leap_year = False if yearx1e0 AF yearxaee == 0: is_leap_year = True els. is_leap_year = False elif yearxa == 6: is_leap_year = True else: is_leap_year = False if is_leap_year: print(#*{year} is a leap year.") else: print(#"{year} is not a leap year.") 1988 is not a leap year Assignment: Build a simple calculator that takes two numbers as input (say fn and sn) and an operator ( etc) Perform the operation between the two numbers as per the operator input and print the result as the output Show error message if the operator or any input is not valic Range in python ‘Syntax: range(start=0, end, step=1) n= range(7) # it returns a sequence of numbers from @ to 7-1 (i.e. 7 not included. print (n) print(1ist(n)) # more on List Later n = range(5,18,5) print (List (n)) range(®, 7) (@, 1, 2, 3, 4, 5, 6 (5, 10, 15] Looping in python fe.g. Print the table of 5: print(s*1, i) print(s*2, i) print(s*3, i) print(5*4, ") print(s*s, i) print(s*6, i) print(s*7, i) print(s*8, ") print(s*9, print(s*1e) 55 10; 15; 20; 255 30; 35; 40; 45; Se ») print table using loops While loops: print(5*i, end: isin print("End of while.") 55 10; 15; 20; 25; 30; 35; 40; 45; 50; End of while. For loops: for 4 in range(1,21) print(5*i, er 3") print ("End of for loop.") 35 18; 155 20; 25; 38; 35; 40; 45; 58; End of for loop. 4 shorthand notation of for Loop [1 for i in range(1,11)] [1, 2, 3, 4, 5, 6, 7, 8 9, 10] # Multiplication with string aed while ico print(i*'@ ') isin @ ee ee@ eeee@ 00066 000006 eeeeeee 00000006 0400000068 0@eeeeeeed Assignment: Using while and for loop, print a triangular flag of stars as below. \* \* \* Lists: * Ibis collection of data. Data can be of same or different types * Itis represented by square brackets [] with elements separated by comma prices = [120, 48, 23, 34, 20, 182] print(prices[@]) print(prices[2]) print (prices -1]) print(prices[-3]) 12e@ 230 182 34 Methods on list: print("Before insert:",prices) print(*No. of elenents in the list:",len(prices)) prices.insert(1, 308) # [120, 300, 48, 230, 34, 20, 182] print(“After insert:",prices) print("No. of elenents in the list:",len(prices)) prices. append (400) print (prices) Before insert: [120, 48, 230, 34, 20, 182. No. of elements in the list: € After insert: [120, 300, 48, 230, 34, 20, 182] No. of elements in the list: 7 120, 308, 48, 238, 34, 20, 182, 400] prices.clear() print (prices) c Other methods on list * istappend(x) # append x to end of lst * lstextend(iterable) # append all elements of iterable to list © istinsert(i x) # insert x at index i © stremove(x) # remove first occurance of x from list ist. pop(i) # pop element at index i (defaults to end of list) ist.clear() # delete all elements from the list istindex(x,, startL end]]) # return index of element x © lst.count(x) # return number of occurances of x in list © istreverse( # reverse elements of list in-place (no return) * istsort{key=None, reverse=False) # sort list in-place * istcopy( # return a shallow copy of the list num = (1, 3, 5, 7, 9] num2 = num1.copy() print (nun2) rnum2. append(11) print (nun2) print (nunz) 1, 3,5, 7, 9 1, 3, 5, 7, 9, 11] 1, 3,5, 7, 9 Looping on list num = [1, 3, 5, 7, 9] for i in num: print(10*i, e print("énd.") 105 30; 58; 70; 90; End. break & continue in loop * breaks used to come out of the loop before it ends by itself * continue is used to skip execution of further statements in the loop num = (2, 4, 6, 8, 18, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30) for a in num: if 10 < ac 16: continue if a> 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