Python Basics

I was programming when I found interest in data science, earlier for nearly 5 years I was using MS Excel for data analysis and data handling until I touched the limits of excel. I found alternatives for excel that is the python for data analysis

Let me explain the python basics which I know is most useful for any data enthusiast

Environment for using python

I like to use Jupyter note book and VS code for the execution and writing the code

The extension of the python I like to use ipynb because it allows me to write multiple cells of code and execute it instantly

Print

Print function prints whatever content given to it, example

print(“Hello everyone!”)

Output: Hello everyone!

Here Hello everyone! Is the argument for the print function

Passing the variable in print function

no_of_chcolate = 10

print(f”I have {no_of_chcolate} chocolates”)

Output: I have 10 chocolates

Operators in python

Arithmetic operators in python

  • ** (Exponent)
  • % (modulo or remainder)
  • / (division)
  • // (quotient)
  • * (multiply)
  • – (subtract)
  • + (add)

Comparison operators

  • > Greater than
  • < Less than
  • <= Less than or equal to
  • >= Greater than or equal to
  • == Checking equality
  • != Not equal to

Logical (or Boolean) operators

  • True
  • False

Assignment operators

  • = assigns a value to a variable
  • += adds the variable along with itself
  • -= subtracts the variable along with itself
  • *= multiplies the variable along with itself
  • %= returns the remainder after dividing the variable along with itself
  • /= gives quotient, after dividing with the variable along with itself
  • //= returns only the integer part of the quotient with the variable along with itself

Data types

Data typeDescriptionExample
Numeric
intIntegers (whole numbers)X =10
FloatDecimal numbersX=10.01
complexReal + imaginary partX=10+2j
String
StringSequence of characterstext = “Hello, world!”
Boolean
BooleanTrue or FalseX= True
Ordered collections
ListOrdered collection of items (mutable)my_list = [1, 2, 3, “apple”]
TupleOrdered collection of items (immutable)my_tuple = (1, 2, 3, “apple”)
SetUnordered collection of unique itemsmy_set = {1, 2, 3, “apple”}
DictionaryUnordered collection of key-value pairsmy_dict = {“name”: “Alice”, “age”: 30}

String operations

OperationDescriptionSyntaxExample
Accessing charactersAccess individual characters using indexstring[index]text = “Python”; print(text[0])
SlicingExtract a substringstring[start:end:step]text = “Python”; print(text[1:4])
ConcatenationCombine stringsstring1 + string2str1 = “Hello”; str2 = “World”; result = str1 + ” ” + str2
LengthGet the length of a stringlen(string)text = “Python”; print(len(text))
Case conversionConvert case of characters.lower(), .upper(), .title(), .capitalize(), .swapcase()text = “Hello”; print(text.upper())
SearchingFind substrings.find(), .index(), .startswith(), .endswith()text = “Python”; print(text.find(“on”))
ReplacingReplace substrings.replace(old, new)text = “Python”; print(text.replace(“Py”, “Ja”))
StrippingRemove leading/trailing whitespace.strip(), .lstrip(), .rstrip()text = ” Python “; print(text.strip())
SplittingSplit a string into a list of substrings.split(separator)text = “apple,banana,cherry”; fruits = text.split(“,”)
JoiningJoin a list of strings into a single stringdelimiter.join(list)fruits = [“apple”, “banana”, “cherry”]; joined_text = “-“.join(fruits)
Checking contentCheck for specific content.isalpha(), .isdigit(), .isalnum(), .isspace()text = “123”; print(text.isdigit())
FormattingFormat strings with variablesf”string” or .format()name = “Alice”; age = 30; print(f”Hello, {name}! You are {age} years old.”)
JustificationAdds spacesrjust, ljust, or center‘328’.rjust(5,”*”) -> **328

Indentation

  • Enhances readability
  • Prevents error
  • Places indentation after : in loops or condition

Conditional statements

If-elif-else

grade = 85

if grade >= 90:

    print(“Excellent”)

elif grade >= 80:

    print(“Good”)

else:

    print(“Needs improvement”)

Shorthand way to write if statements

age = 10

is_adult = True if age >= 18 else False

is_adult

Nested if conditions

age = 25

country = “India”

if age >= 18:

    if country == “India”:

        print(“You are an adult citizen of the India “)

    else:

        print(“You are an adult, but not a Indian citizen”)

else:

    print(“You are a minor”)

Control flow statements

Break, Continue, Pass

