Basics in Python for Data Science Series - Part 1

  Hello all,

This is the first article in the series Python for Data Science. As a prerequisite to this tutorial series, it is expected that python is already installed in your computer. 

In case if you haven't installed python, Please follow the instructions given in the page or in the below video tutorial.


This tutorial is focused mainly on the areas where coding is needed by Data Scientist for daily use. I will try to cover as much as possible. In case if i miss somethings, we are open for your suggestions.

The style of this tutorial would allow the user to get hands on and learn while coding. This style of learning is proven to be effective and encourage to be fast paced.

Run your Python Code from Notepad and Command Prompt

The following steps would guide you to run your python code from Notepad.

1. Open run window by pressing Windows + R and then type cmd for opening command prompt
2. Navigate to the folder path where your python code resides. for example, my python script file exists in C:\Users\Raj\Desktop\openknowledgeshare.blogspot.com\Python\Codes\Day1 path. Then enter the following command

cd C:\Users\Raj\Desktop\openknowledgeshare.blogspot.com\Python\Codes\Day1

3. Now, lets say you would like to run python script intro_code.py which is located inside that folder . then enter the following command 

python intro_code.py

4. This would run the python script and the output will be displayed on the command prompt itself. 


Now that you know how to run your python script. Lets learn on what can be written inside python scripts

1. Print Statement

Print Statement in Python is usually of the form 

print("Hello World")

semicolon is not mandatory  in python at the end of statement unlike many programming and scripting languages.

The above statement would print Hello World on your output screen.

In case if you would like to print variable value. Here is a code snippet 

a = 10
b = 5
print("The value of a is",a)
print("The value of a is "+str(a))
print("The value of a is {}".format(a))
print("The value of a is {} {}".format(a,b))
print("The value of b and a is {1} {0}".format(a,b))
print(f"The value of b and a is {b} {a}")

These are few various types of ways that can be used to print an integer along with String.


2. Arithmetic Operations 

For Arthimetic operations in python between two variables, please refer the following code snippets

a = 10
# To print the type of variable 'a'
print(type(a))
b = 20
# To print the sum of variables a and b
print(a + b)
# To print the subtraction of variables b from a
print(a -b)
# To print the multiplication of variables a and b
print(a * b)
# To print the dividend of a divided by b
print(a/b)
# To print the remainder of a divided by b
print(a%b)
# To print the dividend of b divided by a
print(b/a)
#To calculate the b power of a
print(b**a)


Note: Instead of assigning to variable, we have printed the outcome so that we can see the result at the output. We can assign that value to a variable and can print it later. for example
c = a + b
print(c)

3. Other Complex Math Operations:

There are few operations like logarithmic, exponential , square root and many others cant be done directly with an operator. But, these functionalities are available in "math" library. This library comes  by default with python installation.

To use any library in your python script, we should import that library into our script.

for example, to import math library, use following command

import math

 Note: The import command need not be at the start of the script although it is good practice to do so, it should be added before using it.

Here is code snippet for few math operations

import math
print(math.exp(3))
print(math.sqrt(9))
#print(math.sqrt(-9))
print(math.pow(2,3))
a = math.pow(2,3)
print(type(a))

 Please try and explore different other values and check its outputs


4. String Operations

