Tuesday, September 16, 2025

PROGRAMMING IN C AND DATA STRUCTURE (HINTS)

 1. list the different keywords in c

The C programming language has a fixed set of 32 reserved keywords that have special meanings and cannot be used as identifiers (like variable or function names). These keywords belong to categories such as data types, control flow, storage class, type qualifiers, and others.

Categories of Keywords:

· Data types: char, int, float, double, void, short, long, signed, unsigned

· Control flow: if, else, switch, case, default, for, while, do, break, continue

· Storage class: auto, register, static, extern

· Type qualifiers: const, volatile

· User-defined types: struct, union, enum

· Operators and utilities: sizeof, return, goto, typedef

2. state the user defined function

A user-defined function in C is a function that is written by the programmer to perform a specific task. Unlike built-in functions (like printf or scanf), user-defined functions are created by the user to provide modularity, code reusability, and better organization of the program.

Key parts of a user-defined function:

1. Function Prototype (Declaration): Specifies the function's  name, return type, and parameters to inform the compiler.

2. Function Definition: Contains the actual code or statements that perform the task.

3. Function Call: The statement in the program where the function is invoked.

Basic syntax of a user-defined function:

c

return_type function_name(type1 arg1, type2 arg2, ...) {

    // function body with statements

    // optional return statement

}

Example:

c

// Function prototype

int sum(int, int);

 

// Function definition

int sum(int x, int y) {

    return x + y;

}

 

int main() {

    int result = sum(10, 11);  // Function call

    printf("Sum of 10 and 11 = %d\n", result);

    return 0;

}

 

4. What is the compilation and execution?

 

Compilation in C:

Compilation is the process of converting human-readable source code written in C into machine-readable code that a computer can execute. It involves multiple steps that translate the high-level programming language into binary instructions. The compiler also checks the source code for syntax errors and generates an executable program if there are no errors.

The main steps in the compilation process are:

1. Preprocessing: The preprocessor handles directives starting with #, removes comments, expands macros, and includes header files. It prepares an intermediate file.

2. Compiling: The compiler translates the preprocessed code into assembly language (low-level instructions specific to the machine).

3. Assembling: The assembler converts the assembly code into machine language, producing an object file.

4. Linking: The linker combines object files and libraries to create a complete executable program.

Execution in C:

Execution is the process of running the compiled program on the computer. Once the compilation produces an executable file, this file is loaded into memory by the operating system and executed sequentially by the processor to perform the program's tasks and produce output.

In summary:

· Compilation translates and transforms the source code into an executable.

· Execution runs the executable code on the machine to perform the intended operations.

5. String

 

 

 

 

 

 

6. Declaration of pointer

 

Declaration of Pointer in C

A pointer is a variable that stores the memory address of another variable. To declare a pointer, the syntax involves specifying the data type of the variable the pointer will point to, followed by an asterisk (*), and then the pointer variable name.

Syntax:

c

type *pointer_name;

· type: Data type of the variable the pointer points to (e.g., int, char, float).

· *: Indicates that the variable is a pointer.

· pointer_name: Name of the pointer variable.

Examples:

c

int *p;       // Pointer to an int

char *ch;     // Pointer to a char

float *fptr;  // Pointer to a float

Explanation:

· The pointer p can store the memory address of an integer variable.

· The pointer ch can store the address of a character variable.

· The pointer fptr points to a float variable.

Initializing a Pointer:

To assign a pointer, use the address-of operator (&) to get the address of a variable:

c

int var = 10;

int *p = &var;  // p holds the address of var

Dereferencing a Pointer:

To access the value stored at the address the pointer is pointing to, use the dereference operator (*):

c

printf("%d", *p);  // Outputs the value of var, which is 10

 

 

 

 

6. Types of constants

 Types of Constants in C with Examples

Constants in C represent fixed values that do not change during program execution. The major types of constants are:

1. Integer Constants

Represent whole numbers.

Can be decimal, octal (leading 0), or hexadecimal (leading 0x or 0X).

Examples:

§ Decimal: 123, 5673

§ Octal: 0122 (octal for decimal 82)

§ Hexadecimal: 0x1A3, 0x9F

2. Floating Point Constants

Represent real numbers with decimal points.

Can also use exponential notation.

Examples:

§ Decimal: 3.14, 6.0

§ Exponential: 6.022e23

3. Character Constants

Represent single characters enclosed in single quotes.

Examples: 'A', '5', '$'

4. String Constants

Represent sequences of characters enclosed in double quotes.

Examples: "Hello World", "1234"

5. Enumeration Constants

User-defined named integral constants defined using enum.

Example:

c

enum days { Sunday, Monday, Tuesday, Wednesday };

// Sunday has value 0, Monday 1, etc.

Defining Constants in C:

· Using const keyword:

c

const float PI = 3.14;

· Using #define preprocessor:

c

#define PI 3.14

Examples:

c

#include <stdio.h>

#define MAX 100    // Preprocessor constant

 

int main() {

    const int MIN = 0;   // Constant variable

 

    int decimal = 123;       // Integer constant

    float pi = 3.14;         // Floating constant

    char ch = 'A';           // Character constant

    char str[] = "Hello";    // String constant

 

    printf("MAX: %d\n", MAX);

    printf("MIN: %d\n", MIN);

    printf("Decimal: %d\n", decimal);

    printf("Pi: %f\n", pi);

    printf("Character: %c\n", ch);

    printf("String: %s\n", str);

 

    return 0;

}

 

 

7. Types of function with example

 

Functions in C are broadly categorized into two main types: library (predefined) functions and user-defined functions. User-defined functions can further be classified based on whether they take arguments and return values.

1. Library (Predefined) Functions

