Categories
excel file python

read excel file in python

In this tutorial, we will learn about read excel file in python using the pandas library.

In this example, we are using the pandas library to read an excel file.

Pandas is an open-source library that has a lot of features inbuilt. Here we are using it for reading the excel file.
For More refer to official docs of the pandas
https://pandas.pydata.org/
For our exercise, I am going to use the below excel file format.

Pandas Installtion

pip install pandas

Read excel example

# Using pandas library
import pandas as panda


class ReadExcel:
    # Main method
    if __name__ == "__main__":
        # file path of xlsx file
        file_path = "D://data/Avengers.xlsx"
        # reading the excel file
        excel = panda.read_excel(file_path)
        print(excel)

Output

   ID   Character Name           Real Name
0   1             Hulk        Mark Ruffalo
1   2             Thor     Chris Hemsworth
2   3      Black Widow  Scarlett Johansson
3   4         Iron Man    Robert Downey Jr
4   5  Captain America         Chris Evans

References

https://beginnersbug.com/create-dataframe-in-python-using-pandas/

Related Articles

Categories
mongodb python

python with mongodb

In this post, we will see about connecting Python with MongoDB.

MongoDB is a fast and reliable NO SQL database that is used to store the data in JSON structure.

PyMongo

Here we are using the PyMongo library to connect MongoDB from python. refer https://pymongo.readthedocs.io/en/stable/

We already installed MongoDB, RoboMongo & pyhcarm for our development

I have created a database called avengers which have a collection as avengersdetails as like below image

PyMongo

Command to install pymongo library

pip install pymongo

PyMongo Import

import pymongo

In our example, we are using the OOPS concept to create the connection and fetch the data from Mongo DB.
Below line is the starting point of the code

if __name__ == "__main__":

Python with MongoDB Example

import pymongo


class MongoDbConn:

    # __init__ method will be used to initialize the variable
    # We need to pass the mongo db url & database name to this method
    def __init__(self, host_url, database):
        self.host_details = host_url
        self.db_name = database

    # Once you create the object you can connect the connection object from below method
    def get_mongodb_connection_details(self) -> object:
        my_client = pymongo.MongoClient(self.host_details)
        my_db = my_client[self.db_name]
        return my_db


if __name__ == "__main__":
    # Create an object for our class MongoDbConn
    obj = MongoDbConn("mongodb://localhost:27017/", "avengers")
    # Create database connection from the below line
    db_connection = obj.get_mongodb_connection_details()
    # pass your collection(table) name in below line
    collection_details = db_connection["avengersdetails"]
    for data in collection_details.find():
        print(data)

Output

{'_id': ObjectId('5fd0e603549a851a24a48c36'), 'ID': '1', 'Character Name': 'Hulk', 'Real Name': 'Mark Ruffalo'}
{'_id': ObjectId('5fd0e603549a851a24a48c37'), 'ID': '2', 'Character Name': 'Thor', 'Real Name': 'Chris Hemsworth'}
{'_id': ObjectId('5fd0e603549a851a24a48c38'), 'ID': '3', 'Character Name': 'Black Widow', 'Real Name': 'Scarlett Johansson'}
{'_id': ObjectId('5fd0e603549a851a24a48c39'), 'ID': '4', 'Character Name': 'Iron Man', 'Real Name': 'Robert Downey Jr'}
{'_id': ObjectId('5fd0e603549a851a24a48c3a'), 'ID': '5', 'Character Name': 'Captain America', 'Real Name': 'Chris Evans'}

Related Articles

Categories
python

for loop in python

In this tutorial, we will learn about for loop in python. We can iterate an array using for loop.

Syntax

for seq_val in sequence:
  body

Iterate array

cars = ["Honda", "Toyota", "Hyundai"]
for car in cars:
    print(car)

Output

Honda
Toyota
Hyundai

for loop using range

cars = ["Honda", "Toyota", "Hyundai"]
for i in range(len(cars)):
    print(cars[i])
Honda
Toyota
Hyundai

for loop with custom start value

cars = ["Honda", "Toyota", "Hyundai"]
for i in range(2, len(cars)):
    print(cars[i])

Output

Hyundai

Related Articles

Categories
python

Returning multiple values in python

In this post, let us learn about returning multiple values in python.

Will it possible in python?

Yes, returning multiple values in python is possible. There are several ways to do it.

1 . Return as Tuple :

The tuple stores the values of various datatypes. But we cannot modify those values in any case.

Please refer to the below link to understand it better.

https://beginnersbug.com/difference-between-list-and-tuple/

The tuple is created with or without a round bracket as below.

# Sample program to return as Tuple without bracket
def first():
 a="string"
 b=10
 return a,b
a,b=first()
print(a,b)

The above python function returns more than one value.

string 10

Tuple returns within a bracket as follows.

# Sample program to return as Tuple with bracket
def first():
 a="string"
 b=10
 return (a,b)
a,b=first()
print(a,b)
string 10
2 . Return as List :

The list is also a collection created with square bracket.

The list helps us in returning multiple values in python .

It is mutable in nature.

# Sample program to return as List
def second():
 a="apple"
 b=50
 return [a,b]
second_list=second()
print(second_list)

We return multiple values from the python function using the list.

['apple', 50]

We can identify the datatype of the return by using the below command

Categories
python

difference between list and tuple

In this post , let us learn about the difference between list and tuple.

What are Lists?

Lists are compound data types storing multiple independent values .

It can accommodate different datatypes like integer, string, float, etc., within a square bracket.

In the below example, we have different types of data getting created with the list.

# Creating lists with multiple datatypes 
a = [1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89]
What are Tuples ?

Tuples are also one of the sequence datatypes as like Lists.

Tuples can be created by storing the data within round bracket or without any brackets.

#Creating tuple with round bracket
b=(1,2,3,'a','b','c','apple','orange',10.89,(6,7,8))
#Creating tuple without any brackets
c=1,2,3,'a','b','c','apple','orange',10.89,(6,7,8)
What is the difference between list and tuple?

Lists are mutable whereas tuples are immutable.

We can change the lists but not the tuples.

program
# Creating  list a
a=[1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89]
# Displaying the data
a
# Displaying the datatype
type(a)
Result
[1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89]
list

We can append the list as shown below, But we cannot change the tuple.

This is the difference between the tuple and the list.

program
# Trying to append data to it
a.append('d')
a
RESULT
[1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89, 'd']