Essential Python Installation and Programming Techniques

Practical No. 1

Aim:

Installation and configuration of Python.

Objective:

To successfully install Python on the system and configure the Python environment for development.

Procedure:

  1. Download Python:
    • Visit the official Python website (https://www.python.org) and download the latest version suitable for your operating system (Windows, macOS, or Linux).
  2. Install Python:
    • Run the downloaded installer and follow the on-screen instructions to complete the installation.
    • Ensure that you add Python to your system’s PATH during the installation process.
  3. Verify Installation:
    • Open a terminal or command prompt.
    • Type python --version and press Enter.
    • This should display the installed Python version.

Result:

  • Python is successfully installed on your system.
  • You can now use Python to write and execute scripts.

Practical No. 2

Aim:

Write a Python program to print Fibonacci sequences.

Code:

# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
    print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
    print("Fibonacci sequence up to", nterms, ":")
    print(n1)
# generate Fibonacci sequence
else:
    print("Fibonacci sequence:")
    while count < nterms:
        print(n1)
        nth = n1 + n2
        # update values
        n1 = n2
        n2 = nth
        count += 1

Output:

Practical No. 3

Aim:

Write a Python program to split an array at a given position and append the first part to the second part.

Code:

def split_and_append(arr, position):
    # Split the array into two parts
    first_part = arr[:position]
    second_part = arr[position:]
    # Append the first part to the second part
    result = second_part + first_part
    return result

# Example usage
array = [1, 2, 3, 4, 5, 6]
position = 3
# Perform the operation
new_array = split_and_append(array, position)
print("Original array:", array)
print("New array:", new_array)

Output:

Practical No. 4

Aim:

Write a Python program to check if the given string is a palindrome or not.

Input:

def is_palindrome(string):
    # Remove spaces and convert to lowercase for uniformity
    cleaned_string = ''.join(string.split()).lower()
    # Check if the string is equal to its reverse
    return cleaned_string == cleaned_string[::-1]

# Example usage
input_string = input("Enter a string: ")
if is_palindrome(input_string):
    print(f'"{input_string}" is a palindrome!')
else:
    print(f'"{input_string}" is not a palindrome.')

Output:

Practical No. 5

Aim:

Create a product database using a dictionary. Store the following information about a product:

  • p_id
  • p_name
  • p_company
  • p_price

Implement functions to:

  1. Add a new product to the dictionary
  2. Delete a specified product from the dictionary
  3. Update the price of a specified product
  4. Show details of a specified product
  5. Display a list of all the products

Input:

# Product database
product_database = {}

# Function to add a new product
def add_product(p_id, p_name, p_company, p_price):
    product_database[p_id] = {
        "name": p_name,
        "company": p_company,
        "price": p_price
    }
    print(f"Product {p_name} added successfully.")

# Function to delete a product
def delete_product(p_id):
    if p_id in product_database:
        del product_database[p_id]
        print(f"Product with ID {p_id} deleted successfully.")
    else:
        print("Product ID not found.")

# Function to update product price
def update_product_price(p_id, new_price):
    if p_id in product_database:
        product_database[p_id]["price"] = new_price
        print(f"Price updated for product ID {p_id}.")
    else:
        print("Product ID not found.")

# Function to show details of a specified product
def show_product_details(p_id):
    if p_id in product_database:
        product = product_database[p_id]
        print(f"Details of product ID {p_id}:")
        print(f"Name: {product['name']}, Company: {product['company']}, Price: {product['price']}")
    else:
        print("Product ID not found.")

# Function to display all products
def display_all_products():
    if not product_database:
        print("No products in the database.")
    else:
        print("All products:")
        for p_id, details in product_database.items():
            print(f"ID: {p_id}, Name: {details['name']}, Company: {details['company']}, Price: {details['price']}")

# Menu-driven program
def product_menu():
    while True:
        print("\nProduct Database Menu")
        print("1. Add new product")
        print("2. Delete product")
        print("3. Update product price")
        print("4. Show product details")
        print("5. Display all products")
        print("6. Exit")
        choice = input("Enter your choice (1-6): ")
        if choice == "1":
            p_id = input("Enter product ID: ")
            p_name = input("Enter product name: ")
            p_company = input("Enter product company: ")
            p_price = float(input("Enter product price: "))
            add_product(p_id, p_name, p_company, p_price)
        elif choice == "2":
            p_id = input("Enter product ID to delete: ")
            delete_product(p_id)
        elif choice == "3":
            p_id = input("Enter product ID to update price: ")
            new_price = float(input("Enter new price: "))
            update_product_price(p_id, new_price)
        elif choice == "4":
            p_id = input("Enter product ID to view details: ")
            show_product_details(p_id)
        elif choice == "5":
            display_all_products()
        elif choice == "6":
            print("Exiting the program.")
            break
        else:
            print("Invalid choice. Please try again.")

# Run the menu
product_menu()

Output:

Practical No. 6

Aim:

Create a simple calculator to perform basic arithmetic operations.

Input:

def calculator():
    print("Simple Calculator")
    print("Operations: +, -, *, /")
    # Get inputs from the user
    num1 = float(input("Enter the first number: "))
    operator = input("Enter an operator (+, -, *, /): ")
    num2 = float(input("Enter the second number: "))
    # Perform the calculation
    if operator == '+':
        result = num1 + num2
    elif operator == '-':
        result = num1 - num2
    elif operator == '*':
        result = num1 * num2
    elif operator == '/':
        if num2 == 0:
            return "Error: Division by zero is not allowed."
        result = num1 / num2
    else:
        return "Invalid operator. Please try again."
    return f"The result is: {result}"

# Run the calculator
print(calculator())

Output:

Practical No. 7

Aim:

Write a Python program to find the factorial of a given number using recursion.

Input:

print("Factorial of a number using recursion")
print()

def recur_factorial(n):
    if n == 1:
        return n
    else:
        return n * recur_factorial(n - 1)

num = int(input("Enter a number: "))
# check if the number is negative
if num < 0:
    print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    print("The factorial of", num, "is", recur_factorial(num))

Output:

Practical No. 8

Aim:

Create a JSON file to store employee details. Write a program to read and display the contents of the file.

Input:

import json

employee_json = '''[
    {
        "id": 1,
        "name": "John Doe",
        "position": "Software Engineer",
        "department": "Engineering",
        "salary": 80000
    },
    {
        "id": 2,
        "name": "Jane Smith",
        "position": "Product Manager",
        "department": "Product",
        "salary": 95000
    },
    {
        "id": 3,
        "name": "Sam Brown",
        "position": "Designer",
        "department": "Design",
        "salary": 70000
    }
]''' 

employee_data = json.loads(employee_json)
print("Employee Details:")
for employee in employee_data:
    print(f"ID: {employee['id']}")
    print(f"Name: {employee['name']}")
    print(f"Position: {employee['position']}")
    print(f"Department: {employee['department']}")
    print(f"Salary: ${employee['salary']}")
    print("-" * 30)

Output:

Practical No. 9

Aim:

Write a Python program to print the contents of a file in reverse order.

Input:

p.txt (notepad):

  • Hello, world!
  • Python is great.
  • Learning is fun.

Code:

with open('p.txt', 'r') as file:
    lines = file.readlines()
    reversed_lines = lines[::-1]
    for line in reversed_lines:
        print(line, end='')

Output:

Practical No. 10

Aim:

Write a program to read the e-commerce dataset and perform basic analysis using the pandas library.

Input:

import pandas as pd

# Load the dataset
file_path = 'ecommerce_data.csv'  # Replace with your actual file path
try:
    data = pd.read_csv(file_path)
    print("Dataset loaded successfully!")
except FileNotFoundError:
    print(f"File not found: {file_path}")
    exit()

# Display the first few rows
print("\nFirst 5 rows of the dataset:")
print(data.head())

# Basic information about the dataset
print("\nDataset Information:")
print(data.info())

# Summary statistics
print("\nSummary Statistics:")
print(data.describe())

# Checking for missing values
print("\nMissing Values in Each Column:")
print(data.isnull().sum())

# Checking unique categories (if there's a 'category' column)
if 'category' in data.columns:
    print("\nUnique Categories in 'category' Column:")
    print(data['category'].unique())

# Count the number of rows and columns
print("\nNumber of Rows and Columns:")
print(f"Rows: {data.shape[0]}, Columns: {data.shape[1]}")

# Example: Grouping by a column (e.g., 'category') and getting average sales
if 'category' in data.columns and 'sales' in data.columns:
    print("\nAverage Sales by Category:")
    print(data.groupby('category')['sales'].mean())

# Example: Most common values in a column (e.g., 'product_name')
if 'product_name' in data.columns:
    print("\nTop 5 Most Common Products:")
    print(data['product_name'].value_counts().head())

# Example: Sorting data by a column (e.g., 'price')
if 'price' in data.columns:
    print("\nTop 5 Most Expensive Products:")
    print(data.sort_values(by='price', ascending=False).head())

Output: