1. Python basics for beginners
This is my first article in the “ML Roadmap” series. I would be covering all the topics required to become an ML engineer in the series.
This article will cover all the basics of python you need to know in order to kick start your ML journey.
Why Python?
- Easy to learn and can be learnt by anyone with ease.
- Developing code is easy since it is Compiled language.
- Python has a vast set of libraries which makes our life easier.
- Open-source language and there is an active community to assist you in learning.
- Many Machine learning Models can be built with ease using Python.
- Youtube, Quora, Surveymonkey, and many other popular websites are powered by python.
Before you start off your Journey in python. Install pycharm and python IDE. You can also download anaconda and use Jupyter Notebook for practice.
Variables in Python
- Variable is used to store data. In python, you do not need to declare the type of variable.
- Variable is created the moment you assign a value to it.
- You can also re-assign the value of a variable in python.
- Variables are case-sensitive.
- We can typecast variables from one data type to another.
- You cannot use keywords in naming Python Variables and no special character can be used.
rent=1220
gas=202.5
print(rent) #gives 1220
rent=100 #reassigning
print(rent)#gives 100
rent=str(100) #typecasting to string
Operators in Python
- +,-,*,%/ These operators will have the trivial meaning that we use to do calculations.
- ** Indicates the power operator.
- round(variable, temp) #Rounds off variable to temp number of decimal places
- Python follows the BODMAS rule and operator precedence.
- 6–5.7=0.2999999 #This happens because in any language floating numbers won't maintain accuracy while storing.
if Syntax in Python
while loop Syntax in Python
For loop Syntax in Python
Since all of us are familiar with For loop let's just learnthe syntax.
Functions in Python
- Makes code more modular. helps to form repetitive tasks very easily.
- Function declaration and function calling are different.
- Arguments are of two types name arguments and positional arguments.
- Positional Arguments: Depends on the order in which we call.
- Name arguments: We assign names while calling.
- Variables inside the function body are called local variables.
- def sum(a b=0) #if you don't pass argument then it makes b as zero but if you pass some argument then it will take that argument only. it won't take b as zero
- Documentation strings: we use triple codes to document code inside the function.
- The syntax for documentation:””” documentation of the function “””
Strings in Python
- Stores Characters in Contiguous locations.
- text=”sridhar” #stores in contiguous memory location.
- Strings are immutable.
- text[0]=’g’. Gives the error “str object is immutable.
- But you can re-assign the entire string to another string.
- text=” good boy” Doesn't give you an error.
- Accesing characters in a string:text[1] #gives s
- Slicing:text[0:3]-gives element at 0,1,2 position.
- Slicing: text[4:] #goes from 4th to end
- Slicing: text[:3]#goes from 0 to the second
- single-quote and double-quote can be used to define a string. After a starting quote when it encounters the ending quote it means the end of the string
- text=” hello” is the same as text=’hello’
- If you have a double quote outside use a single quote inside and vice-versa. text=” hello ‘word’” and text=’hello “world”’.
- Before the second quote is encountered if you press enter you get an “EOL while scanning the literal” error.
- Store string in Multiple Lines:address=” I live in \n NewYork \n USA”.
- Concatenation:str1+str2.Appends str2 to str1
- But to concatenate a number to a string we need to convert the number to str and then append.
s=”hello” num=25
s+num #cannot convert int object to str
s+str(num) #hello 25
List in Python
- items=[“bread”,”pasta”] #stored in contiguous memory locations
- Add all the items in the list separated by commas and within the closed brackets.
- The items in the list can be of different data types.
- We can use the index to access elements. #items[0] gives zeroth element
- The list is mutable. items[0]=”chips”
- To print a range of elements. items[0:2] gives the 0th and 1st element
- Negative Indexing: items[-1] will give the last element
- items.append(“butter”) #adds butter at the end
- items.insert(1,” butter”) #inserting butter at first index 1.
- Appending one list to another items=food+bathroom.
- food+” soda” #this is wrong both should be lists
- len(items) #gives the length of items list;
- to check if an element is in list: “bread” in items if bread is present in lists it returns true.
Dictionary in Python
- Also knows as hashtable, maps,associate arrays
- Syntax:d={“key”:value,”key”:value}
- Key can be string number anything. we use d[key] to access the value. In the list we use index.
- In the dictionary orders doesn't matter.
- Modify a value for a key-d[key]=newvalue
- delete a value-del d[key]
- Iterating through all values in a dictionary
8. We use an operator to check if the key is present in the dictionary or not.
Ex: key in d #this will return true if the key is present in dictionary d else it will give false
9.d.clear() #will wipe out everything
Tuple in Python
- list of values grouped together. Ex:point=(4,6)
- We can access tuples also using an index.
Tuple vs List
- In list, all values have the same meaning and in tuple, all values have different meanings (heterogeneous). for example, coordinates are represented as tuples they are of different type
- Tuples are immutable and lists are mutable. We cannot update in the tuple.
Sets and Frozen sets
- Set is an unordered collection of unique elements.
- Syntax:basket={“orange”,”apple”,”mango”,”apple”}
- a=set() #another way
- a.add(1) #adding an element to the set
- a={} #if there is nothing in curly braces then it is a dict
- unique_numbers=set(numbers) #getting unique numbers in the set
- Frozen set will not allow to add new elements
fs=frozenset(numbers)
fs
fs.add(5) #this will generate error
8.” a” in x #return true if a is present I x or not
9. Iteration: Using for loop
10. union of two sets:x|y
11.intersection:x&y
12.difference:x-y
13.to check if x is subset of y we use x<y it return boolean
Comprehensions
List Comprehension
Transforming one list to another.
numbers=[1,2,3,4,5,6,7]
even=[]
for i in numbers:
if i%2==0:
even.append(i)
#lets write this in one line
even=[i for i in numbers if i%2==0]
#lets generate square of numbers
sqr_numbers=[i*i for i in numbers]
Set Comprehension
Set is an unordered structure of non duplicate elements
s=set([1,2,3,4,5,2,3]) #it will remove the duplicate elements in the list passed
even={i for i in numbers if i%2==0} #list comprehension.
Dictionary Comprehension
cities=[“Mumbai”,” new york”,”paris”]
countries=[“india”,”usa”,”france”]
z=zip(cities,countries)
for a in z:
print(a)
output
(‘Mumbai’,’india’)
(‘newyork’,’usa’)
(‘pairs’,’France)
#dict comprehension we use zip function
d={city:country for city,country in zip(cities,countries))
d #you will get a dictionary
PIP Package
- pip is a tool that is installed automatically if you have python 2.7.9 later or python 3.4 or later
- pip installs packages in python. ex:pip install matplotlib
- we need to have an internet connection to download pip package since pip imports from the internet.
- PyPI-Python package Index-pip used this and installs it from this. If our module is there in the PyPI index then it will download
- To uninstall a package. pip uninstall “name of package”
Python Modules
- We can Re-use code written by someone else using Python Modules.
- dir(module) #gives all functions present in the module. we can also check
- import module #syntax to improve module
- Ex:import math math.pi,math.sqrt(16),math.floor(2.3),math.ceil(3)
- we can import modules as alias also example:import pandas as pd
6. We can also write our own python module
a)if the example.py is in the same directory, write a code file named example.py when you want to import the file just write import example.
b)if it is not in the same directory and is in some other directory named module subdirectory then import module.example #directory.file
c)if the file is in some other location
Working with JSON in Python
- JSON is java script object notation and is similar to xml.and is light weight compared to xml.because in xml we will have tags and will take lot more volume of data.
- here are no native obejcts as JSON in python.JSON in python is just dictionary.
book={} #creating a dictionary
book[‘tom’]={‘name’=’tom’,’address’=’1 red street’ }
book[‘bob’]={‘name’=’bob’,’address’=’2 red street’}
import json #import json module
s=json.dump(book) #taking book dictionary and using dump() to convert it into a string and then converting to json
print(s) #it will be a string but will be in the form of JSON.It will have all opening and closing brackets
with open(“c://data//book.txt”,”w”) as f:
(indentation)f.write(s) #writing s to book.txt file
#reading JSON
f=open(“c://data//book.txt”,”r”)
s=f.read()
s #prints the json present in the file in string format
#now to print the JSON i dictionary format
import json
book=json.loads(s)
book #prints json in dictionary format
type(book) #output of this is dict
now since you converted to the dictionary you can use all functions used on the dictionary here as well. You can play with JSON by converting it into the dictionary
Reading and writing files in Python
File open modes
Writing to a file
f=open(“c:\\data\\sridhar.txt”,”w”) #w is the file open mode
f.write(“I love python”)
f.close() #closes the file and clears the space
Appending to a file(appends data to already existing file while write re writes the data)
f.open(“filename”,”a”)
f.write(“\nI love java script”) #appends the text on to new line
f.close()
Reading a file line by line
f.open(“filename”,”r”)
print(f.read()) #reads what is there in file and prints it
f.close()
Reading line by line and counting the number of words
f.open(“filename”,”r”)
for line in f:
tokens=line.split(' ') #tokens is a list of words we are splitting the words using spaces. print(str(tokens)) #prints arrary of words line by line print(len(tokens)) #prints len of words in each line
if name==main
Refer to this comprehensive article on this concept:
Exceptional Handling
If an exception occurs program terminates in middle. We handle this using Exceptional Handling.
except ZeroDivisionError as e: #handling specific exception
use multiple except statements to handle multiple exceptions
print(type(e)) #finding type of exception
Finally, block: Finally block after try and catch will be executed irrespective of the occurrence of the exception.
Classes and Objects in Python
Class is the blueprint of an object and object is the implementation of the class.
Inheritance
- A class(derived class) inherits properties of another class(base class) this phenomenon is called inheritance.
- Uses of inheritance: Code reuse, Extensibility,Readability
Iterators in Python
- __iter()__ is a built-in method. Instead of using for to iterate lists, we can use iter to iterate.
- All loops internally use iterator
Example
a=[“hey”,”sridhar”,”are”,”ok”]
#iterating using for loop
for i in a:
(indent)print(i)
#using iter
itr=iter(a)
next(itr) #gives hey
next(itr) #gives sridhar
next(itr) #gives are
next(itr) #gives ok
next(itr) #gives error stop iteration
iterating in reversed order we use itr=reversed(a). This itr points to the last element.
If you have come till the end of this very lengthy blog.I admire your commitment to becoming an ML Engineer.
I have covered almost all the basics of Python. Still, there are topics like
Multithreading, Multiprocessing, Data structures to be covered. I will be covering these in the later stages of the series.
I would be writing on python libraries Numpy,Pandas,Matplotlib in the next blog.
If you loved the blog consider clapping below.😉
If you have any queries feel free to reach out.Would be happy to help.
Twitter:https://twitter.com/AvsSridhar2
Linkedin:https://www.linkedin.com/in/avs-sridhar-8b9904176/
All social profiles:https://linktr.ee/avssridhar
Happy Learning.Thank you.