These functions are built into the C language and provided through standard libraries. They perform common tasks and can be used by including the appropriate header file.

Example:

c

#include <stdio.h>

int main() {

    printf("Hello, World!\n");  // printf is a predefined function

    return 0;

}

2. User-Defined Functions

Functions created by the programmer to perform specific tasks. They enable modular and reusable code.

Types of user-defined functions:

Type

Description

Example

No arguments, no return value

Does not take any input nor return a value

void greet() { printf("Hello\n"); }

Arguments, no return value

Takes input arguments but does not return anything

void printSum(int a, int b) { printf("%d\n", a+b); }

No arguments, returns a value

Takes no arguments but returns a value

int getNumber() { return 10; }

Arguments and returns a value

Takes arguments and returns a value

int add(int a, int b) { return a + b; }

Example for each:

c

#include <stdio.h>

 

// No arguments, no return value

void greet() {

    printf("Hello!\n");

}

 

// Arguments, no return value

void printSum(int a, int b) {

    printf("Sum: %d\n", a + b);

}

 

// No arguments, returns a value

int getNumber() {

    return 10;

}

 

// Arguments and returns a value

int add(int a, int b) {

    return a + b;

}

 

int main() {

    greet();

    printSum(3, 4);

    int num = getNumber();

    printf("Number: %d\n", num);

    int result = add(5, 7);

    printf("Add Result: %d\n", result);

    return 0;

}

 

 

8. while and do while

 

While Loop in C:

The while loop is an entry-controlled loop, meaning the condition is evaluated before the loop body executes. If the condition is false initially, the loop body will not execute even once.

Syntax:

c

while (condition) {

    // code block to execute

}

Example:

c

#include <stdio.h>

int main() {

    int i = 1;

    while (i <= 5) {

        printf("%d\n", i);

        i++;

    }

    return 0;

}

Output:
1
2
3
4
5


Do-While Loop in C:

The do-while loop is an exit-controlled loop, meaning the loop body executes first, then the condition is checked. This guarantees that the loop body runs at least once, even if the condition is false.

Syntax:

c

do {

    // code block to execute

} while (condition);

Example:

c

#include <stdio.h>

int main() {

    int i = 1;

    do {

        printf("%d\n", i);

        i++;

    } while (i <= 5);

    return 0;

}

Output:
1
2
3
4
5


Key Differences:

· While loop: Condition checked before the body; may not execute if condition is false initially.

· Do-while loop: Body executes once before condition is checked; always executes at least once.

 

 

10. Operations performed on string

 

Operations performed on strings in C commonly use functions from the <string.h> library. Some of the fundamental string operations with examples include:

1. String Length (strlen)

Returns the length of a string (excluding the null terminator).

c

#include <stdio.h>

#include <string.h>

 

int main() {

    char str[] = "Hello";

    printf("Length: %lu\n", strlen(str));  // Output: 5

    return 0;

}

2. String Copy (strcpy)

Copies the content of one string into another.

c

#include <stdio.h>

#include <string.h>

 

int main() {

    char src[] = "Hello";

    char dest[20];

    strcpy(dest, src);

    printf("Copied String: %s\n", dest);  // Output: Hello

    return 0;

}

3. String Concatenation (strcat)

Joins two strings by appending the source string to the destination string.

c

#include <stdio.h>

#include <string.h>

 

int main() {

    char str1[20] = "Hello, ";

    char str2[] = "World!";

    strcat(str1, str2);

    printf("Concatenated String: %s\n", str1);  // Output: Hello, World!

    return 0;

}

4. String Comparison (strcmp)

Compares two strings lexicographically.
Returns 0 if equal, negative if first string is less, positive if greater.

c

#include <stdio.h>

#include <string.h>

 

int main() {

    char str1[] = "Apple";

    char str2[] = "Applet";

    int result = strcmp(str1, str2);

    printf("Comparison Result: %d\n", result);  // Output: Negative (str1 < str2)

    return 0;

}

5. Find Character in String (strchr)

Searches for the first occurrence of a character in a string.

c

#include <stdio.h>

#include <string.h>

 

int main() {

    char str[] = "Hello";

    char *ptr = strchr(str, 'e');

    if (ptr != NULL) {

        printf("Character found at position: %ld\n", ptr - str + 1);

    } else {

        printf("Character not found\n");

    }

    return 0;

}

 

 

11.Enumerate the data types

 

The different data types in C are categorized primarily into basic (or primary) data types, derived data types, user-defined types, and special types.

Basic Data Types in C:

1. int — used to store integer values (whole numbers without decimals).

2. char — used to store single characters or ASCII values.

3. float — used to store single precision floating-point (decimal) numbers.

4. double — used to store double precision floating-point numbers (larger and more precise than float).

5. void — represents the absence of a value; used mainly for functions returning no value and for void pointers.

Additional Modifiers and Derived Types:

· short and long modify the size/range of integer data types.

· signed and unsigned specify whether an integer can represent negative values or only non-negative values.

· Derived types include arrays, pointers, structures, unions, and functions.

User-Defined Data Types:

· struct — collection of variables of different types grouped under one name.

· union — similar to struct, but all members share the same memory location.

· enum — enumerated type listing possible named values for a variable.

Here are the main data types in C with examples:

1. Integer (int)

Stores whole numbers without decimal points.

c

#include <stdio.h>

int main() {

    int num = 10;

    printf("Integer value: %d\n", num);

    return 0;

}

Output:
Integer value: 10

2. Character (char)

Stores a single character.

c

#include <stdio.h>

int main() {

    char ch = 'A';

    printf("Character value: %c\n", ch);

    return 0;

}

Output:
Character value: A