Strings in python are basically text. This should be represented by adding double quotes (") or single quotes (') at the beginning and end of the string text.

Please refer the following code snippet for reference

a = "ML Study"
print(type(a))
a = "ML"
b = "Python"
c = 10
print(a + b)
print(a + " " +b)
#print(a + " " +b +c)
print(a + " " +b + str(c))
# Length of String
a = "ML Python"
print(len(a))
#Split string
a = "I am good at I Python"
print(a.split(" "))
#Modify String
a = "I am Good at I Python"
print(a[0])
print(a[0:6])
a = a.replace('I','p')
print(a)# Search within a string
a = 'string123'
b = 'ring'
print(b in a)

5. Relation Operators

Relation operators are mainly for comparison between various variables or any other objects. Here are few code snippets for reference

print(a,b)
print(a == b)
a = 10
b = 20
print(a > b)
print(a < b)
print(type(a < b))


6. Increment/decrement operations

Increment and decrement operators are mainly to modify the value in the variable like below.



print(a)
# Increments variable a by 1
a += 1
print(a)
# Decrements variable a by 10
a -= 10
print(a)


7. Break point


There is a provision in python to invoke break point thru code by adding pdb.set_trace() where ever breakpoint is required.

For doing this, pdb library need to be imported. pdb stands for python debugger.

import pdb
pdb.set_trace()

8. Lists

Lists in python are collection of items. This can be integers, float, strings , lists or any other objects. These are indicated with []


# Defining List
a = [10,20,30]
a = [10,"abc",30]
a = ['hahahh',10,"abc",30]
print(a)
print(len(a))
print(a[0])
print(a[0][0])
print(a[3])
print(a[-1])
print(a[0:3])
#Modify List elements
a[3] = 100
print(a)
#a[4] = 200
a.append(200)
print(a)
a.pop(1)
print(a)
print(dir(a))
# search within a list
a = ["string1","String2",'abc']
b = 'ab'
print(b in a)
print(10 in [20,30])
print(1 in [10])

9. Tuples

Tuples are similar to lists except for the property that elements in the tuples cant be changed. These are indicated with ()

a = (10,20,30)
a = (10,"abc",30)
a = ('hahahh',10,"abc",30)
print(a)
print(len(a))
print(a[0])
print(a[0][0])
print(a[3])
print(a[-1])
print(a[0:3])
#Modify List elements
a[3] = 100
print(a)


10. Conditional Statements (If, elif, else)

Conditional statements in python are if,elif,else statements. Please refer the code for know the syntax on how it can be represented. The indentation of either 'tab' or 4 spaces is widely followed in python.
    
a = 10
b = 20
if(a > b):
print(a)
print(b)
print("A greater than b")
print("done")
a = 20
b = 10
if(a > b):
print(a)
print(b)
print("A greater than b")
elif(a < b):
print(a)
print(b)
print("A less than b")
elif(a == b):
print(a)
print(b)
print("A == b")
else:
print(a)
print(b)
print("Something Wrong")

a = "qwe"
b = "qwe"
if(a is not b):
print(a)
print(b)
print("A == b")


11. Loops


Loops are used to run certain code iteratively.
Please watch the below for better understanding. This Video is recorded session which contains explanation on Loops.


11.1. While

While Loop in c language will be of this format

while(condition)
{
code here
}

Where as while loop in python will be of the below format 

while(condition):
codeline1
codeline2
Code out of while loop

Here are few code snippets to explore while loop 

i = 1
while(i<=10):
print(i)
i += 2
print("Done")


11.2. Do while

do while in C language will be in this format. Only difference between "while" and "do while" is that the code in do while executes once before checking the while condition

do
{ 
codehere
}while(condition)

In case if there is do while loop in python, it should be in the below format.

i = 0
do:
i = i + 1
print(i)
while(i < 10)

But There is no do while in python. You will receive error while writing a code like above

11.3. For Loop

For loop takes the folloing format in C language.

for(initialization,condition,in/decrement)
{
codehere
}

But in Python, It takes the format shown in the following code snippet
for i in range(0,10):
print(i)

Please refer following code snippet for other examples.

print(list(range(0,10)))
a = [1,2,3,"wef",2]
#for i in [0,1,2,3,4]:
for i in range(0,len(a)):
print(a[i])

for item in [1,2,3,"wef",2]:
print(item)

even_list = []
odd_list = []
for i in range(0,10):
if(i%2 == 0):
even_list.append(i)
else:
odd_list.append(i)
print("Even List is ",even_list)
print("Odd List is ",odd_list)


12. Break Statement

Break Statement can be used to break from the loop. Here is a code snippet in how to use it


i = 0
while(i < 100):
print(i)
i += 1
if(i>10):
break


for i in range(10):
for j in range(5):
print(i,j)
if(i>2):
break


13. Continue Statement

Continue statement can be used to skip that particular iteration in Loop. Here is a code snippet in how to use it


i = 0
while(i < 10):
print(i)
i += 1
if((i>2) and (i < 5)):
continue

 

14. Dictionary

Dictionary is a collection of items. It is similar to List but instead of numeric indices, it has keys which can be any item like number, string etc.

Video Explanation about Dictionary can be found below



a = {}
a['ML'] = 1
a['Python'] = [3,4,5]
a[0] = {}
a[0]['jdjdj'] = [3003,2992]

print(a)
print(a.keys())

for each_key in a.keys():
print(each_key,a[each_key])

15. Error Handlers

Error Handlers are very crucial mainly in terms of writing your code to production. This will help the code not to crash in terms of errors. Error handlers in python are try - except - finally. This takes the format like below.

try:
Code here
except:
Error handling code
finally:
This code executes after try or except

Please refer this video for detailed explanation of Error Handlers

 


Here is a code snippet using these error handlers


a = 10
b = 0
c = a/b
try:
c = a/b
except:
#print("Error Occured")
c = 0
print(c)


n = 5
a = []
for i in range(-5,5):
a.append(n/i)

import pdb
n = 5
a = []
for i in range(-5,5):
try:
a.append(n/i)
print("No Errors ........")
except :
print("Error at ",i)
a.append("Error Occurred")
#pdb.set_trace()
finally:
print("No Errors at",i)
print(a)


n = 5
a = []
for i in range(-5,5):
try:
a.append(n/i)
print("No Errors ........")
except ValueError:
continue
except ZeroDivisionError:
print("Error at ",i)
a.append(0)
#pdb.set_trace()
finally:
print("No Errors at",i)
print(a)

 16. Functions

Functions are usually a set of code which you would like to reuse it multiple times. There by avoiding repetition in writing code.

Please refer the following Video for detailed explanation



Function is of this format in C language

function_name(int a,int b)
{
code here
}
function_name(x,y)

Function in python is of the following format

def function_name(a,b):
code here
codeline2
function_name(x,y)

Here are few code snippets to use functions.

# To print N numbers
def print_n_numbers(n):
for i in range(0,n+1):
print(i)


a = print_n_numbers(10)
print("The Value of a is ",a)
print(type(a))


def print_n_numbers_skip_few(n,skip_list):
for i in range(0,n):
if(i in skip_list):
print("Skipping this",i)
continue
print(i)
continue
print("This should not be printed")

print_n_numbers_skip_few(10,[2,3,6,100])
print(2 in [2,3,6])

def print_n_numbers_skip_few(n,skip_list=[]):
for i in range(0,n):
if(i in skip_list):
print("Skipping this",i)
continue
print(i)
continue
print("This should not be printed")

print_n_numbers_skip_few(10)

def sum_of_numbers_in_list(input_list):
sum = 0
#for i in range(0,len(input_list)):
#sum = sum + input_list[i]
for each_item in input_list:
sum = sum + each_item
return sum

a = [10,20,40,-100,2.5]
b = sum_of_numbers_in_list(a)
print(b)
print(type(b))

def print_n_numbers_skip_few(n=10,skip_list=[]):
for i in range(0,n):
if(i in skip_list):
print("Skipping this",i)
continue
print(i)
continue
print("This should not be printed")

print_n_numbers_skip_few()
print_n_numbers_skip_few(skip_list=[2,5,6])
print_n_numbers_skip_few(skip_list=[2,5,6],n= 20)


def print_n_numbers_skip_few_stop_for_few(n,skip_list=[],stop_list = []):
print("Stop List is ",stop_list)
for i in range(0,n):
if(i in skip_list):
print("Skipping this",i)
continue
#if(i in stop_list):
# break

try:
if(i in stop_list):
break
except:
if(i == stop_list):
print("Stopping after ",i)
break
print(i)
continue
print("This should not be printed")

print_n_numbers_skip_few_stop_for_few()
print_n_numbers_skip_few_stop_for_few(20,skip_list=[2,5,6])
print_n_numbers_skip_few_stop_for_few(skip_list=[2,5,6],20)
print_n_numbers_skip_few_stop_for_few(skip_list=[2,5,6],n= 20)
print_n_numbers_skip_few_stop_for_few(skip_list=[2,5,6],n= 20,stop_list = 10)


17. OS Functions:

'os' library shall provide various functionalities which would be available in command prompt/Terminal. This library is used mainly for file/folder path handling, folder creation, knowing the contents of the folder.

Here we discuss and implement code to get the contents of folder recursively, creating and deleting new folder, checking if certain file/folder exists etc.

Please refer the following video for detailed explanation



Please refer the following code.

#import math
#import pdb
import os

main_folder_path = r'E:\openknowledgeshare.blogspot.com\Python\Outputs\Folder_1'

#print(os.listdir(main_folder_path))

# Printing the content in the folder
for each_folder_name in os.listdir(main_folder_path):
print(each_folder_name)
full_path = os.path.join(main_folder_path,each_folder_name)
print(full_path)
print(os.listdir(full_path))

def get_contents_in_folder(input_folder_path):
content_list = []
for each_folder in os.listdir(input_folder_path):
full_path = os.path.join(input_folder_path,each_folder)
print(full_path)
if(os.path.isdir(full_path)):
content_list += get_contents_in_folder(full_path)
else:
content_list.append(full_path)
return content_list

print("Final Contents",get_contents_in_folder(main_folder_path))

# Creating Folder
new_folder_path = os.path.join(main_folder_path,'MLStduyFOlder_2')
print(new_folder_path)
def create_folder(input_folder_path):
if not os.path.exists(input_folder_path):
os.makedirs(input_folder_path)

def delete_folder(input_folder_path):
if os.path.exists(input_folder_path):
os.remove(input_folder_path)

delete_folder(new_folder_path)


17. Classes:


Classes can be treated as collection of functions. This introduces object oriented programming to python. 

Please watch this video below for detailed explaination on this topic



Here are few code snippets for defining and using classes in python.

In file class_code.py,

import os

class OSRelatedFunctions:
def get_contents_in_folder(self,input_folder_path):
content_list = []
for each_folder in os.listdir(input_folder_path):
full_path = os.path.join(input_folder_path,each_folder)
print(full_path)
if(os.path.isdir(full_path)):
content_list += self.get_contents_in_folder(full_path)
else:
content_list.append(full_path)
return content_list

def create_folder(self,input_folder_path):
if not os.path.exists(input_folder_path):
os.makedirs(input_folder_path)

def delete_folder(self,input_folder_path):
if os.path.exists(input_folder_path):
os.remove(input_folder_path)

if __name__ == '__main__':

main_folder_path = r'E:\openknowledgeshare.blogspot.com\Python\Outputs\Folder_1'
new_folder_path = os.path.join(main_folder_path,'CompletelyNewFolder')
a = OSRelatedFunctions() # Creating an instance of class
print(a.get_contents_in_folder(main_folder_path))
print(a.create_folder(new_folder_path))

In file new_script.py,
#import class_code
from class_code import OSRelatedFunctions
import os

#os_func = class_code.OSRelatedFunctions()
os_func = OSRelatedFunctions()

main_folder_path = r'E:\openknowledgeshare.blogspot.com\Python\Outputs\Folder_1'
new_folder_path = os.path.join(main_folder_path,'CompletelyNewFolder')
#os_func = OSRelatedFunctions() # Creating an instance of class
print(os_func.get_contents_in_folder(main_folder_path))
print(os_func.create_folder(new_folder_path))


18. Files Read and Write Operations

18.1. Reading Text File

Here is the code snippet for reading entire text file at once

import os
main_folder_path = r'E:\openknowledgeshare.blogspot.com\Python\Outputs'
text_file_path = os.path.join(main_folder_path,'meeting_saved_chat.txt')
f = open(text_file_path,'rb')
text_file_info = f.readlines()
f.close()
for each_item in text_file_info:
print(each_item)


Here is the code snippet for reading one line at a time


import os
main_folder_path = r'E:\openknowledgeshare.blogspot.com\Python\Outputs'
text_file_path = os.path.join(main_folder_path,'meeting_saved_chat.txt')
text_file_info = []
f = open(text_file_path,'r')
while(True):
this_line_text = f.read()
print(this_line_text)
text_file_info.append(this_line_text)
if not this_line_text:
break
print(text_file_info)

18.2. Writing to Text File

Here is the code snippet for writing one line at a time


text_file_info = ["1\n","3\n","4\n","6\n"]
folder_path = os.path.join(main_folder_path,'saved_text')
if not os.path.exists(folder_path):
os.makedirs(folder_path)
output_text_path = os.path.join(main_folder_path,'saved_text','new_created_doc.txt')
print(output_text_path)
f = open(output_text_path,'w')
for each_item in text_file_info:
f.write(str(each_item))
f.close()

Here is the code snippet for writing all lines at once


text_file_info = ["1\n","3\n","4\n","6\n"]
folder_path = os.path.join(main_folder_path,'saved_text')
if not os.path.exists(folder_path):
os.makedirs(folder_path)
output_text_path = os.path.join(main_folder_path,'saved_text','new_created_doc.txt')
print(output_text_path)
f = open(output_text_path,'w')
f.writelines(text_file_info)
f.close()


18.3. Appending to Text File

Here is the code snippet for appending one line at a time

text_file_info = ["1\n","3\n","4\n","6\n"]
folder_path = os.path.join(main_folder_path,'saved_text')
if not os.path.exists(folder_path):
os.makedirs(folder_path)
output_text_path = os.path.join(main_folder_path,'saved_text','new_created_doc.txt')
print(output_text_path)
f = open(output_text_path,'a')
for each_item in text_file_info:
f.write(str(each_item))
f.close()

Here is the code snippet for appending all lines at once

text_file_info = ["1\n","3\n","4\n","6\n"]
folder_path = os.path.join(main_folder_path,'saved_text')
if not os.path.exists(folder_path):
os.makedirs(folder_path)
output_text_path = os.path.join(main_folder_path,'saved_text','new_created_doc.txt')
print(output_text_path)
f = open(output_text_path,'a')
f.writelines(text_file_info)
f.close()

18.4. Writing to CSV File


Here is the code snippet for writing one row at a time to a csv file.


import csv
text_file_info = [[1],[2,4],[3,7],[4,10],[5,10,20,30]]
output_csv_path = os.path.join(main_folder_path,'saved_text','new_created_doc.csv')
f = open(output_csv_path,'w',newline = "")
writer_csv = csv.writer(f)
for each_row in text_file_info:
writer_csv.writerow(text_file_info)
f.close()


Here is the code snippet for writing all rows at once


import csv
text_file_info = [[1],[2,4],[3,7],[4,10],[5,10,20,30]]
output_csv_path = os.path.join(main_folder_path,'saved_text','new_created_doc.csv')
f = open(output_csv_path,'w',newline = "")
writer_csv = csv.writer(f)
writer_csv.writerows(text_file_info)
f.close()


18.5 Appending to CSV File

Here is the code snippet for appending one row at a time to a csv file.


import csv

text_file_info = [[1],[2,4],[3,7],[4,10],[5,10,20,30]]

output_csv_path = os.path.join(main_folder_path,'saved_text','new_created_doc.csv')

f = open(output_csv_path,'a',newline = "")

writer_csv = csv.writer(f)

for each_row in text_file_info:

writer_csv.writerow(text_file_info)

f.close()


Here is the code snippet for appending all rows at once

import csv

text_file_info = [[1],[2,4],[3,7],[4,10],[5,10,20,30]]

output_csv_path = os.path.join(main_folder_path,'saved_text','new_created_doc.csv')

f = open(output_csv_path,'a',newline = "")

writer_csv = csv.writer(f)

writer_csv.writerows(text_file_info)

f.close()


19. Using Pickle in Python

19.1 Dumping to Pickle File

Here is the code snippet to dumping to pickle file


import pickle
a = 10
b = 20
c = {'a':[3003,3001],'b':[22,11]}
f = open(os.path.join(main_folder_path,"saved_data.pickle"),'wb')
pickle.dump([a,b,c],f)
f.close()

19.2 Loading from Pickle File


Here is the code snippet to load from pickle file

import pickle
f = open(os.path.join(main_folder_path,"saved_data.pickle"),'rb')
[d,e,f] = pickle.load(f)
print(d,type(d))
print(e,type(e))
print(f,type(f))

import pickle
f = open(os.path.join(main_folder_path,"saved_data.pickle"),'rb')
loaded_info = pickle.load(f)
print(loaded_info)
d = loaded_info[0]
e = loaded_info[1]
f = loaded_info[2]
print(d,type(d))
print(e,type(e))
print(f,type(f))

20. Installing External Python Libraries

External python libraries can be installed by using following command in command prompt/terminal


pip install PACKAGE_NAME

where PACKAGE_NAME is a package/external library which needs to be installed.


For example,

In case you would like to install tensorflow library, you should run the following command

pip install tensorflow

21. Using Jupyter Notebook for Python


Instead of writing your code in .py file, you can also use Jupyter notebook on your browser for the same.


For using Jupyter Notebook, python library jupyter is needed. To install it, please use the following command

pip install jupyter

Now, Navigate to the folder where you would like to create a jupyter notebook and type the following command.

jupyter notebook

This would open the jupyter dashboard on your browser. Click on New and create a Python Notebook.


22. Using Google Colaboratory

In case if you don't have python installed in your system, you can still run your code online in cloud. One such way is using google colaboratory.


Go to the following URL


https://colab.research.google.com/


If you create new file, it will be similar to Jupyter Notebook and you can run it in the browser itself.

This notebook will be saved in google drive automatically.

One more Advantage, you can use this in any device (PC/Mobile) just that your browser should support it.


Main disadvantage is that each session can be maximum 12 hours after which it stops. You need to restart the kernel and run your code from beginning.


23. Classes in Python

In this section, we will discuss on pickling class instances and also on scope of variables in class at various levels.

For detailed explanation, please refer this video.







Using Classes in Python Part-2
In [5]:
import os
In [6]:
main_folder_path = r"E:\openknowledgeshare.blogspot.com\Python\Outputs"
In [7]:
class OSRelatedFunctions:

    def get_contents_in_folder(self,input_folder_path):
        content_list = []
        for each_folder in os.listdir(input_folder_path):
            full_path = os.path.join(input_folder_path,each_folder)
            print(full_path)
            if(os.path.isdir(full_path)):
                content_list += self.get_contents_in_folder(full_path)
            else:
                content_list.append(full_path)
        return content_list

    def create_folder(self,input_folder_path):
        if not os.path.exists(input_folder_path):
            os.makedirs(input_folder_path)

    def delete_folder(self,input_folder_path):
        if os.path.exists(input_folder_path):
            os.remove(input_folder_path)
In [8]:
os_func = OSRelatedFunctions()

1 Pickling class instances

In [10]:
import pickle
f = open(os.path.join(main_folder_path,'class.pickle'),'wb')
pickle.dump(os_func,f)
f.close()
In [11]:
f = open(os.path.join(main_folder_path,'class.pickle'),'rb')
new_class_loaded = pickle.load(f)
f.close()
In [13]:
dir(new_class_loaded)
Out[13]:
['__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__slotnames__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'create_folder',
 'delete_folder',
 'get_contents_in_folder']
In [15]:
new_class_loaded
Out[15]:
<__main__.OSRelatedFunctions at 0x240d17df7f0>

2. Scope of Variables in Classes

2.1. varaiable within functions of class

In [43]:
class ArthimeticFunctions:
    
    def __init__(self):
        print("Initialzied")
        self.a = 100
        self.b = 200
        
    def function1(self,c):
        self.a = self.a + c
        self.b = self.b -c
        return self.a,self.b
    
    def function2(self,d):
        self.a = self.a*d
        self.b = self.b/d
   
In [44]:
af1 = ArthimeticFunctions()
af2 = ArthimeticFunctions()
Initialzied
Initialzied
In [45]:
print(af1.a,af1.b)
print(af2.a,af2.b)
100 200
100 200
In [46]:
af1.function1(10)
Out[46]:
(110, 190)
In [47]:
af1.function1(10)
Out[47]:
(120, 180)
In [48]:
print(af1.a,af1.b)
print(af2.a,af2.b)
120 180
100 200

2.2. Defining varaible at scope of class

In [49]:
e = 1000

class ArthimeticFunctions:
    
    def __init__(self):
        print("Initialzied")
        self.a = 100
        self.b = 200
        
    def function1(self,c):
        self.a = self.a + c
        self.b = self.b -c
        return self.a,self.b
    
    def function2(self,d):
        self.a = self.a*d
        self.b = self.b/d
        
    def function3(self):
        self.a = self.a + e
        self.b = self.b - e
        return self.a,self.b
In [50]:
af = ArthimeticFunctions()
Initialzied
In [51]:
af.function3()
Out[51]:
(1100, -800)
In [98]:
class ArthimeticFunctions:
    
    varaiable1 = 50
    
    def __init__(self):
        print(self)
        print("Initialzied")
        self.a = 100
        self.b = 200
        
    def function1(self,c):
        self.a = self.a + c
        self.b = self.b -c
        return self.a,self.b
    
    def function2(self,d):
        a = self.a*d
        b = self.b/d
        return a,b
        
    def function3(self):
        self.a = self.a + e
        self.b = self.b - e
        return self.a,self.b
    
    def function4(self):
        print(varaiable1)
    
    def function5(self):
        print(self.varaiable1)
        self.varaiable1 = 100
        print(self.function3())
In [100]:
af_new
Out[100]:
<__main__.ArthimeticFunctions at 0x240d191f048>
In [99]:
af_new = ArthimeticFunctions()
<__main__.ArthimeticFunctions object at 0x00000240D191F048>
Initialzied
In [88]:
varaiable1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-88-5ac886194c02> in <module>
----> 1 varaiable1

NameError: name 'varaiable1' is not defined
In [89]:
af_new.function4()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-89-20fcf555a081> in <module>
----> 1 af_new.function4()

<ipython-input-86-8f585c1c12ac> in function4(self)
     24 
     25     def function4(self):
---> 26         print(varaiable1)
     27 
     28     def function5(self):

NameError: name 'varaiable1' is not defined
In [90]:
af_new.function5()
50
(1100, -800)
In [91]:
af_new.a,af_new.b,af_new.varaiable1
Out[91]:
(1100, -800, 100)
In [92]:
af_new.__init__()
Initialzied
In [93]:
af_new.a,af_new.b,af_new.varaiable1
Out[93]:
(100, 200, 100)
In [94]:
af_new.function1(10)
Out[94]:
(110, 190)
In [95]:
af_new.a,af_new.b,af_new.varaiable1
Out[95]:
(110, 190, 100)
In [96]:
af_new.function2(10)
Out[96]:
(1100, 19.0)
In [97]:
af_new.a,af_new.b,af_new.varaiable1
Out[97]:
(110, 190, 100)
In [ ]:
 
24.

We will be adding many more in this article. Please stay tuned for updates.

In case you are struck with any issues or ideas, please let us know through comments

Comments

Popular posts from this blog

How to run Jupyter Notebooks in Cloud

GUI Programming using Tkinter Python

How to download , install and configure Anaconda - Python