Wednesday, August 9, 2023

Q8) Write a Python program to generate a random alphabetical character, alphabetical string and alphabetical string of a fixed length. Use random.choice().

import random

import string

 

def generate_random_alphabetical_character():

    return random.choice(string.ascii_letters)

 

def generate_random_alphabetical_string(length):

    return ''.join(random.choice(string.ascii_letters) for _ in range(length))

 

def generate_fixed_length_alphabetical_string(length):

    return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))

 

random_char = generate_random_alphabetical_character()

print("Random Alphabetical Character:", random_char)

 

random_string = generate_random_alphabetical_string(10)

print("Random Alphabetical String:", random_string)

 

fixed_length_string = generate_fixed_length_alphabetical_string(8)

print("Fixed Length Alphabetical String:", fixed_length_string)

Q7) 7. Write a Menu Driver Program to add, display, update, delete and exit in a student database containing Student_id,Student_name,Course through Python-MongoDB connectivity

from pymongo import MongoClient

 

# Connect to MongoDB

client = MongoClient("mongodb://localhost:27017/")

db = client["StudentDatabase"]

collection = db["Students"]

 

def add_student():

    student_id = input("Enter Student ID: ")

    student_name = input("Enter Student Name: ")

    course = input("Enter Course: ")

   

    student_data = {

        "Student_id": student_id,

        "Student_name": student_name,

        "Course": course

    }

   

    result = collection.insert_one(student_data)

    print("Student added with ID:", result.inserted_id)

 

def display_students():

    students = collection.find()

    for student in students:

        print("Student ID:", student["Student_id"])

        print("Student Name:", student["Student_name"])

        print("Course:", student["Course"])

        print("-" * 20)

 

def update_student():

    student_id = input("Enter Student ID to update: ")

    new_course = input("Enter new Course: ")

   

    result = collection.update_one({"Student_id": student_id}, {"$set": {"Course": new_course}})

    if result.modified_count > 0:

        print("Student record updated successfully")

    else:

        print("No student found with the given ID")

 

def delete_student():

    student_id = input("Enter Student ID to delete: ")

   

    result = collection.delete_one({"Student_id": student_id})

    if result.deleted_count > 0:

        print("Student record deleted successfully")

    else:

        print("No student found with the given ID")

 

while True:

    print("\nMenu:")

    print("1. Add Student")

    print("2. Display Students")

    print("3. Update Student")

    print("4. Delete Student")

    print("5. Exit")

   

    choice = input("Enter your choice: ")

   

    if choice == "1":

        add_student()

    elif choice == "2":

        display_students()

    elif choice == "3":

        update_student()

    elif choice == "4":

        delete_student()

    elif choice == "5":

        print("Exiting program")

        break

    else:

        print("Invalid choice. Please select again.")


Q6) Write a Python multithreading program to print the thread name and corresponding process for each task (assume that there are four tasks).

import threading

 

def task(task_number):

    print(f"Task {task_number} in thread {threading.current_thread().name}")

 

def main():

    tasks = 4

   

    threads = []

    for i in range(tasks):

        thread = threading.Thread(target=task, args=(i+1,))

        threads.append(thread)

        thread.start()

   

    for thread in threads:

        thread.join()

   

    print("All tasks are completed")

 

if __name__ == "__main__":

    main()

 

Q5) Plot the following data on a line chart and customize the chart according to the below-given instructions:

import matplotlib.pyplot as plt

 

# Data

months = ["January", "February", "March", "April", "May"]

sales = [510, 350, 475, 580, 600]

 

# Create a line chart

plt.figure(figsize=(10, 6))  # Set the figure size

plt.plot(months, sales, color='blue', linestyle='--', marker='D', label='Sales')  # Line style, marker, and label

 

# Title and labels

plt.title("The Monthly Sales Report")

plt.xlabel("Month")

plt.ylabel("Sales")

 

# Legends

plt.legend()

 

# Show the plot

plt.show()

 

Q4)Write a Python multithreading program which creates two threads, one for calculating the square of a given number and other for calculating the cube of a given number.

import threading

 

def calculate_square(number):

    square = number * number

    print(f"Square of {number} is {square}")

 

def calculate_cube(number):

    cube = number * number * number

    print(f"Cube of {number} is {cube}")

 

def main():

    number = int(input("Enter a number: "))

   

    thread_square = threading.Thread(target=calculate_square, args=(number,))

    thread_cube = threading.Thread(target=calculate_cube, args=(number,))

   

    thread_square.start()

    thread_cube.start()

   

    thread_square.join()

    thread_cube.join()

   

    print("Both threads have finished")

 