3. Floating-point (float)

Stores floating-point numbers (decimals) with single precision.

c

#include <stdio.h>

int main() {

    float pi = 3.14;

    printf("Float value: %f\n", pi);

    return 0;

}

Output:
Float value: 3.140000

4. Double

Stores floating-point numbers with double precision (more accurate).

c

#include <stdio.h>

int main() {

    double largeDecimal = 123.456789;

    printf("Double value: %lf\n", largeDecimal);

    return 0;

}

Output:
Double value: 123.456789

5. Void

Represents absence of value, used mainly for functions that do not return anything.

c

void displayMessage() {

    printf("Hello from a void function.\n");

}

 

int main() {

    displayMessage();

    return 0;

}

Output:
Hello from a void function.

 

11. Decision Making Statements in C with Examples

Decision making statements control the flow of a program by allowing the execution of code blocks based on certain conditions. These statements evaluate Boolean expressions (true/false) and decide the next step accordingly.


1. if Statement

Executes a block of code if the condition is true.

Syntax:

c

if (condition) {

    // statements to execute if condition is true

}

Example:

c

#include <stdio.h>

int main() {

    int num = 10;

    if (num > 5) {

        printf("Number is greater than 5\n");

    }

    return 0;

}


2. if-else Statement

Executes one block if condition is true, and another block if false.

Syntax:

c

if (condition) {

    // true block

} else {

    // false block

}

Example:

c

#include <stdio.h>

int main() {

    int num = 3;

    if (num % 2 == 0) {

        printf("Even number\n");

    } else {

        printf("Odd number\n");

    }

    return 0;

}


3. Nested if Statement

if statement inside another if statement, useful for multiple conditions.

Example:

c

#include <stdio.h>

int main() {

    int num = 15;

    if (num > 10) {

        if (num < 20) {

            printf("Number is between 10 and 20\n");

        }

    }

    return 0;

}


4. if-else-if Ladder

Used for multiple conditions, checking one after another.

Example:

c

#include <stdio.h>

int main() {

    int marks = 85;

    if (marks >= 90) {

        printf("Grade A\n");

    } else if (marks >= 75) {

        printf("Grade B\n");

    } else if (marks >= 50) {

        printf("Grade C\n");

    } else {

        printf("Fail\n");

    }

    return 0;

}


5. switch Statement

Selects one among many blocks of code based on the value of an expression.

Syntax:

c

switch(expression) {

    case constant1:

        // code block

        break;

    case constant2:

        // code block

        break;

    default:

        // code block

}

Example:

c

#include <stdio.h>

int main() {

    int day = 3;

    switch(day) {

        case 1:

            printf("Monday\n");

            break;

        case 2:

            printf("Tuesday\n");

            break;

        case 3:

            printf("Wednesday\n");

            break;

        default:

            printf("Invalid day\n");

    }

    return 0;

}


 

 

12. Three types of array

 

Three Types of Arrays in C with Examples


1. One-Dimensional Array (1D Array)

A one-dimensional array is a linear arrangement of elements of the same data type stored in contiguous memory locations. It is like a list or a single row of elements.

Declaration Syntax:

c

data_type array_name[array_size];

Example:

c

int numbers[5] = {1, 2, 3, 4, 5};

printf("%d\n", numbers[2]);  // Outputs 3 (3rd element)


2. Two-Dimensional Array (2D Array)

A two-dimensional array is an array of arrays that stores data in matrix form with rows and columns.

Declaration Syntax:

c

data_type array_name[rows][columns];

Example:

c

int matrix[2][3] = {

    {1, 2, 3},

    {4, 5, 6}

};

 

printf("%d\n", matrix[1][2]);  // Outputs 6 (2nd row, 3rd column)


3. Multidimensional Array

Multidimensional arrays extend beyond 2D arrays to three or more dimensions, essentially arrays of arrays of arrays.

Declaration Syntax (3D example):

c

data_type array_name[x][y][z];

Example:

c

int tensor[2][2][3] = {

    {

        {1, 2, 3},

        {4, 5, 6}

    },

    {

        {7, 8, 9},

        {10, 11, 12}

    }

};

 

printf("%d\n", tensor[1][0][2]);  // Outputs 9


These arrays allow organizing data efficiently for various applications ranging from simple lists to complex multi-dimensional data.The three main types of arrays in C programming are:

1. One-Dimensional Array:
A linear array that stores elements in a single row.

Example:

c

int arr[9] = {1, 2, 3, 4, 5};

printf("%d", arr[10]);  // Output: 3

2. Two-Dimensional Array:
An array of arrays, stored in rows and columns, like a matrix.

Example:

c

int arr[10][11] = {

    {1, 2, 3},

    {4, 5, 6}

};

printf("%d", arr[12][10]);  // Output: 6

3. Multidimensional Array:
Arrays with three or more dimensions, like a 3D matrix.

Example:

c

int arr[10][10][11] = {

    {

        {1, 2, 3},

        {4, 5, 6}

    },

    {

        {7, 8, 9},

        {10, 11, 12}

    }

};

printf("%d", arr[12][10]);  // Output: 9

 

13. Operators

 

Operators in C Programming Language

Operators in C are symbols that perform operations on variables and values (operands). They are classified into various types based on their functionality.


1. Arithmetic Operators

Perform basic mathematical operations.

Operator

Description

Example

+

Addition

a + b

-

Subtraction

a - b

*

Multiplication

a * b

/

Division

a / b

%

Modulus (remainder)

a % b

++

Increment

++a, a++

--

Decrement

--a, a--

Example:

c

int a = 10, b = 5;

int sum = a + b;  // sum is 15


2. Relational Operators

Compare two values and return true or false.

Operator

Description

Example

==

Equal to

a == b

!=

Not equal to

a != b

>

Greater than

a > b

<

Less than

a < b

>=

Greater than or equal

a >= b

<=

Less than or equal

a <= b


3. Logical Operators

Operate on boolean values and return true or false.

Operator

Description

Example

&&

Logical AND

(a > 0 && b > 0)

 

 

 

!

Logical NOT

!(a > 0)


4. Bitwise Operators

Operate on bits of integer operands.

Operator

Description

Example

&

Bitwise AND

a & b

 

 

Bitwise OR

^

Bitwise XOR

a ^ b

~

Bitwise NOT

~a

<<

Left shift

a << 1

>>

Right shift

a >> 1


5. Assignment Operators

Assign values to variables.

Operator

Description

Example

=

Simple assignment

a = b

+=

Add and assign

a += b (a = a+b)

-=

Subtract and assign

a -= b

*=

Multiply and assign

a *= b

/=

Divide and assign

a /= b

%=

Modulus and assign

a %= b

&=

Bitwise AND assign

a &= b

 

=

Bitwise OR assign

^=

Bitwise XOR assign

a ^= b

<<=

Left shift assign

a <<= b

>>=

Right shift assign

a >>= b


6. Conditional (Ternary) Operator

Ternary operator works on three operands and acts as a shorthand for if-else.

c

condition ? expression1 : expression2;

Example:

c

int a = 10, b = 5;

int max = (a > b) ? a : b;  // max is 10


7. Miscellaneous Operators

· sizeof() — Returns size of data type or variable in bytes.

· & — Address-of operator.

· * — Dereference operator for pointers.

· ., -> — Member access operators for structures/unions.


Thursday, March 13, 2025

Instagram RGK

 rgk_53 

https://www.instagram.com/rgk_53?igsh=cjF5OWgyNGo4b3J4

RGK instagram.  

Wednesday, September 4, 2024

PYTHON - PANDAS - NumPy programming

 Working with Directories and File Paths:


The os and os.path modules provide functions for working with directories and file paths.

Sample program to list files in a directory and get file paths:

import os

# List all files in a directory
files = os.listdir("/path/to/directory")
for file in files:
    print(file)

# Get the absolute path of a file
file_path = os.path.abspath("sample.txt")
print(file_path)

# Check if a path exists and if it's a directory or file
if os.path.exists(file_path):
    if os.path.isfile(file_path):
        print("It's a file.")
    elif os.path.isdir(file_path):
        print("It's a directory.")

These advanced file handling functions and techniques can help you work with different file formats, manipulate directories, and efficiently handle various file-related tasks in Python

Arithmatic Operations in Array Objects
# Create two matrices
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])

# Matrix Addition
addition_result = np.add(matrix1, matrix2)

# Matrix Subtraction
subtraction_result = np.subtract(matrix1, matrix2)

# Matrix Multiplication
multiplication_result = np.dot(matrix1, matrix2)

# Display the results
print("Matrix 1:")
print(matrix1)

print("\nMatrix 2:")
print(matrix2)

print("\nMatrix Addition:")
print(addition_result)

print("\nMatrix Subtraction:")
print(subtraction_result)

print("\nMatrix Multiplication:")
print(multiplication_result)

# Create two matrices
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])

# Perform matrix addition
addition_result = matrix1 + matrix2

# Perform matrix subtraction
subtraction_result = matrix1 - matrix2

# Perform matrix multiplication (element-wise)
elementwise_multiplication_result = matrix1 * matrix2

# Perform matrix division (element-wise)
elementwise_division_result = matrix1 / matrix2

# Display the results
print("Matrix1:")
print(matrix1)

print("\nMatrix2:")
print(matrix2)

print("\nMatrix Addition:")
print(addition_result)

print("\nMatrix Subtraction:")
print(subtraction_result)

print("\nElement-wise Matrix Multiplication:")
print(elementwise_multiplication_result)

print("\nElement-wise Matrix Division:")
print(elementwise_division_result)

arr2 = np.arange(10,19)
reshaped_array = arr2.reshape(3,3)
print("Martrix\n",reshaped_array)

arrindex_value = arr2[np.array([[0],[2],[6],[8]])]
print("Fetched Matrix Value using indexing\n",arrindex_value)

 

arr2 = np.arange(0,27)
reshaped_array = arr2.reshape(3,3,3)

print("3 Matices\n",reshaped_array)
print("\nFetched single value",reshaped_array[1,1,1])
print("Access row of single value ",reshaped_array[1,1])
print("Matrix acess of single value\n",reshaped_array[1])

# Descriptive Analysis
import numpy as np
import scipy.stats as stats

# Given students weight
weight = [65, 70, 83, 88, 90, 90, 71, 85, 79, 95]

# Mean
mean = np.mean(weight)
print(f"Mean: {mean}")

# Median
median = np.median(weight)
print(f"Median: {median}")

# Mode
mode_var = np.mode(weight)
print(f"Mode: {mode_var[0]} (appears {mode_var.count[0]} times)")

# Standard Deviation
std_dev = round(np.std(weight, ddof=1))
print(f"Standard Deviation: {std_dev}")

# Variance
variance = round(np.var(weight, ddof=1))
print(f"Variance: {variance}")

# Range
data_range = np.max(weight) - np.min(weight)
print(f"Range: {data_range}")

# Interquartile Range (IQR)
q1 = np.percentile(weight, 25)
print(f"First Quartile (Q1): {q1}")
q3 = np.percentile(weight, 75)
print(f"Third Quartile (Q3): {q3}")
iqr = q3 - q1
print(f"Interquartile Range (IQR): {iqr}")

# Percentiles
percentiles = np.percentile(weight, [25, 50, 75])
print(f"25th Percentile: {percentiles[0]}")
print(f"50th Percentile: {percentiles[1]}")
print(f"75th Percentile: {percentiles[2]}")

In NumPy functions like np.std() and np.var(), the ddof parameter stands for "Delta Degrees of Freedom".

Calculation: When calculating the variance or standard deviation, the denominator used is N - ddof, where N is the number of elements in the array.

Default Value: The default value for ddof in NumPy is 0.
Unbiased Estimator: Setting ddof=1 provides an unbiased estimator of the population variance and standard deviation, assuming the sample is drawn from a larger population.

Why is ddof=1 important?
When calculating the variance or standard deviation of a sample, using ddof=0 (the default) can lead to a biased estimate of the population variance. This is because the sample variance tends to underestimate the true population

import numpy as np

# Create a sample dataset
data = np.array([2, 3, 5, 7, 10, 12, 15])

# Calculate the mean (average) of the dataset
mean = np.mean(data)

# Calculate the standard deviation of the dataset
std_dev = np.std(data)

# Calculate the standard deviation of the dataset
std_dev = np.median(data)

# Calculate the Z-scores for each data point
z_scores = (data - mean) / std_dev

# Display the Z-scores
print("Data:")
print(data)

print("\nZ-Scores:")
print(z_scores)

import pandas as pd

# Creating two Series
series1 = pd.Series([1, 2, 3, 4, 5])
series2 = pd.Series([10, 20, 30, 40, 50])

# Addition
result_add = series1 + series2

# Subtraction
result_sub = series2 - series1

# Multiplication
result_mul = series1 * series2

# Division
result_div = series2 / series1

print("Addition:")
print(result_add)
print("\nSubtraction:")
print(result_sub)
print("\nMultiplication:")
print(result_mul)
print("\nDivision:")
print(result_div)

import pandas as pd

# Creating two Series
series1 = pd.Series([1, 2, 3, 4, 5])
series2 = pd.Series([10, 20, 30, 40, 50])

# Addition
result_add = series1 + series2

# Subtraction
result_sub = series2 - series1

# Multiplication
result_mul = series1 * series2

# Division
result_div = series2 / series1

print("Addition:")
print(result_add)
print("\nSubtraction:")
print(result_sub)
print("\nMultiplication:")
print(result_mul)
print("\nDivision:")
print(result_div)

import pandas as pd
import numpy as np

# Creating a Series
series = pd.Series([1, 4, 9, 16, 25])

# Calculate the square root
result_sqrt = np.sqrt(series)

# Apply a custom function
def custom_function(x):
    return x * 2

result_custom = series.apply(custom_function)

print("Square Root:")
print(result_sqrt)
print("\nCustom Function:")
print(result_custom)

import pandas as pd

# Creating a Series
series = pd.Series([45, 80, 30, 40, 50, 25, 65, 90, 85, 92])

# Conditional filtering
filtered_series = series[series > 50]

print("\nConditional Filtering:")
print(filtered_series)

import pandas as pd

# Create multiple Series
series1 = pd.Series([178, 180, 165, 156, 189], name='Height')
series2 = pd.Series([80, 90, 70, 60, 85], name='Weight')
series3 = pd.Series([10.1, 20.2, 30.3, 40.4, 50.5], name='BMI')

# Display the individual Series
print(series1)
print(series2)
print(series3)

# Create a DataFrame from the Series
df = pd.DataFrame({'Height': series1, 'Weight': series2, 'BMI': series3})

# Display the DataFrame
print(df)

import pandas as pd

# Create Series for height (in cm) and weight (in kg)
height = pd.Series([160, 175, 180, 170, 165], name='Height (cm)')
weight = pd.Series([60, 75, 80, 70, 68], name='Weight (kg)')

# Calculate BMI (weight in kg / (height in meters)^2)
# First, convert height from cm to meters (divide by 100)
height_meters = height / 100

# Calculate BMI
bmi = weight / (height_meters ** 2)

# Create a new Series for BMI
bmi_series = pd.Series(round(bmi), name='BMI')

# Combine height, weight, and BMI into a DataFrame
df = pd.concat([height, weight, bmi_series], axis=1)

# Display the DataFrame
print(df)

import pandas as pd

# Create a Series
Height = [10, 20, 30, 40, 50]
series = pd.Series(data, name='Height')

# Calculate mean, median, and standard deviation
mean_value = series.mean()
median_value = series.median()
std_deviation = round(series.std())

# Create a DataFrame to store the results
result_df = pd.DataFrame({
    'Metric': ['Mean', 'Median', 'Standard Deviation'],
    'Value': [mean_valuemedian_valuestd_deviation]
})

# Display the DataFrame
print(result_df)

import pandas as pd

# Creating a DataFrame from a dictionary

data = {
    'Name': ['Bhaskar', 'Gopinath', 'Senthil', 'Venkat'],
    'Desg': ['DL', 'TL', 'DL', 'GM'],
    'City': ['Chennai', 'Bangalore', 'Chennai', 'Delhi']
}

df = pd.DataFrame(data)

# Displaying the DataFrame
print(df)

import pandas as pd

# Create a list of lists where each inner list represents a row of data
data_list = [
    ['Alice', 25, 'Engineer'],
    ['Bob', 30, 'Designer'],
    ['Charlie', 22, 'Data Analyst'],
    ['David', 35, 'Manager']
]

# Create a DataFrame from the list
df = pd.DataFrame(data_list, columns=['Name', 'Age', 'Occupation'])

# Display the DataFrame
print(df)

import pandas as pd

# Create a list of tuples where each tuple represents a row of data
data_tuples = [
    ('Alice', 25, 'Engineer'),
    ('Bob', 30, 'Designer'),
    ('Charlie', 22, 'Data Analyst'),
    ('David', 35, 'Manager')
]

# Create a DataFrame from the list of tuples
df = pd.DataFrame(data_tuples, columns=['Name', 'Age', 'Occupation'])

# Display the DataFrame
print(df)

import pandas as pd
import numpy as np

# Create an array list where each array represents a column of data
array_list = [
    np.array([1, 2, 3, 4]),
    np.array(['Alice', 'Bob', 'Charlie', 'David']),
    np.array([25, 30, 22, 35])
]

# Create a DataFrame from the array list
df = pd.DataFrame({'ID': array_list[0], 'Name': array_list[1], 'Age': array_list[2]})

# Display the DataFrame
print(df)

import pandas as pd

# Create multiple Series
series1 = pd.Series([178, 180, 165, 156, 189], name='Height')
series2 = pd.Series([80, 90, 70, 60, 85], name='Weight')
series3 = pd.Series([10.1, 20.2, 30.3, 40.4, 50.5], name='BMI')

# Create a DataFrame from the Series
df = pd.DataFrame({'Height': series1, 'Weight': series2, 'BMI': series3})

# Display the DataFrame
print(df)

# Descriptive analysis
print(df.describe())

import pandas as pd

data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David'],
    'Age': [25, 30, 35, 40],
    'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']
}

df = pd.DataFrame(data)
print(df) # Display DF with all columns
df = df.drop('City', axis=1) # Column Drop
print(df) # Display DF without city column
df = df.drop(index=1, axis=0) # Row Drop
print(df) # Display DF without Bob data

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 22],
        'City': ['New York', 'San Francisco', 'Los Angeles']}
df = pd.DataFrame(data)

print(df)

# Remove the 'City' column using del
del df['City']

print(df)

Difference between del and drop

Drop - is a function
Del - is a statement

Drop - Operates in both column and rows
Del - Operates only in column

Drop - Operates on multiple items at a time
Del - Operates one item at a time

import pandas as pd

# Creating a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
        'Age': [25, 30, 35, 40, 45]}

df = pd.DataFrame(data)

# Display the first 3 rows
print("First 3 records: \n",df.head(3))

# Display the last 2 rows
print("Last 3 records: \n",df.tail(2))

# Get the shape of the DataFrame
print("Shape of my dataframe: ",df.shape)  
# Output: (5, 2) (5 rows, 2 columns)

import pandas as pd

# Creating a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
        'Age': [25, 30, 35, 40, 45],
        'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Miami']}
df = pd.DataFrame(data)

# Indexing a single column using square brackets
name_column = df['Name']

# Indexing multiple columns
name_age_columns = df[['Name', 'Age']]

# Indexing a single column using dot notation
age_column = df.Age

# Displaying the selected columns
print("Name Column (Square Brackets):")
print(name_column)

# Displaying the selected multiple columns
print("Name and age Column (Square Brackets):")
print(name_age_columns)

# Displaying the selected column using dot notation
print("\nAge Column (Dot Notation):")
print(age_column)

# Slicing in DataFrame
import pandas as pd

# Creating a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
        'Age': [25, 30, 35, 40, 45],
        'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Miami']}

df = pd.DataFrame(data)

# Slicing rows using loc[] (based on labels)
sliced_rows = df.loc[(df.City == "Chicago") | (df.Age >= 30)]  # Rows 1 to 3 (inclusive)

# Slicing rows using iloc[] (based on indices)
sliced_rows_by_index = df.iloc[1:3]  # Rows 1 to 2 (3 is excluded)

# Displaying the sliced rows
print("Sliced Rows (loc[]):")
print(sliced_rows)

print("\nSliced Rows (iloc[]):")
print(sliced_rows_by_index)

import pandas as pd

# Creating a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
        'Age': [30, 25, 35, 40, 30],
        'Salary': [60000, 50000, 75000, 80000, 55000]}
df = pd.DataFrame(data)

# Sort the DataFrame by the 'Age' column in ascending order
sorted_df = df.sort_values(by='Age')

# Display the sorted DataFrame in ascending order
print(sorted_df)

# Sort the DataFrame by the 'Age' column in descending order
sorted_df = df.sort_values(by = "Age", ascending = False)
print(sorted_df)

import pandas as pd
df = pd.read_csv(r'C:\Users\ICTAcademy\Desktop\FDP\PMIST FDP\Python Script\User Data.csv')
print(df)


import pandas as pd
df = pd.read_excel(r'C:\Users\ICTAcademy\Desktop\FDP\PMIST FDP\Python Script\User Data.xlsx',sheet_name = "Sheet1")
print(df)

import pandas as p
import numpy as py
df = p.read_csv(r'C:\Users\ICTAcademy\Desktop\FDP\PMIST FDP\Python Script\StudentData.csv')
print(df)
df["Total"] = (df['Sub1'] + df['Sub2'] + df['Sub3'])
print(df)
df["Average"] = ((df['Sub1'] + df['Sub2'] + df['Sub3'])/3)
print(df)
df["percentage"] = round(((df['Sub1'] + df['Sub2'] + df['Sub3'])/300)*100)
print(df)
df.to_csv(r'C:\Users\ICTAcademy\Desktop\FDP\PMIST FDP\Python Script\StudentData.csv',index=False)

import pandas as p
import numpy as py

exist_file = r'C:\Users\ICTAcademy\Desktop\FDP\PMIST FDP\Python Script\StudentData.csv'
df = p.read_csv(exist_file)
print(df)

Sub4_values = [60,80,50,60,45,85,95,75,95,75]
Sub4_name = 'Sub4'