StatementDescriptionExample
breakTerminate the loopfor i in range(10):     if i == 5:         break         print(i)
continueSkips current iterationfor i in range(5):     if i == 3:         continue         print(i)
passDoes nothing (place holder)if condition:     pass

Loops

While loopFor Loop
Controlled by a conditionControlled by the sequence length
count = 0 while count < 5:     print(count)     count += 1fruits = [“apple”, “banana”, “cherry”] for fruit in fruits:     print(fruit)  
i = 0 while i < 3:     j = 0     while j < 2:         print(i, j)         j += 1     i += 1for i in range(3):     for j in range(2):         print(i, j)

Functions

FunctionLambda function
def keywordlambda keyword
Multiple lines, can have complex logicSingle expression
General-purpose functionsShort, simple operations
def greet(name):   print(“Hello,”, name + “!”)   greet(“Alice”) # Output: Hello, Alice!double = lambda x: x * 2 result = double(5) # Output: 10

Syntax errors

Error TypeDescriptionExample
Missing colonRequired after if, else, for, while, def, and class statementsif condition print(“Hello”)
Incorrect indentationIndentation to define code blocksif condition: print(“Hello”) print(“World”)
Mismatched parentheses/brackets/bracesUnbalanced parentheses, brackets, or bracesprint(“Hello, world(“)
Missing quotesUnclosed stringsprint(Hello)
Invalid charactersUsing characters not allowed in variable names123variable = 10
Keyword misuseUsing keywords as variable namesprint = “Hello”
Unexpected EOF (End of File)Code ends prematurely, missing closing parentheses, brackets, or quotesprint(“Hello

Errors in python

Error TypeDescriptionExample
NameErrorUse a variable that doesn’t existprint(x) (if x is not defined)
TypeErrorOperation on incompatible typeshello’ + 5
ValueErrorCorrect type but improper valueint(‘abc’)
IndexErrorAccess index which is out of rangemy_list[5] (if list has only 4 elements)
ZeroDivisionErrorDivision by zero10 / 0
KeyErrorAccess a nonexistent key in a dictionarymy_dict[‘nonexistent_key’]

Read files in excel

df = sns.load_dataset(“titanic”)

df = pd.read_csv(r”C:\Users\User\Documents\file.csv”)

Save to a file

df.to_csv(r”Data.csv”)

Containers

Lists

OperationSyntaxDescriptionExample
Accessing elementslist[index]Access an element at a specific index (starts from 0)my_list = [1, 2, 3]; print(my_list[0])
Slicinglist[start:end:step]Extract a sublistmy_list = [1, 2, 3, 4, 5]; print(my_list[1:4:2])
Changing elementslist[index] = new_valueModify an element at a specific indexmy_list[0] = 10
Adding elementslist.append(item)Add an element to the end of the listmy_list.append(6)
Inserting elementslist.insert(index, item)Insert an element at a specific indexmy_list.insert(2, ‘hello’)
Adding multiple elementslist.extend(iterable)Extend the list with elements from another iterablemy_list.extend([2, ‘hello’])
Removing elementslist.remove(item)Remove the first occurrence of an itemmy_list.remove(3)
Delete elementDel list. [index]Delete element in indexdel my_list [0]
Removing element by indexlist.pop(index)Remove and return the element at a specific index (default: last)removed_item = my_list.pop(1)
Finding index of an elementlist.index(item)Return the index of the first occurrence of an itemindex = my_list.index(‘hello’)
Counting elementslist.count(item)Count the number of occurrences of an itemcount = my_list.count(2)
Sorting the listlist.sort()Sort the list in ascending ordermy_list.sort()
Reversing the listlist.reverse()Reverse the order of elements in the listmy_list.reverse()
Concatenating listslist1 + list2Combine two listscombined_list = my_list + [7, 8]
List lengthlen(list)Get the number of elements in the listlength = len(my_list)
Checking for membershipitem in listCheck if an item is present in the listif 3 in my_list:
Copying a listnew_list = list.copy()Create a shallow copy of the listnew_list = my_list.copy(
Finding minimum and maximummin(list), max(list)  
Multiplying a listlist * n  

Creating new list form existing list

FunctionSyntaxDescriptionExample
List Comprehension

Expression for item in iterable if condition

Creates a new list based on an iterable with optional filtering

numbers = [1, 2, 3, 4, 5]

squares = [x**2 for x in numbers if x % 2 == 0]  

# Squares of even numbers

print(squares)  

# Output: [4, 16]

Map

map(function, iterable, …)

Applies a function to each element of an iterable

numbers = [1, 2, 3, 4, 5]

def square(x):

    return x**2

squared_numbers = list(map(square, numbers))

print(squared_numbers)  

# Output: [1, 4, 9, 16, 25]

Filter

filter(function, iterable)

Creates an iterator of elements for which the function returns True

numbers = [1, 2, 3, 4, 5]

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers)

# Output: [2, 4]

Zip

zip(*iterables)

Aggregates elements from multiple iterables into tuples

numbers = [1, 2, 3]

letters = [‘a’, ‘b’, ‘c’]

zipped_list = list(zip(numbers, letters))

print(zipped_list)  

# Output: [(1, ‘a’), (2, ‘b’), (3, ‘c’)]

enumerate

enumerate(iterable, start=0)

Adds a counter to an iterable and returns it as an enumerate object

fruit = [‘apple’, ‘banana’, ‘cherry’]

for index, fru in enumerate(fruit):

    print(index, fru)

Concatenate

list1 + list2

Concatenate

list1 = [1, 2, 3]

list2 = [4, 5, 6]

combined_list = list1 + list2

extend

list1.extend(iterable)

Appends all elements

list1 = [1, 2, 3]

list2 = [4, 5, 6]

list1.extend(list2)

Tuples

OperationSyntaxDescriptionExample
Accessing elementstuple[index]Access an element at a specific index (starts from 0)my_tuple = (1, 2, 3) print(my_tuple[0])
Slicingtuple[start:end:step]Extract a sub-tuplemy_tuple = (1, 2, 3, 4, 5) print(my_tuple[1:4:2])
Concatenationtuple1 + tuple2Combine two tuples into a new tupletuple1 = (1, 2) tuple2 = (3, 4) combined_tuple = tuple1 + tuple2
Lengthlen(tuple)Get the number of elements in the tuplemy_tuple = (1, 2, 3) length = len(my_tuple)
Membership testingitem in tupleCheck if an item exists in the tupleif 2 in my_tuple:
Indexing and countingtuple.index(item), tuple.count(item)Find the index of an item or count its occurrencesindex = my_tuple.index(2) count = my_tuple.count(1)
Converting to a listlist(tuple)Convert a tuple to a list (for modification)my_list = list(my_tuple)

Applications of tuple

my_dict = {(1, 2): ‘value1’, (3, 4): ‘value2’}

Dictionary

OperationSyntaxDescriptionExample
Accessing valuedictionary[key]Retrieves the value associated with the given keymy_dict = {‘a’: 1, ‘b’: 2} value = my_dict[‘a’]
Adding or modifying a key-value pairdictionary[key] = valueAdds a new key-value pair or modifies an existing onemy_dict[‘c’] = 3
Deleting a key-value pairdel dictionary[key]Removes the key-value pair with the given keydel my_dict[‘b’]
Checking if a key existskey in dictionaryReturns True if the key exists, False otherwiseif ‘a’ in my_dict:
Getting all keysdictionary.keys()Returns a view of the dictionary’s keyskeys = my_dict.keys()
Getting all valuesdictionary.values()Returns a view of the dictionary’s valuesvalues = my_dict.values()
Getting key-value pairsdictionary.items()Returns a view of the dictionary’s key-value pairs as tuplesitems = my_dict.items()
Removing and returning a random itemdictionary.popitem()Removes and returns an arbitrary (key, value) pairremoved_item = my_dict.popitem()
Getting a value with a defaultdictionary.get(key, default_value)Returns the value for the key if it exists, otherwise returns the default valuevalue = my_dict.get(‘d’, 0)
Updating multiple key-value pairsdictionary.update(other_dict)Updates the dictionary with key-value pairs from another dictionarymy_dict.update({‘e’: 5, ‘f’: 6})
Clear the dictionarydictionary.clear()Removes all items from the dictionarymy_dict.clear()
Creating a copy of the dictionarynew_dict = dictionary.copy()Creates a shallow copy of the dictionarynew_dict = my_dict.copy()
Clearnew_dict.clear()Clears all key value pairsnew_dict.clear()
Setdefaultdictionary.setdefault(key, default_value)insert a key-value pair if the key doesn’t already exist in the dictionary It returns the value for the key if it existsmy_dict = {‘a’: 1, ‘b’: 2}   # Accessing an existing key value = my_dict.setdefault(‘a’, 10) print(value)  # Output: 1   # Adding a new key with a default value value = my_dict.setdefault(‘c’, 3) print(value)  # Output: 3   print(my_dict)  # Output: {‘a’: 1, ‘b’: 2, ‘c’: 3}  

Object oriented programming (oops)

Object-Oriented Programming (OOP) is a way to organize and structure code so that it’s easier to understand, reuse, and maintain

OOP allows to model real-world things using classes and objects

Key Concepts of OOP:

  1. Class
    • A class is like a blueprint for creating objects. It defines a set of attributes and methods that the objects created from the class will have
    • For example, think of a class as a blueprint for a car. It defines what a car is (attributes like color, brand, model) and what it can do (methods like drive, stop)

class Car:

    def __init__(self, color, brand, model):

        self.color = color

        self.brand = brand

        self.model = model

    def drive(self):

        print(f”The {self.color} {self.brand} {self.model} is driving.”)

    def stop(self):

        print(f”The {self.color} {self.brand} {self.model} has stopped.”)

  1. Object
    • An object is an instance of a class. If a class is the blueprint, then an object is the actual car built from the blueprint
    • We can create multiple objects from a single class, each with its own unique properties

my_car = Car(“red”, “Toyota”, “Corolla”)

my_car.drive()  # Output: The red Toyota Corolla is driving.

my_car.stop()   # Output: The red Toyota Corolla has stopped.

  1. Attributes
    • Attributes are the properties of an object
    • They represent the state or data of an object
    • In the Car class, attributes are color, brand, and model
  2. Methods
    • Methods are the functions defined inside a class that describe the behaviors of an object. In the Car class, drive and stop are methods
  3. Inheritance
    • Inheritance is a way to create a new class from an existing class
    • The new class, called the child class, inherits the attributes and methods of the existing class, called the parent class
    • This allows for code reuse and the creation of a hierarchical relationship between classes

class ElectricCar(Car):

    def __init__(self, color, brand, model, battery_capacity):

        super().__init__(color, brand, model)

        self.battery_capacity = battery_capacity

    def charge(self):

        print(f”The {self.color} {self.brand} {self.model} is charging its {self.battery_capacity} kWh battery.”)

my_electric_car = ElectricCar(“blue”, “Tesla”, “Model S”, 100)

my_electric_car.drive()  # Output: The blue Tesla Model S is driving.

my_electric_car.charge() # Output: The blue Tesla Model S is charging its 100 kWh battery.

  1. Encapsulation
    • Encapsulation is the concept of bundling data (attributes) and methods that operate on the data into a single unit or class
    • It also involves restricting access to certain details of an object to protect its integrity
    • In Python, you can indicate that an attribute is private by prefixing it with an underscore (_)

class Car:

    def __init__(self, color, brand, model):

        self._color = color  # Private attribute

    def get_color(self):

        return self._color

    def set_color(self, new_color):

        self._color = new_color

my_car = Car(“red”, “Toyota”, “Corolla”)

print(my_car.get_color())  # Output: red

my_car.set_color(“blue”)

print(my_car.get_color())  # Output: blue

  1. Polymorphism
    • Polymorphism allows methods to do different things based on the object it is acting upon, even if they share the same name
    • This is often achieved through method overriding, where a child class provides a specific implementation of a method that is already defined in its parent class

class Animal:

    def speak(self):

        pass

class Dog(Animal):

    def speak(self):

        return “Woof!”

Example:

Class: Define a class called Person with attributes like name, age, and gender, and methods like introduce and birthday.

class Person:

    def __init__(self, name, age, gender):

        self.name = name

        self.age = age

        self.gender = gender

    def introduce(self):

        print(f”Hi, my name is {self.name}. I am {self.age} years old and I am {self.gender}.”)

    def birthday(self):

        self.age += 1

        print(f”Happy birthday {self.name}! You are now {self.age} years old.”)

Object: Create instances of the Person class (objects) and call their methods.

# Create a person object

person1 = Person(“Alice”, 30, “female”)

# Call the introduce method

person1.introduce()  

# Output: Hi, my name is Alice. I am 30 years old and I am female.

# Call the birthday method

person1.birthday()  

# Output: Happy birthday Alice! You are now 31 years old.

# Create another person object

person2 = Person(“Bob”, 25, “male”)

# Call the introduce method

person2.introduce()

# Output: Hi, my name is Bob. I am 25 years old and I am male.

  • Class: Person is the class.
  • Attributes: name, age, and gender are attributes of the Person class.
  • Methods: introduce and birthday are methods of the Person class.
  • Objects: person1 and person2 are instances (objects) of the Person class.
Venu Kumar M
Venu Kumar M