if __name__ == "__main__":

    main()

Q3)Create the following DataFrame Sales containing year wise sales figures for five salespersons in INR. Use the years as column labels, and salesperson names as row labels.

import pandas as pd

 

# Create the DataFrame

data = {

    2018: [110, 130, 115, 118],

    2019: [205, 165, 206, 198],

    2020: [177, 175, 157, 183],

    2021: [189, 190, 179, 169]

}

 

salespersons = ["Kapil", "Kamini", "Shikhar", "Mohini"]

 

sales_df = pd.DataFrame(data, index=salespersons)

 

# Display row labels

print("Row Labels:")

print(sales_df.index)

 

# Display column labels

print("\nColumn Labels:")

print(sales_df.columns)

 

# Display data types of each column

print("\nData Types:")

print(sales_df.dtypes)

Q2 :- Write a python program to validate an email address by using regular expression.

import re

 

def validate_email(email):

    pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'

    if re.match(pattern, email):

        return True

    else:

        return False

 

# Test the program

email_to_validate = input("Enter an email address: ")

 

if validate_email(email_to_validate):

    print("Valid email address")

else:

    print("Invalid email address")

Q5) Demonstrate a program to perform the Insertion & updation of records using PHP Script in Student table with appropriate field.

 

<?php

$servername = "localhost"; // Change this to your server name

$username = "root"; // Change this to your database username

$password = ""; // Change this to your database password

$dbname = "dbStudents";

 

// Create a connection

$conn = new mysqli($servername, $username, $password, $dbname);

 

// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

 

// Insertion: Process form submission to insert a new student record

if (isset($_POST['insert'])) {

    $rollNo = $_POST['roll_no'];

    $name = $_POST['name'];

    $age = $_POST['age'];

 

    // Insert new student record into the Student table

    $insert_sql = "INSERT INTO Student (RollNo, Name, Age) VALUES ('$rollNo', '$name', '$age')";

 

    if ($conn->query($insert_sql) === TRUE) {

        echo "Record inserted successfully<br>";

    } else {

        echo "Error inserting record: " . $conn->error . "<br>";

    }

}

 

// Updation: Process form submission to update an existing student record

if (isset($_POST['update'])) {

    $rollNoToUpdate = $_POST['roll_no_to_update'];

    $newName = $_POST['new_name'];

    $newAge = $_POST['new_age'];

 

    // Update student record in the Student table

    $update_sql = "UPDATE Student SET Name = '$newName', Age = '$newAge' WHERE RollNo = '$rollNoToUpdate'";

 

    if ($conn->query($update_sql) === TRUE) {

        echo "Record updated successfully<br>";

    } else {

        echo "Error updating record: " . $conn->error . "<br>";

    }

}

 

// Close the connection

$conn->close();

?>

 

<!DOCTYPE html>

<html>

<head>

    <title>Student Records</title>

</head>

<body>

    <h1>Student Records</h1>

 

    <!-- Insertion Form -->

    <h2>Insert New Student Record</h2>

    <form method="post" action="">

        Roll No: <input type="text" name="roll_no" required><br>

        Name: <input type="text" name="name" required><br>

        Age: <input type="text" name="age" required><br>

        <input type="submit" name="insert" value="Insert Record">

    </form>

 

    <!-- Updation Form -->

    <h2>Update Student Record</h2>

    <form method="post" action="">

        Roll No to Update: <input type="text" name="roll_no_to_update" required><br>

        New Name: <input type="text" name="new_name" required><br>

        New Age: <input type="text" name="new_age" required><br>

        <input type="submit" name="update" value="Update Record">

    </form>

</body>

</html>

Q4) • Demonstrate a PHP Program to update a Dept of employee of given Empno from Employee table (create database dbEMP with appropriate field). Accept roll number and name from the user.

 

<?php

$servername = "localhost"; // Change this to your server name

$username = "root"; // Change this to your database username

$password = ""; // Change this to your database password

$dbname = "dbEMP";

 

// Create a connection

$conn = new mysqli($servername, $username, $password, $dbname);

 

// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

 

// Process form submission

if (isset($_POST['update'])) {

    $empno = $_POST['empno'];

    $newDept = $_POST['new_dept'];

 

    // Update department for the given Empno

    $sql = "UPDATE Employee SET Dept = '$newDept' WHERE Empno = '$empno'";

 

    if ($conn->query($sql) === TRUE) {

        echo "Department updated successfully<br>";

    } else {

        echo "Error updating department: " . $conn->error . "<br>";

    }

}

 