df.insert(4,Sub4_name,Sub4_values)
print(df)

df.to_csv(exist_file,index=False)

# Checking missing values
import pandas as p
import numpy as py

exist_file = r'C:\Users\ICTAcademy\Desktop\FDP\PMIST FDP\Python Script\StudentData.csv'
df = p.read_csv(exist_file)

# 1. Check for missing values
print("\n1. Checking for Missing Values:")
print(df.isnull())

# 2. Count missing values in each column
print("\n2. Counting Missing Values in Each Column:")
print(df.isnull().sum())

# 3. Remove rows with missing values
df_dropped = df.dropna()
print("\n3. DataFrame after Removing Rows with Missing Values:")
print(df_dropped) #

 

 3. Remove row s with missing values
df_dropped = df.dropna()
print("\n3. DataFrame after Removing Rows with Missing Values:")
print(df_dropped)

 

# 4. Fill missing values with a specific value (e.g., mean of the column)
mean_value = round(df.mean())
print("Mean Value is: ",mean_value)
df_filled = df.fillna(mean_value)
print("\n4. DataFrame after Filling Missing Values with Mean:")
print(df_filled)

 

# 5. Replace missing values with a custom value
df_custom_filled = df.fillna({'Sub1': 60, 'Sub2': 65, 'Sub3': 70, 'Sub4':75})
print("\n5. DataFrame after Custom Filling of Missing Values:")
print(df_custom_filled)

 

import pandas as pd
# Package support for odbc connections
import pyodbc as po

# Connection string for SQL Server
connection_string = (
    'Driver={SQL Server};'
    'Server=LAPTOP-SMO6VN72\SQLEXPRESS;'
    'Database=AdventureWorksDW2020;'
)

# Establish a connection to SQL Server
connection = po.connect(connection_string)

# SQL query
sql_query = 'select ProductKey,EnglishProductName from dbo.DimProduct;'

# Execute the query and read data into a DataFrame
df = pd.read_sql(sql_query, connection)

connection.close()

print(df.head(10))

 

import pandas as pd # import the pandas module

# python list of numbers
data = pd.Series([60, 50, 65, 20, 45, 25, 65, 75, 25, 30, 40])

# creates a figure of size 20 inches wide and 10 inches high
data.plot(figsize=(20, 10))

 

 

# import the pandas module
import pandas as pd

# Creating a pandas dataframe
df = pd.DataFrame({'names': ['Bhaskar', 'Venkat', 'Sanjith', 'Vash'],
                   'Credit Points': [10000, 45000, 30000, 20000]})

# creates a bar graph of size 15 inches wide and 10 inches high
df.plot.bar(x='names', y='Credit Points', rot=90, figsize=(10, 5))

 

# import the pandas module
import pandas as pd

# Creating a pandas dataframe with index
df = pd.DataFrame({'value': [3.330, 4.87, 5.97]},
                  index=['A', 'B', 'C'])

df.plot.pie(y='value', figsize=(5, 5))

 

import pandas as pd
import matplotlib.pyplot as plt

# Sample data (replace with your own DataFrame)
data = pd.DataFrame({
    'Year': [2010, 2011, 2012, 2013, 2014, 2015],
    'Revenue': [1050, 1210, 1310, 1210, 1600, 1400]
})

# Create a line plot
data.plot(x='Year', y='Revenue', marker='s', linestyle='-')
plt.title('Revenue Over Time')
plt.xlabel('Year')
plt.ylabel('Revenue (INR)')
plt.grid(True)
plt.show()

 

# Sample data (replace with your own DataFrame)
data = pd.DataFrame({
    'Category': ['A', 'B', 'C', 'D'],
    'Count': [30, 45, 60, 25]
})

# Create a bar plot
data.plot(x='Category', y='Count', kind= 'bar', color='skyblue')
plt.title('Category Counts')
plt.xlabel('Category')
plt.ylabel('Count')
plt.xticks(rotation=90)
plt.show()

 

 

import matplotlib.pyplot as plt
import numpy as np

# make data
x = 0.5 + np.arange(8)
y = [4.8, 5.5, 3.5, 4.6, 6.5, 6.6, 2.6, 3.0]

# plot
fig, ax = plt.subplots()

ax.stem(x, y)

ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
       ylim=(0, 8), yticks=np.arange(1, 8))

plt.show()

 

import matplotlib.pyplot as plt
import numpy as np

# make data
x = np.arange(0, 10, 2)
ay = [1, 1.25, 2, 2.75, 3]
by = [1, 1, 1, 1, 1]
cy = [2, 1, 2, 1, 2]
y = np.vstack([ay, by, cy])

# plot
fig, ax = plt.subplots()

ax.stackplot(x, y)

ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
       ylim=(0, 8), yticks=np.arange(1, 8))

plt.show()

 

import pandas as pd
import matplotlib.pyplot as plt

# Assuming you have a list or array of 50 student heights in centimeters
heights = [160, 165, 170, 155, 175, 180, 162, 168, 172, 163, 166, 169, 176, 161, 164,
           158, 178, 173, 157, 171, 159, 167, 182, 174, 181, 177, 150, 183, 152, 179,
           185, 154, 187, 151, 184, 156, 153, 186, 189, 148, 190, 147, 188, 149, 146,
           191, 145, 144]

# Create a pandas DataFrame from the heights list
df = pd.DataFrame({'Heights (cm)': heights})

# Plot a histogram
plt.hist(df['Heights (cm)'], bins=10, edgecolor='black')
plt.title('Histogram of Student Heights')
plt.xlabel('Height (cm)')
plt.ylabel('Frequency')

# Show the plots
plt.show()





