1. Python basics for beginners

avs sridhar
10 min readSep 1, 2021

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?

  1. Easy to learn and can be learnt by anyone with ease.
  2. Developing code is easy since it is Compiled language.
  3. Python has a vast set of libraries which makes our life easier.
  4. Open-source language and there is an active community to assist you in learning.
  5. Many Machine learning Models can be built with ease using Python.
  6. 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

  1. Variable is used to store data. In python, you do not need to declare the type of variable.
  2. Variable is created the moment you assign a value to it.
  3. You can also re-assign the value of a variable in python.
  4. Variables are case-sensitive.
  5. We can typecast variables from one data type to another.
  6. 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

  1. +,-,*,%/ These operators will have the trivial meaning that we use to do calculations.
  2. ** Indicates the power operator.
  3. round(variable, temp) #Rounds off variable to temp number of decimal places
  4. Python follows the BODMAS rule and operator precedence.
  5. 6–5.7=0.2999999 #This happens because in any language floating numbers won't maintain accuracy while storing.

if Syntax in Python

Follow the indentation properly

while loop Syntax in Python

For loop Syntax in Python

Since all of us are familiar with For loop let's just learnthe syntax.

Looping through String
Break Statement
Continue Statement
using range()

Functions in Python

Syntax of Function in Python
  1. Makes code more modular. helps to form repetitive tasks very easily.
  2. Function declaration and function calling are different.
  3. Arguments are of two types name arguments and positional arguments.
  4. Positional Arguments: Depends on the order in which we call.
  5. Name arguments: We assign names while calling.
  6. Variables inside the function body are called local variables.
  7. 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
  8. Documentation strings: we use triple codes to document code inside the function.
  9. The syntax for documentation:””” documentation of the function “””
Local and Global Variables

Strings in Python

  1. Stores Characters in Contiguous locations.
  2. text=”sridhar” #stores in contiguous memory location.
  3. Strings are immutable.
  4. text[0]=’g’. Gives the error “str object is immutable.
  5. But you can re-assign the entire string to another string.
  6. text=” good boy” Doesn't give you an error.
  7. Accesing characters in a string:text[1] #gives s
  8. Slicing:text[0:3]-gives element at 0,1,2 position.
  9. Slicing: text[4:] #goes from 4th to end
  10. Slicing: text[:3]#goes from 0 to the second
  11. 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
  12. text=” hello” is the same as text=’hello’
  13. If you have a double quote outside use a single quote inside and vice-versa. text=” hello ‘word’” and text=’hello “world”’.
  14. Before the second quote is encountered if you press enter you get an “EOL while scanning the literal” error.
  15. Store string in Multiple Lines:address=” I live in \n NewYork \n USA”.
  16. Concatenation:str1+str2.Appends str2 to str1
  17. 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

  1. items=[“bread”,”pasta”] #stored in contiguous memory locations
  2. Add all the items in the list separated by commas and within the closed brackets.
  3. The items in the list can be of different data types.
  4. We can use the index to access elements. #items[0] gives zeroth element
  5. The list is mutable. items[0]=”chips”
  6. To print a range of elements. items[0:2] gives the 0th and 1st element
  7. Negative Indexing: items[-1] will give the last element
  8. items.append(“butter”) #adds butter at the end
  9. items.insert(1,” butter”) #inserting butter at first index 1.
  10. Appending one list to another items=food+bathroom.
  11. food+” soda” #this is wrong both should be lists
  12. len(items) #gives the length of items list;
  13. to check if an element is in list: “bread” in items if bread is present in lists it returns true.

Dictionary in Python

  1. Also knows as hashtable, maps,associate arrays
  2. Syntax:d={“key”:value,”key”:value}
  3. Key can be string number anything. we use d[key] to access the value. In the list we use index.
  4. In the dictionary orders doesn't matter.
  5. Modify a value for a key-d[key]=newvalue
  6. delete a value-del d[key]
  7. Iterating through all values in a dictionary
Iterating a dictionary
Iteration using tuple

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

  1. list of values grouped together. Ex:point=(4,6)
  2. We can access tuples also using an index.

Tuple vs List

  1. 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
  2. Tuples are immutable and lists are mutable. We cannot update in the tuple.

Sets and Frozen sets

  1. Set is an unordered collection of unique elements.
  2. Syntax:basket={“orange”,”apple”,”mango”,”apple”}
  3. a=set() #another way
  4. a.add(1) #adding an element to the set
  5. a={} #if there is nothing in curly braces then it is a dict
  6. unique_numbers=set(numbers) #getting unique numbers in the set
  7. 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

  1. pip is a tool that is installed automatically if you have python 2.7.9 later or python 3.4 or later
  2. pip installs packages in python. ex:pip install matplotlib
  3. we need to have an internet connection to download pip package since pip imports from the internet.
  4. 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
  5. To uninstall a package. pip uninstall “name of package”

Python Modules

  1. We can Re-use code written by someone else using Python Modules.
  2. dir(module) #gives all functions present in the module. we can also check
  3. import module #syntax to improve module
  4. Ex:import math math.pi,math.sqrt(16),math.floor(2.3),math.ceil(3)
  5. we can import modules as alias also example:import pandas as pd
Working with calender module

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

Using sys to append path

Working with JSON in Python

  1. 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.
  2. 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

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.

Syntax to handle the exception

except ZeroDivisionError as e: #handling specific exception

use multiple except statements to handle multiple exceptions

print(type(e)) #finding type of exception

raising an exception in a code
User-defined 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

  1. A class(derived class) inherits properties of another class(base class) this phenomenon is called inheritance.
  2. Uses of inheritance: Code reuse, Extensibility,Readability
Example of inheritance
Multiple inheritances

Iterators in Python

  1. __iter()__ is a built-in method. Instead of using for to iterate lists, we can use iter to iterate.
  2. 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.

Creating an iterator object

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.

--

--