// Close the connection

$conn->close();

?>

 

<!DOCTYPE html>

<html>

<head>

    <title>Update Employee Department</title>

</head>

<body>

    <h1>Update Employee Department</h1>

    <form method="post" action="">

        <label for="empno">Employee Number (Empno):</label>

        <input type="text" name="empno" required><br>

 

        <label for="new_dept">New Department:</label>

        <input type="text" name="new_dept" required><br>

 

        <input type="submit" name="update" value="Update Department">

    </form>

</body>

</html>

 

Q3)Demonstrate a code in PHP to create calculator which will accept two values as arguments, then add them, subtract them, multiply them together, or divide them on request.

 

<?php

function add($a, $b) {

    return $a + $b;

}

 

function subtract($a, $b) {

    return $a - $b;

}

 

function multiply($a, $b) {

    return $a * $b;

}

 

function divide($a, $b) {

    if ($b == 0) {

        return "Cannot divide by zero";

    }

    return $a / $b;

}

 

if (isset($_POST['calculate'])) {

    $value1 = $_POST['value1'];

    $value2 = $_POST['value2'];

    $operation = $_POST['operation'];

 

    switch ($operation) {

        case 'add':

            $result = add($value1, $value2);

            break;

        case 'subtract':

            $result = subtract($value1, $value2);

            break;

        case 'multiply':

            $result = multiply($value1, $value2);

            break;

        case 'divide':

            $result = divide($value1, $value2);

            break;

        default:

            $result = "Invalid operation";

    }

}

?>

 

<!DOCTYPE html>

<html>

<head>

    <title>Simple Calculator</title>

</head>

<body>

    <h1>Simple Calculator</h1>

    <form method="post" action="">

        <label for="value1">Value 1:</label>

        <input type="number" name="value1" required><br>

 

        <label for="value2">Value 2:</label>

        <input type="number" name="value2" required><br>

 

        <label for="operation">Select Operation:</label>

        <select name="operation">

            <option value="add">Add</option>

            <option value="subtract">Subtract</option>

            <option value="multiply">Multiply</option>

            <option value="divide">Divide</option>

        </select><br>

 

        <input type="submit" name="calculate" value="Calculate">

    </form>

 

    <?php if (isset($result)) : ?>

        <h2>Result: <?php echo $result; ?></h2>

    <?php endif; ?>

</body>

</html>

Q2 )Create a website using HTML and CSS code to design webpages as follows - The first webpage will accept the name of the traveller, date of travel, telephone number. It also has submit button as an image. The second webpage has information about the name of transporter, time , seatno and destination displayed one belowtheotherintheformofunorderedlistas • Name of transporter– AirAsia • Time - 09:30am • Seatno– B39 • Destination–Delhi Both pages should be interlinked. Create external style sheet with relevant tags

 

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="styles.css">

    <title>Traveler Information</title>

</head>

<body>

    <div class="container">

        <h1>Traveler Information</h1>

        <form action="transporter.html">

            <label for="name">Name:</label>

            <input type="text" id="name" name="name" required><br>

 

            <label for="date">Date of Travel:</label>

            <input type="date" id="date" name="date" required><br>

 

            <label for="phone">Telephone Number:</label>

            <input type="tel" id="phone" name="phone" required><br>

 

            <input type="image" src="submit_button.png" alt="Submit">

        </form>

    </div>

</body>

</html>

 

 

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="styles.css">

    <title>Transporter Information</title>

</head>

<body>

    <div class="container">

        <h1>Transporter Information</h1>

        <ul>

            <li><strong>Name of Transporter:</strong> AirAsia</li>

            <li><strong>Time:</strong> 09:30am</li>

            <li><strong>Seat No:</strong> B39</li>

            <li><strong>Destination:</strong> Delhi</li>

        </ul>

    </div>

</body>

</html>

 

 

body {

    font-family: Arial, sans-serif;

    margin: 0;

    padding: 0;

    background-color: #f0f0f0;

}

 

.container {

    max-width: 600px;

    margin: 50px auto;

    padding: 20px;

    background-color: #fff;

    border-radius: 10px;

    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);

}

 

h1 {

    text-align: center;

    margin-bottom: 20px;

}

 

form {

    text-align: center;

}

 

form label, form input[type="text"], form input[type="date"], form input[type="tel"] {

    display: block;

    margin-bottom: 10px;

    width: 100%;

}

 

ul {

    list-style: none;

    padding: 0;

}

 

ul li {

    margin-bottom: 10px;

}