# Plot Box Plots
import pandas as p
import matplotlib.pyplot as plt
import seaborn as sns

df = p.read_csv('E:/Python Script/BMI_Chart.csv')
plt.figure(figsize=(8, 4))
sns.boxplot(data=df, palette='Set2')
plt.title('Box Plot of Columns Height, Weight, and BMI')

 

# Create a line plot using relplot
sns.relplot(x="total_bill", y="tip", kind="line", style = 'smoker', data=data)

# Set plot labels and title
plt.xlabel("Total Bill ($)")
plt.ylabel("Tip ($)")
plt.title("Line Plot of Total Bill vs. Tip")

# Show the plot
plt.show()

 

import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
data = sns.load_dataset("tips")

# Create an lmplot
sns.lmplot(x="total_bill", y="tip", data=data)

# Set plot labels and title
plt.xlabel("Total Bill ($)")
plt.ylabel("Tip ($)")
plt.title("Scatter Plot with Regression Line")

# Show the plot
plt.show()

 

import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
data = sns.load_dataset("tips")

# Create a stripplot
sns.stripplot(x="day", y="total_bill", data=data)

# Set plot labels and title
plt.xlabel("Day of the Week")
plt.ylabel("Total Bill ($)")
plt.title("Strip Plot of Total Bill by Day")

# Show the plot
plt.show()

 

 

import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
data = sns.load_dataset("tips")

# Create a histogram using histplot
plt.figure(figsize=(8, 4))
sns.histplot(data=data, x="total_bill", color="skyblue")
plt.xlabel("Total Bill ($)")
plt.ylabel("Frequency")
plt.title("Histogram without KDE")
plt.show()

 

 

import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
data = sns.load_dataset("tips")

# Create a KDE plot using kdeplot
plt.figure(figsize=(8, 4))
sns.kdeplot(data=data, x="total_bill", fill=True, color="salmon")
plt.xlabel("Total Bill ($)")
plt.ylabel("Density")
plt.title("KDE Plot")
plt.show()

 

 

import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
data = sns.load_dataset("tips")
# Create a rug plot using rugplot
plt.figure(figsize=(8, 1))
sns.rugplot(data=data, x="total_bill", height=0.5, color="purple")
plt.xlabel("Total Bill ($)")
plt.title("Rug Plot")
plt.show()

 

 

import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
data = sns.load_dataset("tips")

# Create a swarmplot
plt.figure(figsize=(8, 4))
sns.swarmplot(data=data, x="day", y="total_bill", palette="Set2")
plt.xlabel("Gender")
plt.ylabel("Total Bill ($)")
plt.title("Swarm Plot of Total Bill by Day")
plt.show()


import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
data = sns.load_dataset("tips")

# Create a violin plot
plt.figure(figsize=(8, 4))
sns.violinplot(data=data, x="day", y="total_bill", palette="Set2")
plt.xlabel("Day of the Week")
plt.ylabel("Total Bill ($)")
plt.title("Violin Plot of Total Bill by Day")
plt.show()

 

import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
data = sns.load_dataset("tips")

# Create a jointplot
sns.jointplot(data=data, x="total_bill", y="tip", kind="scatter")
plt.suptitle("Jointplot of Total Bill vs. Tip")
plt.show()

PYTHON- Reading and Writing with with Statement- JSON - BINARY

 Reading and Writing with with Statement:

You can use the with statement to automatically close the file when you're done with it. It's a recommended approach as it ensures that the file is properly closed even if an exception occurs.

Sample program using the with statement:

# Writing to a file using the with statement
with open("sample.txt", "w") as file:
    file.write("Hello, World!")

# Reading from a file using the with statement
with open("sample.txt", "r") as file:
    content = file.read()
    print(content)


Handling Binary Files:

You can open files in binary mode by specifying "b" in the mode string ("rb" for reading binary, "wb" for writing binary, etc.). This is useful for working with non-text files like images or executables.

Sample program for binary file handling:

# Reading a binary file
with open("image.jpg", "rb") as file:
    binary_data = file.read()

# Writing binary data to a file
with open("copy_image.jpg", "wb") as file:
    file.write(binary_data)

These are the fundamental operations for file handling in Python. Remember to handle exceptions, check if files exist before working with them, and close files properly to avoid data corruption and resource leaks.


Advanced File Handling Functions:
In addition to the basic file handling operations mentioned earlier, Python provides more advanced file handling functions and techniques that can help you work with files more efficiently and handle various scenarios. Here are some advanced file handling functions.

Reading and Writing CSV Files:


You can use the csv module to easily read and write CSV (Comma-Separated Values) files.

Sample program to read and write CSV files:

import csv
# Writing data to a CSV file
with open("Sample_csv.csv", "w", newline="") as csvfile:
    csv_writer = csv.writer(csvfile)
    csv_writer.writerow(["Name", "Age"])
    csv_writer.writerow(["Bhaskar", 34])
    csv_writer.writerow(["Vinoth", 34])
    csv_writer.writerow(["Senthil", 37])
    csv_writer.writerow(["Venkatesh", 34])

# Reading data from a CSV file
with open("data.csv", "r") as csvfile:
    csv_reader = csv.reader(csvfile)
    for row in csv_reader:
        print(row)


Working with JSON Files:

The json module allows you to work with JSON (JavaScript Object Notation) files.

Sample program to read and write JSON files:

import json

# Writing data to a JSON file
data = {"name": "Alice", "age": 30}
with open("data.json", "w") as jsonfile:
    json.dump(data, jsonfile)

# Reading data from a JSON file
with open("data.json", "r") as jsonfile:
    loaded_data = json.load(jsonfile)
    print(loaded_data)