Linux Crash Course

Day 1: Introduction to Linux

Topics:

  1. Linux operating system
    Explanation: Learn about the Linux operating system, its features, and its popularity among developers and system administrators.
  2. Basic Linux commands
    Explanation: Understand essential Linux commands such as ls (list files and directories), cd (change directory), pwd (print working directory), and mkdir (make directory).
  3. File and directory management
    Explanation: Learn how to create, delete, move, and rename files and directories using commands like touch, rm, mv, and cp.
  4. File permissions and ownership
    Explanation: Understand the concept of file permissions and how to set permissions using chmod, as well as changing file ownership using chown.
  5. File manipulation and text editing
    Explanation: Explore commands like cat (concatenate and display file contents), less (view file contents page by page), and nano (a basic text editor).

Assignments:

  1. Create a directory named “my_files” and navigate into it.
    Answer: mkdir my_files (to create the directory) and cd my_files (to navigate into it).
  2. Create a file named “my_text.txt” and write some text into it.
    Answer: touch my_text.txt (to create the file) and nano my_text.txt (to open the file in the nano text editor and write the text).
  3. List all the files and directories in the current directory.
    Answer: ls (to list files and directories).
  4. Rename the file “my_text.txt” to “new_text.txt”.
    Answer: mv my_text.txt new_text.txt (to rename the file).
  5. Delete the directory “my_files” and all its contents.
    Answer: rm -r my_files (to remove the directory and its contents).

Day 2: Working with Files and Permissions

Topics:

  1. File manipulation commands
    Explanation: Explore more file manipulation commands such as head (display the beginning of a file), tail (display the end of a file), and wc (word count).
  2. File permissions and access modes
    Explanation: Understand the three levels of file permissions (owner, group, others) and how to set permissions using symbolic notation (rwx) and numeric notation (777).
  3. Changing file ownership and group
    Explanation: Learn how to change the owner and group of a file using the chown and chgrp commands.
  4. File compression and archiving
    Explanation: Discover commands like tar (archive files) and gzip (compress files) to manage large file collections efficiently.
  5. File searching and filtering
    Explanation: Learn about commands like find (search for files and directories) and grep (search for text patterns in files).

Assignments:

  1. Create a file named “sample.txt” and write some content into it.
    Answer: touch sample.txt (to create the file) and nano sample.txt (to open the file in the nano text editor and write the content).
  2. Display the first 5 lines of the file “sample.txt”.
    Answer: head -n 5 sample.txt (to display the first 5 lines).
  3. Set the file permissions of “sample.txt” to read and write for the owner only.
    Answer: chmod 600 sample.txt (to set the permissions).
  4. Change the owner of “sample.txt

” to a different user.
Answer: chown username sample.txt (to change the owner to the specified username).

  1. Archive the file “sample.txt” and compress it into a single file.
    Answer: tar -czvf sample.tar.gz sample.txt (to create the archive and compress it).

Day 3: Introduction to Vim Editor

Topics:

  1. Introduction to Vim
    Explanation: Understand the basics of the Vim editor, including its modes (Normal, Insert, Visual), navigation, and command execution.
  2. Opening and saving files
    Explanation: Learn how to open files in Vim, make changes, and save them using commands like :e (open), :w (save), and :q (quit).
  3. Moving and navigating within files
    Explanation: Explore various movement commands like h (left), j (down), k (up), l (right), and using line numbers to jump to specific locations.
  4. Editing and modifying text
    Explanation: Understand text editing commands like i (insert), o (open a new line), x (delete a character), and yy (copy a line).
  5. Undo and redo operations
    Explanation: Learn how to undo and redo changes made in Vim using the u (undo) and Ctrl+R (redo) commands.

Assignments:

  1. Open the file “my_file.txt” in Vim and navigate to the end of the file.
    Answer: vim my_file.txt (to open the file) and G (to move to the end of the file).
  2. Insert a new line after the current line and write some text into it.
    Answer: Press o (to open a new line) and start typing the desired text.
  3. Delete the current line in Vim.
    Answer: Press dd (to delete the current line).
  4. Copy the current line in Vim and paste it below the current line.
    Answer: Press yy (to copy the current line) and then p (to paste it below).
  5. Save the changes made to the file and exit Vim.
    Answer: Press :wq (to save and quit).

Day 4: Advanced Vim Editing

Topics:

  1. Visual mode in Vim
    Explanation: Learn how to select and manipulate blocks of text using Visual mode, including commands like v (characterwise), V (linewise), and Ctrl+V (blockwise).
  2. Searching and replacing text
    Explanation: Discover how to search for specific text patterns using / (forward search) and ? (backward search), as well as replacing text using :s (substitute).
  3. Advanced editing commands
    Explanation: Explore advanced editing commands like x (delete a character), r (replace a character), J (join lines), and . (repeat the last command).
  4. Advanced movement and navigation
    Explanation: Learn advanced movement commands like w (jump to the beginning of the next word), b (jump to the beginning of the previous word), and gg (jump to the first line).
  5. Split windows and tabs in Vim
    Explanation: Understand how to split the Vim editor window vertically and horizontally using commands like :split and :vsplit, and navigate between tabs.

Assignments:

  1. Open the file “my_notes.txt” in Vim and search for the word “important”.
    Answer: vim my_notes.txt (to open the file) and /important (to search for the word “important”).
  2. Replace all occurrences of the word “old” with “new” in the current line.
    Answer: :s/old/new/ (to perform the substitution).
  3. Join the current line with the line below it.
    Answer: Press J (to join the lines).
  4. Split the Vim editor window vertically.
    Answer: :vsplit (to split the window vertically).
  5. Move the cursor to the beginning of the next word in Vim.
    Answer: Press w (to jump to the beginning of the next word).

Day 5: Vim Customization and Advanced Topics

Topics:

  1. Vim configuration files
    Explanation: Understand the .vimrc file and how to customize Vim settings, key mappings, and plugins.
  2. Customizing Vim colorschemes
    Explanation: Learn how to change the colorscheme in Vim to enhance the visual appearance and readability of your code.
  3. Advanced Vim features and plugins
    Explanation: Explore advanced Vim features like macros, multiple cursors (using plugins), and code completion (using plugins).
  4. Vim navigation shortcuts
    Explanation: Discover useful navigation shortcuts like Ctrl+U (scroll half a page up), Ctrl+D (scroll half a page down), and gg (jump to the first line).
  5. Vim documentation and help
    Explanation: Learn how to access Vim documentation and help resources, including built-in help pages and online resources.

Assignments:

  1. Customize the Vim settings by adding the following lines to your .vimrc file:
  • Set the tab width to 4 spaces.
  • Enable line numbers.
    Answer: Open the .vimrc file in Vim (vim ~/.vimrc) and add the desired configurations.
  1. Change the colorscheme in Vim to a different one.
    Answer: In Vim, type :colorscheme <colorscheme_name> to change the colorscheme.
  2. Create a macro in Vim that inserts a specific code snippet.
    Answer: Record the macro using q<register> and replay it using @<register>.
  3. Install a plugin in Vim for code completion or any other desired functionality.
    Answer: Install the desired plugin using a plugin manager like Vundle or Pathogen.
  4. Access the Vim built-in help and find information on a specific Vim command or feature.
    Answer: In Vim, type :help <command_or_feature> to access the built-in help pages.

Shell Scripting

Apologies for the oversight. Here are the shell scripting assignments along with sample answers for each day:

Day 1:

  1. Write a shell script that takes two numbers as input and prints their sum.
#!/bin/bash

echo "Enter the first number: "
read num1

echo "Enter the second number: "
read num2

sum=$((num1 + num2))
echo "The sum is: $sum"
  1. Create a shell script that reads a filename from the user and checks if it exists in the current directory. If the file exists, display a message confirming its existence; otherwise, display an error message.
#!/bin/bash

echo "Enter a filename: "
read filename

if [ -e "$filename" ]; then
    echo "The file '$filename' exists in the current directory."
else
    echo "Error: The file '$filename' does not exist in the current directory."
fi
  1. Write a shell script that reads a string from the user and prints it in reverse order.
#!/bin/bash

echo "Enter a string: "
read input_string

reversed_string=$(echo "$input_string" | rev)
echo "Reversed string: $reversed_string"
  1. Create a script that takes a directory name as input and lists all the files in that directory.
#!/bin/bash

echo "Enter a directory name: "
read directory

if [ -d "$directory" ]; then
    echo "Files in $directory:"
    ls "$directory"
else
    echo "Error: '$directory' is not a valid directory."
fi
  1. Write a shell script that generates a random number between 1 and 100 and asks the user to guess the number. Provide appropriate feedback based on the user’s guess.
#!/bin/bash

random_number=$((RANDOM % 100 + 1))

echo "Guess the number between 1 and 100: "
read user_guess

if [ "$user_guess" -eq "$random_number" ]; then
    echo "Congratulations! You guessed the correct number."
elif [ "$user_guess" -lt "$random_number" ]; then
    echo "Try again. The number is higher than your guess."
else
    echo "Try again. The number is lower than your guess."
fi

Day 2:

  1. Write a shell script that takes a filename as input and checks if it is a regular file or a directory.
#!/bin/bash

echo "Enter a filename: "
read filename

if [ -f "$filename" ]; then
    echo "'$filename' is a regular file."
elif [ -d "$filename" ]; then
    echo "'$filename' is a directory."
else
    echo "Error: '$filename' is neither a regular file nor a directory."
fi
  1. Create a script that takes a file containing a list of numbers and calculates their sum.
#!/bin/bash

sum=0
while read -r num; do
    sum=$((sum + num))
done < "$1"

echo "Sum of numbers in the file: $sum"
  1. Write a shell script that renames all files in a directory with a specific extension to have a prefix “backup_” followed by the original filename.
#!/bin/bash

echo "Enter the directory name: "
read directory

echo "Enter the file extension to rename: "
read ext

for file in "$directory"/*."$ext"; do
    filename=$(basename "$file")
    mv "$file" "$directory/backup_$filename"
done
  1. Create a script that reads a file and counts the number of lines, words, and characters in it.
#!/bin/bash

echo "Enter a filename: "
read filename

if [ -f "$filename" ]; then
    line_count=$(wc -l < "$filename")
    word_count=$(wc -w < "$filename")
    char_count=$(wc -c < "$filename")

    echo "Number of lines: $line_count"
    echo "Number of words: $word_count"
    echo "Number of characters: $char_count"
else
    echo "Error: '$filename' is not a valid file."
fi
  1. Write a shell script that takes a number as input and prints all the prime numbers less than or equal to that number.
#!/bin/bash

echo "Enter a number: "
read num

if [ "$num" -lt 2 ]; then
    echo "There are no prime numbers less than 2."
else
    echo "Prime numbers less than or equal to $num:"
    for ((i = 2; i <= num; i++)); do
        is_prime=1
        for ((j = 2; j <= i / 2; j++)); do
            if ((i % j == 0)); then
                is_prime=0
                break
            fi
        done
        if [ "$is_prime" -eq 1 ]; then
            echo "$i"
        fi
    done
fi

Day 3:

  1. Create a shell script that takes a directory name as input and finds all the subdirectories within it.
#!/bin/bash

echo "Enter a directory name: "
read directory

if [ -d "$directory" ]; then
    echo "Subdirectories in '$directory':"
    find "$directory" -type d
else
    echo "Error: '$directory' is not a valid directory."
fi
  1. Write a script that reads a file and removes all the empty lines from it.
#!/bin/bash

echo "Enter a filename: "
read filename

if [ -f "$filename" ]; then
    sed -i '/^[[:space:]]*$/d' "$filename"
    echo "Empty lines removed from '$filename'."
else
    echo "Error: '$filename' is not a valid file."
fi
  1. Create a shell script that takes a string as input and checks if it is a palindrome.
#!/bin/bash

echo "Enter a string: "
read input_string

reverse_string=$(echo "$input_string" | rev)

if [ "$input_string" = "$reverse_string" ]; then
    echo "The string is a palindrome."
else
    echo "The string is not a palindrome."
fi
  1. Write a shell script that reads a number as input and checks if it is even or odd.
#!/bin/bash

echo "Enter a number: "
read num

if ((num % 2 == 0)); then
    echo "$num is an even number."
else
    echo "$num is an odd number."
fi
  1. Create a shell script that prints the current date and time.
#!/bin/bash

current_date=$(date +"%Y-%m-%d")
current_time=$(date +"%H:%M:%S")

echo "Current date: $current_date"
echo "Current time: $current_time"

Day 4:

  1. Write a shell script that takes a directory name as input and deletes all the files in that directory with a “.tmp” extension.
#!/bin/bash

echo "Enter a directory name: "
read directory

if [ -d "$directory" ]; then
    find "$directory" -type f -name "*.tmp" -delete
    echo "All '.tmp' files in '$directory' deleted."
else
    echo "Error: '$directory' is not a valid directory."
fi
  1. Create a script that reads a file and replaces all occurrences of a word with another word.
#!/bin/bash

echo "Enter a filename: "
read filename

if [ -f "$filename" ]; then
    echo "Enter the word to replace: "
    read old_word

    echo "Enter the new word: "
    read new_word

    sed -i "s/$old_word/$new_word/g" "$filename"
    echo "Occurrences of '$old_word' replaced with '$new_word' in '$filename'."
else
    echo "Error: '$filename' is not a valid file."
fi
  1. Write a shell script that reads a number as input and checks if it is prime.
#!/bin/bash

echo "Enter a number: "
read num

if [ "$num" -lt 2 ]; then
    echo "The number must be greater than or equal to 2 to check for primality."
else
    is_prime=1
    for ((i = 2; i <= num / 2; i++)); do
        if ((num % i == 0)); then
            is_prime=0
            break
        fi
    done

    if [ "$is_prime" -eq 1 ]; then
        echo "$num is a prime number."
    else
        echo "$num is not a prime number."
    fi
fi
  1. Create a shell script that takes a directory name as input and counts the number of files and subdirectories in it.
#!/bin/bash

echo "Enter a directory name: "
read directory

if [ -d "$directory" ]; then
    file_count=$(find "$directory" -type f | wc -l)
    dir_count=$(find "$directory" -type d | wc -l)

    echo "Number of files: $file_count"
    echo "Number of subdirectories: $dir_count"
else
    echo "Error: '$directory' is not a valid directory."
fi
  1. Write a shell script that reads a string as input and converts it to uppercase.
#!/bin/bash

echo "Enter a string: "
read input_string

upper_case_string=$(echo "$input_string" | tr '[:lower:]' '[:upper:]')

echo "Uppercase string: $upper_case_string"

Day 5:

  1. Create a shell script that takes two numbers as input and swaps their values.
#!/bin/bash

echo "Enter the first number: "
read num1

echo "Enter the second number: "
read num2

echo "Before swapping: num1 = $num1, num2 = $num2"

# Swapping using a temporary variable
temp=$num1
num1=$num2
num2=$temp

echo "After swapping: num1 = $num1, num2 = $num2"
  1. Write a script that takes a file and sorts its lines in ascending order.
#!/bin/bash

echo "Enter a filename: "
read filename

if [ -f "$filename" ]; then
    sort "$filename" > sorted_"$filename"
    echo "Lines in '$filename' sorted in ascending order and saved to 'sorted_$filename'."
else
    echo "Error: '$filename' is not a valid file."
fi
  1. Create a shell script that reads a directory name as input and prints the names of the 10 largest files in it.
#!/bin/bash

echo "Enter a directory name: "
read directory

if [ -d "$directory" ]; then
    echo "The 10 largest files in '$directory':"
    du -ah "$directory" | sort -rh | head -n 10
else
    echo "Error: '$directory' is not a valid directory."
fi
  1. Write a shell script that takes a list of filenames as arguments and checks if all of them exist in the current directory.
#!/bin/bash

for filename in "$@"; do
    if [ ! -e "$filename" ]; then
        echo "Error: '$filename' does not exist in the current directory."
    else
        echo "'$filename' exists in the current directory."
    fi
done
  1. Create a shell script that calculates the factorial of a given number.
#!/bin/bash

echo "Enter a number: "
read num

factorial=1

for ((i = 1; i <= num; i++)); do
    factorial=$((factorial * i))
done

echo "Factorial of $num is: $factorial"

mysql crash course

Day 1: Basic SQL Queries

Topics:

  1. Introduction to SQL and relational databases
  2. Creating a database and tables
  3. Inserting data into tables
  4. Retrieving data with SELECT statement
  5. Filtering and sorting data

Assignments:

  1. Create a database named “mydb”.
   CREATE DATABASE mydb;
  1. Create a table named “users” with columns id, name, age, city, added_at, and updated_at.
   CREATE TABLE users (
     id INT PRIMARY KEY,
     name VARCHAR(50),
     age INT,
     city VARCHAR(50),
     added_at DATETIME,
     updated_at DATETIME
   );
  1. Insert 5 records into the “users” table.
   INSERT INTO users (id, name, age, city, added_at, updated_at)
   VALUES
     (1, 'John', 25, 'Mumbai', '2022-01-01', '2022-01-02'),
     (2, 'Jane', 30, 'Delhi', '2022-01-03', '2022-01-04'),
     (3, 'Mike', 35, 'Bangalore', '2022-01-05', '2022-01-06'),
     (4, 'Lisa', 28, 'Chennai', '2022-01-07', '2022-01-08'),
     (5, 'David', 32, 'Kolkata', '2022-01-09', '2022-01-10');
  1. Retrieve all records from the “users” table.
   SELECT * FROM users;
  1. Retrieve the names of users whose age is greater than 30.
   SELECT name FROM users WHERE age > 30;

Day 2: Data Manipulation

Topics:

  1. Updating records with UPDATE statement
  2. Deleting records with DELETE statement
  3. Limiting and pagination with LIMIT and OFFSET
  4. Aggregation functions: COUNT, SUM, AVG, MIN, MAX
  5. Grouping data with GROUP BY

Assignments:

  1. Update the age of the user with id 2 to 35.
   UPDATE users SET age = 35 WHERE id = 2;
  1. Delete the user with id 4 from the “users” table.
   DELETE FROM users WHERE id = 4;
  1. Retrieve the first 3 records from the “users” table.
   SELECT * FROM users LIMIT 3;
  1. Retrieve the total number of users in the “users” table.
   SELECT COUNT(*) FROM users;
  1. Retrieve the average age of users.
   SELECT AVG(age) FROM users;

Day 3: Filtering and Sorting

Topics:

  1. Using WHERE clause for conditional filtering
  2. Using comparison operators: =, <>, <, >, <=, >=
  3. Using logical operators: AND, OR, NOT
  4. Sorting data with ORDER BY clause
  5. Sorting in ascending and descending order

Assignments:

  1. Retrieve the names of users whose city is ‘Mumbai’.
 SELECT name FROM users WHERE city = 'Mumbai';
  1. Retrieve the names of users whose age is between 25 and 35.
   SELECT name FROM users WHERE age BETWEEN 25 AND 35;
  1. Retrieve the names of users whose city is not ‘Delhi’.
   SELECT name FROM users WHERE city <> 'Delhi';
  1. Retrieve all records from the “users” table sorted by age in ascending order.
   SELECT * FROM users ORDER BY age ASC;
  1. Retrieve all records from the “users” table sorted by name in descending order.
   SELECT * FROM users ORDER BY name DESC;

Day 4: Data Aggregation and Functions

Topics:

  1. Using aggregate functions: COUNT, SUM, AVG, MIN, MAX
  2. Working with NULL values: IS NULL, IS NOT NULL
  3. Using mathematical functions: ROUND, CEILING, FLOOR
  4. String functions: CONCAT, UPPER, LOWER, LENGTH
  5. Date functions: NOW, DATE_FORMAT, DATE_ADD, DATE_SUB

Assignments:

  1. Retrieve the total number of users in the “users” table.
   SELECT COUNT(*) FROM users;
  1. Retrieve the sum of ages of all users.
   SELECT SUM(age) FROM users;
  1. Retrieve the average age of users excluding NULL values.
   SELECT AVG(age) FROM users WHERE age IS NOT NULL;
  1. Retrieve the concatenated names and cities of all users.
   SELECT CONCAT(name, ', ', city) AS info FROM users;
  1. Retrieve the current date and time.
   SELECT NOW();

Day 5: Grouping and Filtering with HAVING Clause

Topics:

  1. Grouping data with GROUP BY clause
  2. Filtering grouped data with HAVING clause
  3. Using aggregate functions with GROUP BY
  4. Using multiple columns in GROUP BY
  5. Combining GROUP BY, HAVING, and ORDER BY

Assignments:

  1. Retrieve the names and ages of users grouped by city.
   SELECT city, GROUP_CONCAT(name) AS names, GROUP_CONCAT(age) AS ages FROM users GROUP BY city;
  1. Retrieve the cities with more than 2 users.
   SELECT city FROM users GROUP BY city HAVING COUNT(*) > 2;
  1. Retrieve the average age of users in each city.
   SELECT city, AVG(age) AS average_age FROM users GROUP BY city;
  1. Retrieve the cities with the highest and lowest average age of users.
   SELECT city, AVG(age) AS average_age FROM users GROUP BY city HAVING AVG(age) = (SELECT MAX(avg_age) FROM (SELECT AVG(age) AS avg_age FROM users GROUP BY city) AS temp) OR AVG(age) = (SELECT MIN(avg_age) FROM (SELECT AVG(age) AS avg_age FROM users GROUP BY city) AS temp);
  1. Retrieve the cities with at least 1 user whose age is greater than 30, sorted by city name.
   SELECT city FROM users WHERE age > 30 GROUP BY city ORDER BY city ASC;

HTML Crash Course

Day 1: Introduction to HTML

Topics:

  1. HTML syntax and structure
  2. HTML tags and elements
  3. Headings, paragraphs, and line breaks
  4. Text formatting with HTML
  5. Creating lists in HTML

Assignments:

  1. Create a basic HTML document structure with a title and heading.
<!DOCTYPE html>
<html>
<head>
    <title>My First Webpage</title>
</head>
<body>
    <h1>Welcome to My Webpage</h1>
</body>
</html>
  1. Write a paragraph describing your favorite hobby using appropriate HTML tags.
<!DOCTYPE html>
<html>
<head>
    <title>My Hobbies</title>
</head>
<body>
    <h2>My Favorite Hobby</h2>
    <p>I enjoy playing the guitar in my free time. It's a great way to relax and express my creativity.</p>
</body>
</html>
  1. Create an ordered list of your top 5 favorite movies.
<!DOCTYPE html>
<html>
<head>
    <title>My Favorite Movies</title>
</head>
<body>
    <h2>My Top 5 Favorite Movies</h2>
    <ol>
        <li>The Shawshank Redemption</li>
        <li>The Godfather</li>
        <li>Pulp Fiction</li>
        <li>The Dark Knight</li>
        <li>Fight Club</li>
    </ol>
</body>
</html>
  1. Format a piece of text as bold, italic, and underline using HTML tags.
<!DOCTYPE html>
<html>
<head>
    <title>Formatted Text</title>
</head>
<body>
    <p>This is <b>bold</b> text.</p>
    <p>This is <i>italic</i> text.</p>
    <p>This is <u>underlined</u> text.</p>
</body>
</html>
  1. Construct an unordered list of your favorite food items.
<!DOCTYPE html>
<html>
<head>
    <title>My Favorite Foods</title>
</head>
<body>
    <h2>My Favorite Foods</h2>
    <ul>
        <li>Pizza</li>
        <li>Sushi</li>
        <li>Burger</li>
        <li>Chocolate</li>
        <li>Ice Cream</li>
    </ul>
</body>
</html>

Day 2: Working with Links and Images

Topics:

  1. Creating hyperlinks with anchor tags
  2. Linking to external websites and internal sections
  3. Inserting images in HTML
  4. Image attributes and alternative text

Assignments:

  1. Create a hyperlink that opens a new tab and leads to your favorite website.
<!DOCTYPE html>
<html>
<head>
    <title>My Webpage</title>
</head>
<body>
    <h1>Welcome to My Webpage</h1>
    <a href="https://www.example.com" target="_blank">Visit Example.com</a>
</body>
</html>
  1. Link an internal section within the same webpage using anchor tags.
<!DOCTYPE html>
<html>
<head>
    <title>My Webpage</title>
</head>
<body>
    <h1>Welcome to My Webpage</h1>
    <a href="#about">Jump to About Section</a>
    <h2 id="about">About</h2>


    <p>This is the About section of my webpage.</p>
</body>
</html>
  1. Insert an image of your favorite animal with appropriate alt text.
<!DOCTYPE html>
<html>
<head>
    <title>My Webpage</title>
</head>
<body>
    <h1>Welcome to My Webpage</h1>
    <img src="animal.jpg" alt="A picture of my favorite animal">
</body>
</html>
  1. Create a gallery of three images using HTML and appropriate attributes.
<!DOCTYPE html>
<html>
<head>
    <title>Image Gallery</title>
</head>
<body>
    <h2>Image Gallery</h2>
    <img src="image1.jpg" alt="Image 1">
    <img src="image2.jpg" alt="Image 2">
    <img src="image3.jpg" alt="Image 3">
</body>
</html>
  1. Add a link around an image that opens another webpage when clicked.
<!DOCTYPE html>
<html>
<head>
    <title>My Webpage</title>
</head>
<body>
    <h1>Welcome to My Webpage</h1>
    <a href="https://www.example.com" target="_blank">
        <img src="image.jpg" alt="Image">
    </a>
</body>
</html>

Day 3: Tables and Forms

Topics:

  1. Creating tables in HTML
  2. Table rows and cells
  3. Table headers and data
  4. Form elements and input types
  5. Form submission and handling

Assignments:

  1. Create a table to display a simple schedule with days of the week and corresponding activities.
<!DOCTYPE html>
<html>
<head>
    <title>Weekly Schedule</title>
</head>
<body>
    <h2>Weekly Schedule</h2>
    <table>
        <tr>
            <th>Day</th>
            <th>Activity</th>
        </tr>
        <tr>
            <td>Monday</td>
            <td>Gym</td>
        </tr>
        <tr>
            <td>Tuesday</td>
            <td>Work</td>
        </tr>
        <tr>
            <td>Wednesday</td>
            <td>Music Lessons</td>
        </tr>
        <tr>
            <td>Thursday</td>
            <td>Study Group</td>
        </tr>
        <tr>
            <td>Friday</td>
            <td>Movie Night</td>
        </tr>
    </table>
</body>
</html>
  1. Create a form with input fields for name, email, and message, and a submit button.
<!DOCTYPE html>
<html>
<head>
    <title>Contact Form</title>
</head>
<body>
    <h2>Contact Form</h2>
    <form action="submit.php" method="POST">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br><br>
        <label for="message">Message:</label>
        <textarea id="message" name="message" required></textarea><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Day 4: CSS Styling

Topics:

  1. CSS syntax and selectors
  2. Applying styles to HTML elements
  3. Working with colors, backgrounds, and borders
  4. Formatting text with CSS
  5. Creating layouts with CSS

Assignments:

  1. Style the headings in your webpage using CSS.
<!DOCTYPE html>
<html>
<head>
    <title>My Webpage</title>
    <style>
        h1 {
            color: blue;
            font-size: 24px;
        }
        h2 {
            color: green;
            font-size: 20px;
        }
    </style>
</head>
<body>
    <h1>Welcome to My Webpage</h1>
    <h2>About Me</h2>
    <!-- Rest of the content -->
</body>
</html>
  1. Add a background color and padding to the paragraphs in your webpage using CSS.
<!DOCTYPE html>
<html>
<head>
    <title>My Webpage</title>
    <style>
        p {
            background-color: lightgray;
            padding: 10px;
        }
    </style>
</head>
<body>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
    <!-- Rest of the content -->
</body>
</html>
  1. Create a navigation bar using an unordered list and style it with CSS.
html
<!DOCTYPE html>
<html>
<head>
    <title>My Webpage</title>
    <style>
        ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
            background-color: #333;
        }
        li {
            display: inline-block;
            margin-right: 10px;
        }
        a {
            color: white;
            text-decoration: none;
            padding: 10px;
        }
    </style>
</head>
<body>
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
</body>
</html>

Day 5: JavaScript Basics

Topics:

  1. Introduction to JavaScript
  2. Variables and data types
  3. Operators and expressions
  4. Control flow statements (if-else, switch)
  5. Functions and event handling

Assignments:

  1. Create a JavaScript function that calculates the sum of two numbers and displays the result.
<!DOCTYPE html>
<html>
<head>
    <title>Calculator</title>
    <script>
        function calculateSum() {
            var num1 = parseInt(document.getElementById('num1').value);
            var num2 = parseInt(document.getElementById('num2').value);
            var sum = num1 + num2;
            document.getElementById('result').innerHTML = "Sum: " + sum;
        }
    </script>
</head>
<body>
    <h2>Calculator</h2>
    <input type="number" id="num1" placeholder="Enter number 1"><br><br>
    <input type="number" id="num2" placeholder="Enter number 2"><br><br>
    <button onclick="calculateSum()">Calculate Sum</button>
    <p id="result"></p>
</body>
</html>
  1. Create a JavaScript function that validates a form and displays an error message if any field is empty.
<!DOCTYPE html>
<html>
<head>
    <title>Form Validation</title>
    <script>
        function validateForm() {
            var name = document.getElementById('name').value;
            var email = document.getElementById('email').value;
            var message = document.getElementById('message').value;

            if (name === "" || email === "" || message === "") {
                alert("All fields are required!");
                return false;
            }
        }
    </script>
</head>
<body>
    <h2>Contact Form</h2>
    <form action="submit.php" method="POST" onsubmit="return validateForm()">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name"><br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email"><br><br>
        <label for="message">Message:</label>
        <textarea id="message" name="message"></textarea><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Basics of Computer

Day 1: Introduction to Computers and Operating Systems

  • Topics:
  • Basic computer components and peripherals
  • Operating system fundamentals
  • Assignments:
  1. Identify and label the major components of your computer system.
  2. Explore the features and functionality of your operating system.
  3. Customize your desktop background and screensaver.

Day 2: File Management and Organization

  • Topics:
  • Creating, copying, moving, and deleting files and folders
  • Organizing files and folders
  • Assignments:
  1. Create a new folder on your desktop and name it “Assignments.”
  2. Copy files from one folder to another.
  3. Delete unnecessary files and empty your recycle bin or trash folder.

Day 3: Internet Basics and Web Browsing

  • Topics:
  • Internet fundamentals
  • Web browser usage and navigation
  • Assignments:
  1. Open a web browser and visit three different websites of your choice.
  2. Bookmark your favorite website for quick access.
  3. Perform a simple web search to find information on a topic of interest.

Day 4: Email Communication and Online Safety

  • Topics:
  • Email account setup and management
  • Online safety and security best practices
  • Assignments:
  1. Create a new email account with a service provider of your choice.
  2. Compose and send an email to a friend or family member.
  3. Update your email account settings to enable spam filtering and two-factor authentication.

Day 5: Online Search and Information Evaluation

  • Topics:
  • Effective online searching techniques
  • Evaluating the reliability and credibility of online information
  • Assignments:
  1. Perform an advanced search using search operators to find specific information.
  2. Evaluate the credibility of a website by examining its domain, author, and references.
  3. Create a list of reliable online sources for future reference.

Day 6: Online Communication and Social Media

  • Topics:
  • Instant messaging and video calling
  • Social media platforms and their features
  • Assignments:
  1. Install a messaging app and send a message to a friend or family member.
  2. Set up a video call with someone using a communication tool like Skype or FaceTime.
  3. Create a profile on a social media platform and explore its features, such as posting and commenting.

Day 7: Online Privacy and Security

  • Topics:
  • Protecting personal information online
  • Recognizing and avoiding online scams
  • Assignments:
  1. Review the privacy settings of your social media accounts and adjust them to your comfort level.
  2. Learn about common online scams and how to identify and avoid them.
  3. Install and run antivirus software to ensure your computer’s security.

Day 8: Online Shopping and Financial Transactions

  • Topics:
  • E-commerce websites and online shopping
  • Online payment methods and security
  • Assignments:
  1. Browse an e-commerce website and add items to your cart to simulate online shopping.
  2. Research different online payment methods and understand their security measures.
  3. Create a budget using a spreadsheet application to track your expenses.

Day 9: Online Entertainment and Multimedia

  • Topics:
  • Streaming services and media players
  • Digital photo and video management
  • Assignments:
  1. Explore a streaming service and watch a movie or TV show of your choice.
  2. Install a media player on your computer and play your favorite songs or videos.
  3. Organize your digital photos into folders and create a slideshow using a photo management application.

Day 10: Online Learning and Productivity Tools

  • Topics:
  • Online learning platforms and resources
  • Productivity tools for personal and professional use
  • Assignments:
  1. Enroll in an online course or explore educational resources on a learning platform.
  2. Use a productivity tool like Google Docs or Microsoft Office Online to create a document or presentation.
  3. Research and install a task management application to organize your daily activities and to-do lists.

Assignment

Day 1: Introduction to Computers and Operating Systems

  1. Explain the main components of a computer system and their functions.
  2. Describe the difference between hardware and software.
  3. Discuss the purpose and features of an operating system.
  4. Identify three popular operating systems used today.
  5. Explain the importance of keeping your operating system and software updated.

Day 2: File Management and Organization with Google Drive

  1. Create a new folder in your Google Drive and name it “Assignments.”
  2. Upload a file to your Google Drive.
  3. Move a file from one folder to another in Google Drive.
  4. Share a file or folder with a friend and specify their access level (view, comment, or edit).
  5. Discuss the benefits of cloud storage and how Google Drive can help with file organization and accessibility.

Day 3: Internet Basics and Web Browsing

  1. Explain the purpose of a web browser and name three popular web browsers.
  2. Perform a search on Google and find information about a topic of interest.
  3. Bookmark a website that you frequently visit and organize it into a bookmark folder.
  4. Clear your browsing history and cookies in your web browser.
  5. Discuss the importance of internet safety, such as avoiding suspicious websites and protecting personal information.

Day 4: Email Communication and Google Drive Integration

  1. Create a new Gmail account and send an email to a friend.
  2. Attach a file from your Google Drive to an email.
  3. Save an email attachment to your Google Drive.
  4. Organize your Gmail inbox using labels and filters.
  5. Discuss the benefits of using Google Drive for file sharing and collaboration in email communication.

Day 5: Online Search and Information Evaluation

  1. Perform an advanced search on Google using specific search operators or filters.
  2. Evaluate the credibility of a website by examining the source, author, and references.
  3. Compare search results and information from different search engines.
  4. Discuss the importance of fact-checking and critically analyzing online information.
  5. Use Google Scholar to find scholarly articles on a specific topic.

Day 6: Online Communication and Collaboration Tools

  1. Create a Google Docs document and share it with a collaborator to work on together.
  2. Use the comment feature in Google Docs to provide feedback or suggestions.
  3. Start a video call using Google Meet and invite others to join.
  4. Collaborate on a Google Sheets spreadsheet with a teammate in real-time.
  5. Discuss the advantages of online communication and collaboration tools for remote work or group projects.

Day 7: Online Privacy and Security

  1. Review and adjust your Google account privacy settings.
  2. Enable two-factor authentication for your Google account.
  3. Identify and avoid common online scams, such as phishing emails or fake websites.
  4. Create a strong, unique password for your Google account.
  5. Discuss best practices for online privacy, such as using secure connections and being cautious with personal information.

Day 8: Google Slides and Presentations

  1. Create a new presentation using Google Slides.
  2. Customize the theme and layout of your slides.
  3. Add text, images, and shapes to your presentation.
  4. Apply transitions and animations to enhance your presentation.
  5. Share your presentation with others and allow them to comment or edit.

Day 9: Google Forms and Surveys

  1. Create a survey or questionnaire using Google Forms.
  2. Add different types of questions to your form, such as multiple choice or short answer.
  3. Customize the design and layout of your form.
  4. Share your form with others and collect responses.
  5. Analyze the survey results and generate visualizations using Google Sheets.

Day 10: Google Drive Organization and Productivity Tips

  1. Create a folder structure in your Google Drive to organize your files and documents.
  2. Use the Google Drive search feature to quickly find specific files or folders.
  3. Set up offline access to your Google Drive for accessing files without an internet connection.
  4. Explore additional productivity features in Google Drive, such as Google Keep for note-taking or Google Calendar for scheduling.
  5. Discuss how Google Drive can enhance your personal and professional productivity.

7 Day Assignment

Day 1: Introduction to Computers and Internet

  1. Write a short essay on the importance of computers in our daily lives.
  2. Create a diagram illustrating the basic components of a computer system.
  3. Research and list five popular websites and explain their purposes.
  4. Compare and contrast different types of computer operating systems.
  5. Write step-by-step instructions on how to connect to a Wi-Fi network.
  6. Explore different types of computer input devices and their functions.
  7. Create a presentation on the evolution of computers over time.
  8. Research and explain the concept of computer viruses and methods to protect against them.
  9. Write a report on the impact of technology on society and ethical considerations.
  10. Explore different internet browsers and document their key features and differences.

Day 2: Computer Software and Applications

  1. Install a software program of your choice and document the installation process.
  2. Explore different types of software applications (e.g., word processing, spreadsheet, image editing) and their uses.
  3. Customize the settings of your operating system to personalize your computer experience.
  4. Research and describe the concept of cloud computing and its advantages.
  5. Write a step-by-step tutorial on how to perform a specific task using a software application.
  6. Investigate different programming languages and their applications in software development.
  7. Create a presentation comparing proprietary software and open-source software.
  8. Research and explain the concept of software updates and the importance of keeping software up-to-date.
  9. Write a report on the role of artificial intelligence in software development.
  10. Explore different productivity tools and discuss their benefits in improving efficiency.

Day 3: Internet and Web Browsers

  1. Research and explain the purpose of domain names and how they are registered.
  2. Compare and evaluate different web browsers based on speed, security, and user interface.
  3. Clear browser cache and cookies and explain their importance.
  4. Research and describe the different types of internet connections available.
  5. Write a report on internet protocols (e.g., HTTP, TCP/IP) and their roles in web communication.
  6. Explore different search engines and compare their search algorithms.
  7. Identify and analyze common online scams and how to avoid them.
  8. Research and explain the concept of phishing attacks and how to recognize them.
  9. Create a checklist for evaluating the credibility of websites and online sources.
  10. Write a blog post on internet privacy and strategies to protect personal information online.

Day 4: Online Safety and Security

  1. Research and explain the concept of encryption and its importance in securing online communications.
  2. Create a strong and unique password for your online accounts and explain password security best practices.
  3. Research and compare different antivirus software programs and their features.
  4. Write a report on social engineering techniques and how to defend against them.
  5. Create a YouTube account and upload a short video introducing yourself.
  6. Explore YouTube’s privacy settings and customize them according to your preferences.
  7. Research copyright laws related to YouTube content and create a video discussing fair use guidelines.
  8. Comment on five different YouTube videos, expressing your opinions and engaging with the content creators.
  9. Create a YouTube playlist of your favorite videos on a specific topic or theme.
  10. Write a reflective essay on the impact of YouTube on media consumption and online entertainment.

Day 5: Basics of Google Drive and Cloud Storage

  1. Create a Google Drive account and explore its features and storage options.
  2. Upload a document to Google Drive and share it with a friend or colleague.
  3. Create a folder structure in Google Drive to organize your files and documents.
  4. Collaborate with others on a shared document using Google Docs
  5. Explore Google Drive’s integration with other Google apps like Google Sheets and Google Slides.
  6. Research and compare different cloud storage services, highlighting their features and pricing plans.
  7. Backup important files from your computer to Google Drive and explain the importance of data backup.
  8. Create a Google Form and use it to collect responses or conduct a survey.
  9. Explore Google Drive’s advanced search features to quickly find specific files or documents.
  10. Write a blog post comparing Google Drive to other cloud storage services and their advantages.

Day 6: Email and Communication Tools

  1. Set up an email account with a provider of your choice and configure it in an email client.
  2. Compose and send an email to a friend or family member, including attachments.
  3. Explore the features of your email client, such as organizing emails into folders and applying filters.
  4. Research and compare different email providers, highlighting their storage limits and security features.
  5. Create a professional email signature that includes your name, contact information, and any relevant links.
  6. Use a communication tool like Slack or Microsoft Teams to join a workspace and interact with others.
  7. Research and explain the concept of email etiquette and best practices for professional communication.
  8. Set up email forwarding or auto-responder for your email account and explain their purposes.
  9. Participate in an online discussion forum or community and share your thoughts on a topic of interest.
  10. Write a reflection on the benefits and challenges of online communication tools in modern society.

Day 7: Introduction to Social Media and Online Presence

  1. Create accounts on popular social media platforms like Facebook, Twitter, and Instagram.
  2. Customize your social media profiles with a profile picture, cover photo, and bio information.
  3. Post a status update on each social media platform, sharing your thoughts or an interesting article.
  4. Research and discuss the impact of social media on personal relationships and society.
  5. Explore privacy settings on social media platforms and adjust them according to your preferences.
  6. Follow influencers or organizations in your field of interest on social media and engage with their content.
  7. Create a blog on a free blogging platform and write your first blog post on a topic of your choice.
  8. Share your blog post on social media and engage with readers through comments and discussions.
  9. Explore social media analytics tools to track the performance of your posts and engagement metrics.
  10. Write a reflection on the benefits and drawbacks of social media and its influence on online culture.

PHP Crash Course

Basics

  • Example 1: Printing “Hello, World!” using echo:
   echo "Hello, World!";
  • Example 2: Assigning and displaying variables:
   $name = "John Doe";
   echo "My name is " . $name;
  • Example 3: Writing comments in PHP code:
   // This is a single-line comment

   /*
   This is a
   multi-line comment
   */
  • Example 4: Using the print statement:
   print "Welcome to PHP";
  • Example 5: Getting the current date and time:
   $currentDate = date("Y-m-d H:i:s");
   echo "Current date and time: " . $currentDate;

Variables and Constants

  • Example 1: Declaring and using variables:
   $name = "John Doe";
   $age = 25;
   $salary = 5000.50;

   echo "Name: " . $name . ", Age: " . $age . ", Salary: $" . $salary;
  • Example 2: Defining and using constants:
   define("PI", 3.14);
   echo "The value of PI is: " . PI;
  • Example 3: Variable scope (local and global):
   $globalVariable = "I am a global variable";

   function myFunction() {
       $localVariable = "I am a local variable";
       echo $localVariable;
       echo $GLOBALS['globalVariable'];
   }

   myFunction();
  • Example 4: Variable interpolation:
   $name = "John Doe";
   echo "My name is $name";
  • Example 5: Constants case sensitivity:
   define("MY_CONSTANT", "Hello");
   echo MY_CONSTANT;
   echo my_constant;

Operators

  • Example 1: Arithmetic operators:
   $num1 = 10;
   $num2 = 5;

   echo $num1 + $num2; // Addition
   echo $num1 - $num2; // Subtraction
   echo $num1 * $num2; // Multiplication
   echo $num1 / $num2; // Division
   echo $num1 % $num2; // Modulo
  • Example 2: Assignment operators:
   $num = 10;
   $num += 5; // Equivalent to $num = $num + 5;
   echo $num;

   $str = "Hello";
   $str .= " World"; // Equivalent to $str = $str . " World";
   echo $str;
  • Example 3: Comparison operators:
   $num1 = 10;
   $num2 = 5;

   var_dump($num1 == $num2);  // Equal to
   var_dump($num1 != $num2);  // Not equal to
   var_dump($num1 > $num2);   // Greater than
   var_dump($num1 < $num2);   // Less than
   var_dump($num1 >= $num2);  // Greater than or equal to
   var_dump($num1 <= $num

2);  // Less than or equal to
  • Example 4: Logical operators:
   $num1 = 10;
   $num2 = 5;
   $num3 = 7;

   var_dump($num1 > $num2 && $num1 < $num3);   // Logical AND
   var_dump($num1 > $num2 || $num1 > $num3);   // Logical OR
   var_dump(!($num1 > $num2));                  // Logical NOT
  • Example 5: String operators:
   $str1 = "Hello";
   $str2 = "World";

   echo $str1 . $str2;   // Concatenation
   echo $str1 .= $str2;  // Concatenation and assignment

Conditionals

  • Example 1: If-else statement:
   $num = 10;

   if ($num > 0) {
       echo "The number is positive";
   } else {
       echo "The number is not positive";
   }
  • Example 2: Switch case statement:
   $day = "Monday";

   switch ($day) {
       case "Monday":
           echo "Today is Monday";
           break;
       case "Tuesday":
           echo "Today is Tuesday";
           break;
       default:
           echo "Today is not Monday or Tuesday";
   }
  • Example 3: Ternary operator:
   $num = 10;

   $result = ($num % 2 == 0) ? "Even" : "Odd";
   echo $result;
  • Example 4: Multiple conditions in if statement:
   $num = 10;

   if ($num > 0 && $num < 20) {
       echo "The number is between 0 and 20";
   }
  • Example 5: Nested if-else statements:
   $num = 10;

   if ($num > 0) {
       if ($num < 20) {
           echo "The number is between 0 and 20";
       }
   }

Loop Constructs

  • Example 1: For loop:
   for ($i = 1; $i <= 5; $i++) {
       echo $i . " ";
   }
  • Example 2: While loop:
   $i = 1;

   while ($i <= 5) {
       echo $i . " ";
       $i++;
   }
  • Example 3: Do-while loop:
   $i = 1;

   do {
       echo $i . " ";
       $i++;
   } while ($i <= 5);
  • Example 4: Foreach loop with an array:
   $numbers = [1, 2, 3, 4, 5];

   foreach ($numbers as $number) {
       echo $number . " ";
   }
  • Example 5: Loop control statements (break and continue):
   for ($i = 1; $i <= 10; $i++) {
       if ($i == 5) {
           break;      // Exit the loop
       }

       if ($i % 2 == 0) {
           continue;   // Skip the rest of the iteration


 }

       echo $i . " ";
   }

Arrays

  • Example 1: Creating an indexed array:
   $fruits = ["Apple", "Banana", "Orange"];
  • Example 2: Accessing array elements:
   $fruits = ["Apple", "Banana", "Orange"];
   echo $fruits[0];  // Output: Apple
  • Example 3: Modifying array elements:
   $fruits = ["Apple", "Banana", "Orange"];
   $fruits[1] = "Mango";
  • Example 4: Counting array elements:
   $fruits = ["Apple", "Banana", "Orange"];
   $count = count($fruits);
   echo $count;  // Output: 3
  • Example 5: Searching for a value in an array:
   $fruits = ["Apple", "Banana", "Orange"];
   $index = array_search("Banana", $fruits);
   echo $index;  // Output: 1

Multi-Dimensional Arrays

  • Example 1: Creating a 2D array:
   $matrix = [
       [1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]
   ];
  • Example 2: Accessing elements in a 2D array:
   $matrix = [
       [1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]
   ];

   echo $matrix[1][2];  // Output: 6
  • Example 3: Modifying elements in a 2D array:
   $matrix = [
       [1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]
   ];

   $matrix[2][1] = 10;
  • Example 4: Counting elements in a 2D array:
   $matrix = [
       [1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]
   ];

   $count = count($matrix, COUNT_RECURSIVE);
   echo $count;  // Output: 9
  • Example 5: Searching for a value in a 2D array:
   $matrix = [
       [1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]
   ];

   $index = array_search(6, array_merge(...$matrix));
   echo $index;  // Output: 5

Associative Arrays

  • Example 1: Creating an associative array:
   $student = [
       "name" => "John Doe",
       "age" => 20,
       "city" => "New York"
   ];
  • Example 2: Accessing values in an associative array:
   $student = [
       "name" => "John Doe",
       "age" => 20,
       "city" => "New York"
   ];

   echo $student["name"]; 

 // Output: John Doe
  • Example 3: Modifying values in an associative array:
   $student = [
       "name" => "John Doe",
       "age" => 20,
       "city" => "New York"
   ];

   $student["age"] = 21;
  • Example 4: Counting elements in an associative array:
   $student = [
       "name" => "John Doe",
       "age" => 20,
       "city" => "New York"
   ];

   $count = count($student);
   echo $count;  // Output: 3
  • Example 5: Checking if a key exists in an associative array:
   $student = [
       "name" => "John Doe",
       "age" => 20,
       "city" => "New York"
   ];

   $exists = array_key_exists("age", $student);
   echo $exists;  // Output: 1 (true)

Array of Associative Arrays

  • Example 1: Creating an array of associative arrays:
   $students = [
       [
           "name" => "John Doe",
           "age" => 20,
           "city" => "New York"
       ],
       [
           "name" => "Jane Smith",
           "age" => 22,
           "city" => "Los Angeles"
       ],
       [
           "name" => "Mike Johnson",
           "age" => 19,
           "city" => "Chicago"
       ]
   ];
  • Example 2: Accessing values in an array of associative arrays:
   $students = [
       [
           "name" => "John Doe",
           "age" => 20,
           "city" => "New York"
       ],
       [
           "name" => "Jane Smith",
           "age" => 22,
           "city" => "Los Angeles"
       ],
       [
           "name" => "Mike Johnson",
           "age" => 19,
           "city" => "Chicago"
       ]
   ];

   echo $students[1]["name"];  // Output: Jane Smith
  • Example 3: Modifying values in an array of associative arrays:
   $students = [
       [
           "name" => "John Doe",
           "age" => 20,
           "city" => "New York"
       ],
       [
           "name" => "Jane Smith",
           "age" => 22,
           "city" => "Los Angeles"
       ],
       [
           "name" => "Mike Johnson",
           "age" => 19,
           "city" => "Chicago"
       ]
   ];

   $students[2]["age"] = 20;
  • Example 4: Counting elements in an array of associative arrays:
   $students = [
       [
           "name" => "John Doe",
           "age" => 20,
           "city" => "New York"
       ],
       [
           "name" => "Jane Smith",
           "age" => 22,
           "city" => "Los Angeles"
       ],
       [
           "name" => "Mike Johnson",
           "age" => 19,
           "city" => "Chicago"
       ]
   ];

   $count = count($students);
   echo $count;  // Output: 3
  • Example 5: Searching for a value in an array of associative arrays:
   $students = [
       [
           "name" => "John Doe",
           "age" => 20,
           "city" => "New York"
       ],
       [
           "name" => "Jane Smith",
           "age" => 22,
           "city" => "Los Angeles"
       ],
       [
           "name" => "Mike Johnson",
           "age" => 19,
           "city" => "Chicago"
       ]
   ];

   $index = array_search("Los Angeles", array_column($students, "city"));
   echo $index;  // Output: 1

Functions

  • Example 1: Creating a function:
   function sayHello() {
       echo "Hello, World!";
   }

   sayHello();
  • Example 2: Function with parameters:
   function greet($name) {
       echo "Hello, " . $name . "!";
   }

   greet("John");
  • Example 3: Returning a value from a function:
   function add($num1, $num2) {
       return $num1 + $num2;
   }

   $result = add(3, 5);
   echo $result;  // Output: 8
  • Example 4: Function with default parameter value:
   function greet($name = "Guest") {
       echo "Hello, " . $name . "!";
   }

   greet();       // Output: Hello, Guest!
   greet("John"); // Output: Hello, John!
  • Example 5: Recursive function:
   function factorial($num) {
       if ($num <= 1) {
           return 1;
       }

       return $num * factorial($num - 1);
   }

   $result = factorial(5);
   echo $result;  // Output: 120

Classes

  • Example 1: Creating a class:
   class Person {
       public $name;
       public $age;

       public function sayHello() {
           echo "Hello, my name is " . $this->name . " and I am " . $this->age . " years old.";
       }
   }

   $person = new Person();
   $person->name = "John";
   $person->age = 25;
   $person->sayHello();
  • Example 2: Constructors and property accessors:
   class Person {
       private $name;
       private $age;

       public function __construct($name, $age) {
           $this->name = $name;
           $this->age = $age;
       }

       public function getName() {
           return $this->name;
       }

       public function getAge() {
           return $this->age;
       }
   }

   $person = new Person("John", 25);
   echo $person->getName();  // Output: John
   echo $person->getAge();   // Output: 25
  • Example 3: Inheritance:
   class Animal {
       public function makeSound() {
           echo "The animal makes a sound.";
       }
   }

   class Dog extends Animal {
       public function makeSound() {
           echo "The dog barks.";
       }
   }

   $dog = new Dog();
   $dog->makeSound();  // Output: The dog barks.
  • Example

4: Static properties and methods:

   class MathUtils {
       public static $pi = 3.14159;

       public static function square($num) {
           return $num * $num;
       }
   }

   echo MathUtils::$pi;            // Output: 3.14159
   echo MathUtils::square(5);      // Output: 25
  • Example 5: Abstract classes and interfaces:
   abstract class Animal {
       abstract public function makeSound();
   }

   interface CanFly {
       public function fly();
   }

   class Bird extends Animal implements CanFly {
       public function makeSound() {
           echo "The bird chirps.";
       }

       public function fly() {
           echo "The bird is flying.";
       }
   }

   $bird = new Bird();
   $bird->makeSound();  // Output: The bird chirps.
   $bird->fly();        // Output: The bird is flying.

File Handling

  • Example 1: Reading from a file:
   $file = fopen("data.txt", "r");
   while (!feof($file)) {
       $line = fgets($file);
       echo $line;
   }
   fclose($file);
  • Example 2: Writing to a file:
   $file = fopen("data.txt", "w");
   fwrite($file, "Hello, World!");
   fclose($file);
  • Example 3: Appending to a file:
   $file = fopen("data.txt", "a");
   fwrite($file, "New content");
   fclose($file);
  • Example 4: Checking if a file exists:
   if (file_exists("data.txt")) {
       echo "File exists.";
   } else {
       echo "File does not exist.";
   }
  • Example 5: Deleting a file:
   unlink("data.txt");

Database Connection (MySQL)

  1. Connecting to the database:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
  1. Selecting all users from the “users” table:
try {
    $stmt = $conn->query("SELECT * FROM users");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($users as $user) {
        echo "ID: " . $user['id'] . " - Name: " . $user['name'] . " - Age: " . $user['age'] . " - City: " . $user['city'] . " - Salary: " . $user['salary'] . "<br>";
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
  1. Deleting a user from the “users” table:
try {
    $id = 1;

    $stmt = $conn->prepare("DELETE FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();

    echo "User deleted successfully";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
  1. Adding a new user to the “users” table:
try {
    $name = "John Doe";
    $age = 25;
    $city = "New York";
    $salary = 5000;

    $stmt = $conn->prepare("INSERT INTO users (name, age, city, salary) VALUES (:name, :age, :city, :salary)");
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':age', $age);
    $stmt->bindParam(':city', $city);
    $stmt->bindParam(':salary', $salary);
    $stmt->execute();

    echo "New user added successfully";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}
  1. Fetching a single user from the “users” table:
try {
    $id = 1;

    $stmt = $conn->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();

    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        echo "ID: " . $user['id'] . " - Name: " . $user['name'] . " - Age: " . $user['age'] . " - City: " . $user['city'] . " - Salary: " . $user['salary'];
    } else {
        echo "User not found";
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

Remember to replace “your_username”, “your_password”, and “your_database” with your actual MySQL credentials and database name. Additionally, ensure that PDO extension is enabled in your PHP configuration.

Go Lang Crash Course

Basics of Go

  • Variables and Constants:
package main

import "fmt"

func main() {
    var message string = "Hello, Go!"
    fmt.Println(message)

    const pi = 3.14159
    fmt.Println(pi)
}
  • Data Types and Type Conversion:
package main

import "fmt"

func main() {
    var age int = 25
    fmt.Println(age)

    var price float64 = 9.99
    fmt.Println(price)

    var isTrue bool = true
    fmt.Println(isTrue)

    var name string = "John"
    fmt.Println(name)

    // Type conversion
    var num int = 42
    var result float64 = float64(num)
    fmt.Println(result)
}

Operators

package main

import "fmt"

func main() {
    var a = 10
    var b = 5

    fmt.Println(a + b)
    fmt.Println(a - b)
    fmt.Println(a * b)
    fmt.Println(a / b)
    fmt.Println(a % b)

    var isTrue = true
    fmt.Println(!isTrue)
}

Control Structures: if-else and switch:

package main

import "fmt"

func main() {
    var num = 5

    if num > 0 {
        fmt.Println("Number is positive")
    } else if num < 0 {
        fmt.Println("Number is negative")
    } else {
        fmt.Println("Number is zero")
    }

    var day = "Monday"

    switch day {
    case "Monday":
        fmt.Println("It's Monday")
    case "Tuesday":
        fmt.Println("It's Tuesday")
    default:
        fmt.Println("It's another day")
    }
}

Loops: for and range

package main

import "fmt"

func main() {
    // For loop
    for i := 1; i <= 5; i++ {
        fmt.Println(i)
    }

    // Range loop
    nums := []int{1, 2, 3, 4, 5}
    for index, value := range nums {
        fmt.Println(index, value)
    }
}

Functions in Go

  • Simple Function:
package main

import "fmt"

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

func main() {
    result := add(3, 5)
    fmt.Println(result)
}
  • Function with Multiple Return Values:
package main

import "fmt"

func divide(a, b int) (int, int) {
    quotient := a / b
    remainder := a % b
    return quotient, remainder
}

func main() {
    q, r := divide(10, 3)
    fmt.Println("Quotient:", q)
    fmt.Println("Remainder:", r)
}
  • Variadic Function:
package main

import "fmt"

func sum(numbers ...int) int {
    total := 0
    for _, num := range numbers {
        total += num
    }
    return total
}

func main() {
    result := sum(1, 2, 3, 4, 5)
    fmt.Println(result)
}
  • Anonymous Functions and Closures:
package main

import "fmt"

func main() {
    add := func(a, b int) int {
        return a + b


 }

    result := add(3, 5)
    fmt.Println(result)
}
  • Recursion:
package main

import "fmt"

func factorial(n int) int {
    if n == 0 {
        return 1
    }
    return n * factorial(n-1)
}

func main() {
    result := factorial(5)
    fmt.Println(result)
}

Arrays, Slices, and Maps in Go

  • Arrays:
package main

import "fmt"

func main() {
    var numbers [5]int
    numbers[0] = 1
    numbers[1] = 2
    numbers[2] = 3
    numbers[3] = 4
    numbers[4] = 5
    fmt.Println(numbers)

    var matrix [3][3]int
    matrix[0] = [3]int{1, 2, 3}
    matrix[1] = [3]int{4, 5, 6}
    matrix[2] = [3]int{7, 8, 9}
    fmt.Println(matrix)
}
  • Slices:
package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    fmt.Println(numbers)

    fmt.Println(numbers[1:4]) // Slicing a slice

    numbers = append(numbers, 6) // Appending an element
    fmt.Println(numbers)

    numbers = append(numbers[:2], numbers[3:]...) // Removing an element
    fmt.Println(numbers)
}
  • Maps:
package main

import "fmt"

func main() {
    person := map[string]string{
        "name":  "John",
        "age":   "30",
        "email": "john@example.com",
    }
    fmt.Println(person)

    fmt.Println(person["name"])

    person["city"] = "New York" // Adding a new key-value pair
    fmt.Println(person)

    delete(person, "age") // Removing a key-value pair
    fmt.Println(person)
}
  • Iterating over Slices and Maps:
package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    for index, value := range numbers {
        fmt.Println(index, value)
    }

    person := map[string]string{
        "name":  "John",
        "age":   "30",
        "email": "john@example.com",
    }
    for key, value := range person {
        fmt.Println(key, ":", value)
    }
}

Structs and Methods in Go

  • Structs:
package main

import "fmt"

type Person struct {
    name    string
    age     int
    address string
}

func main() {
    person := Person{"John", 30, "New York"}
    fmt.Println(person)

    fmt.Println(person.name)
    fmt.Println(person.age)
    fmt.Println(person.address)
}
  • Methods:
package main

import "fmt"

type Rectangle struct {
    width  float64
    height float64
}

func (r Rectangle) area() float64 {
    return r.width * r.height
}

func main() {
    rect := Rectangle{3.0, 4.0}
    fmt.Println(rect.area())
}

Packages and Error Handling in Go

  • Packages:
package main

import (
    "fmt"
    "math"
)

func main() {
    fmt.Println(math

.Sqrt(16))
}
  • Error Handling with error Type:
package main

import (
    "fmt"
    "math"
)

func calculateSqrt(num float64) (float64, error) {
    if num < 0 {
        return 0, fmt.Errorf("Cannot calculate square root of a negative number")
    }
    return math.Sqrt(num), nil
}

func main() {
    result, err := calculateSqrt(-9)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(result)
    }
}
  • Custom Error Types:
package main

import (
    "fmt"
    "math"
)

type NegativeNumberError struct {
    number float64
}

func (e NegativeNumberError) Error() string {
    return fmt.Sprintf("Cannot calculate square root of a negative number: %f", e.number)
}

func calculateSqrt(num float64) (float64, error) {
    if num < 0 {
        return 0, NegativeNumberError{num}
    }
    return math.Sqrt(num), nil
}

func main() {
    result, err := calculateSqrt(-9)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(result)
    }
}

Database Connection

  1. Installing and Importing Dependencies:
package main

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)
  1. Establishing a Database Connection:
func main() {
    // Database connection parameters
    db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/database_name")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // Check if the connection is successful
    err = db.Ping()
    if err != nil {
        panic(err)
    }

    fmt.Println("Connected to the database!")
}
  1. Creating the “users” Table:
func main() {
    db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/database_name")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    createTableQuery := `
        CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(50) NOT NULL,
            age INT,
            city VARCHAR(50),
            salary FLOAT,
            added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        );
    `

    _, err = db.Exec(createTableQuery)
    if err != nil {
        panic(err)
    }

    fmt.Println("Table 'users' created successfully!")
}
  1. Inserting Data into the “users” Table:
func main() {
    db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/database_name")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    insertQuery := `
        INSERT INTO users (name, age, city, salary)
        VALUES (?, ?, ?, ?);
    `

    result, err := db.Exec(insertQuery, "John Doe", 30, "New York", 5000.0)
    if err != nil {
        panic(err)
    }

    lastInsertID, err := result.LastInsertId()
    if err != nil {
        panic(err)
    }

    fmt.Println("Inserted record ID:", lastInsertID)
}
  1. Querying Data from the “users” Table:
func main() {
    db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/database_name")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    selectQuery := `
        SELECT id, name, age, city, salary, added_at, updated_at
        FROM users;
    `

    rows, err := db.Query(selectQuery)
    if err != nil {
        panic(err)
    }
    defer rows.Close()

    for rows.Next() {
        var id int
        var name string
        var age int
        var city string
        var salary float64
        var addedAt string
        var updatedAt string

        err := rows.Scan(&id, &name, &age, &city, &salary, &addedAt, &updatedAt)
        if err != nil {
            panic(err)
        }

        fmt.Println("ID:", id)
        fmt.Println("Name:", name)
        fmt.Println("Age:", age)
        fmt.Println("City:", city)
        fmt.Println("Salary:", salary)
        fmt.Println("Added At:", addedAt)
        fmt

.Println("Updated At:", updatedAt)
        fmt.Println()
    }
}

Go and Gin Framework

  1. Retrieving All Users:
func main() {
    router := gin.Default()

    // ...

    router.GET("/users", func(c *gin.Context) {
        selectQuery := `
            SELECT id, name, age, city, salary, added_at, updated_at
            FROM users;
        `

        rows, err := db.Query(selectQuery)
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }
        defer rows.Close()

        users := []gin.H{}
        for rows.Next() {
            var id int
            var name string
            var age int
            var city string
            var salary float64
            var addedAt string
            var updatedAt string

            err := rows.Scan(&id, &name, &age, &city, &salary, &addedAt, &updatedAt)
            if err != nil {
                c.JSON(500, gin.H{"error": err.Error()})
                return
            }

            user := gin.H{
                "id":        id,
                "name":      name,
                "age":       age,
                "city":      city,
                "salary":    salary,
                "added_at":  addedAt,
                "updated_at": updatedAt,
            }

            users = append(users, user)
        }

        c.JSON(200, users)
    })

    // ...

    router.Run(":8080")
}
  1. Deleting a User:
func main() {
    router := gin.Default()

    // ...

    router.DELETE("/users/:id", func(c *gin.Context) {
        id := c.Param("id")

        deleteQuery := `
            DELETE FROM users
            WHERE id = ?;
        `

        result, err := db.Exec(deleteQuery, id)
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        rowsAffected, err := result.RowsAffected()
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        if rowsAffected == 0 {
            c.JSON(404, gin.H{"message": fmt.Sprintf("User with ID %s not found", id)})
        } else {
            c.JSON(200, gin.H{"message": fmt.Sprintf("User with ID %s deleted", id)})
        }
    })

    // ...

    router.Run(":8080")
}
  1. Adding a New User:
func main() {
    router := gin.Default()

    // ...

    router.POST("/users", func(c *gin.Context) {
        var user struct {
            Name   string  `json:"name"`
            Age    int     `json:"age"`
            City   string  `json:"city"`
            Salary float64 `json:"salary"`
        }

        if err := c.ShouldBindJSON(&user); err != nil {
            c.JSON(400, gin.H{"error": err.Error()})
            return
        }

        insertQuery := `
            INSERT INTO users (name, age, city, salary)
            VALUES (?, ?, ?, ?);
        `

        result, err := db.Exec(insertQuery, user.Name, user.Age, user.City, user.Salary)
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        lastInsertID, err := result.LastInsertId()
        if err != nil {
            c

.JSON(500, gin.H{"error": err.Error()})
            return
        }

        c.JSON(201, gin.H{"message": fmt.Sprintf("User created with ID %d", lastInsertID)})
    })

    // ...

    router.Run(":8080")
}
  1. Fetching a Single User:
func main() {
    router := gin.Default()

    // ...

    router.GET("/users/:id", func(c *gin.Context) {
        id := c.Param("id")

        selectQuery := `
            SELECT id, name, age, city, salary, added_at, updated_at
            FROM users
            WHERE id = ?;
        `

        row := db.QueryRow(selectQuery, id)

        var user struct {
            ID        int     `json:"id"`
            Name      string  `json:"name"`
            Age       int     `json:"age"`
            City      string  `json:"city"`
            Salary    float64 `json:"salary"`
            AddedAt   string  `json:"added_at"`
            UpdatedAt string  `json:"updated_at"`
        }

        err := row.Scan(&user.ID, &user.Name, &user.Age, &user.City, &user.Salary, &user.AddedAt, &user.UpdatedAt)
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        c.JSON(200, user)
    })

    // ...

    router.Run(":8080")
}
  1. Updating an Existing User:
func main() {
    router := gin.Default()

    // ...

    router.PUT("/users/:id", func(c *gin.Context) {
        id := c.Param("id")

        var user struct {
            Name   string  `json:"name"`
            Age    int     `json:"age"`
            City   string  `json:"city"`
            Salary float64 `json:"salary"`
        }

        if err := c.ShouldBindJSON(&user); err != nil {
            c.JSON(400, gin.H{"error": err.Error()})
            return
        }

        updateQuery := `
            UPDATE users
            SET name = ?, age = ?, city = ?, salary = ?
            WHERE id = ?;
        `

        result, err := db.Exec(updateQuery, user.Name, user.Age, user.City, user.Salary, id)
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        rowsAffected, err := result.RowsAffected()
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }

        if rowsAffected == 0 {
            c.JSON(404, gin.H{"message": fmt.Sprintf("User with ID %s not found", id)})
        } else {
            c.JSON(200, gin.H{"message": fmt.Sprintf("User with ID %s updated", id)})
        }
    })

    // ...

    router.Run(":8080")
}

Please make sure to replace "username", "password", and "database_name" with your actual MySQL database credentials and database name.

Python Crash Course

Certainly! Here are ten examples for each of the topics you mentioned:

BASICS

  1. Basics:
    Example 1: Printing a message
   print("Hello, World!")

Example 2: Arithmetic operations

   a = 10
   b = 5
   print("Addition:", a + b)
   print("Subtraction:", a - b)
   print("Multiplication:", a * b)
   print("Division:", a / b)
   print("Modulo:", a % b)

Example 3: String concatenation

   name = "Alice"
   age = 25
   print("My name is " + name + " and I am " + str(age) + " years old.")

Example 4: Using the input function

   name = input("Enter your name: ")
   print("Hello, " + name + "!")

Example 5: Conditional statements

   num = int(input("Enter a number: "))
   if num > 0:
       print("The number is positive.")
   elif num < 0:
       print("The number is negative.")
   else:
       print("The number is zero.")

Example 6: Working with loops (for loop)

   for i in range(5):
       print(i)

Example 7: Working with loops (while loop)

   count = 0
   while count < 5:
       print(count)
       count += 1

Example 8: Using the len() function

   text = "Hello, World!"
   print("Length:", len(text))

Example 9: Using the str() function

   num = 42
   text = "The answer is: " + str(num)
   print(text)

Example 10: Importing and using modules

   import math

   radius = 5
   area = math.pi * radius ** 2
   print("Area of the circle:", area)

CONDITIONAL STATEMENTS IF ELSE

  1. If-Else Statements:
    Example 1: Checking if a number is even or odd
   num = int(input("Enter a number: "))
   if num % 2 == 0:
       print("The number is even.")
   else:
       print("The number is odd.")

Example 2: Checking if a year is a leap year

   year = int(input("Enter a year: "))
   if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
       print("The year is a leap year.")
   else:
       print("The year is not a leap year.")

Example 3: Determining the maximum of three numbers

   num1 = float(input("Enter the first number: "))
   num2 = float(input("Enter the second number: "))
   num3 = float(input("Enter the third number: "))
   max_num = max(num1, num2, num3)
   print("The maximum number is:", max_num)

Example 4: Checking if a student passed or failed

   score = float(input("Enter the student's score: "))
   if score >= 60:
       print("The student passed.")
   else:
       print("The student failed.")

Example 5

: Categorizing a number into different ranges

   num = float(input("Enter a number: "))
   if num < 0:
       print("The number is negative.")
   elif num >= 0 and num <= 10:
       print("The number is between 0 and 10.")
   elif num > 10 and num <= 20:
       print("The number is between 10 and 20.")
   else:
       print("The number is greater than 20.")

Example 6: Checking if a person is eligible to vote

   age = int(input("Enter your age: "))
   if age >= 18:
       print("You are eligible to vote.")
   else:
       print("You are not eligible to vote yet.")

Example 7: Checking if a number is positive, negative, or zero (alternative approach)

   num = float(input("Enter a number: "))
   if num > 0:
       print("The number is positive.")
   elif num < 0:
       print("The number is negative.")
   else:
       print("The number is zero.")

Example 8: Checking if a character is a vowel or consonant

   char = input("Enter a character: ").lower()
   if char in ['a', 'e', 'i', 'o', 'u']:
       print("The character is a vowel.")
   else:
       print("The character is a consonant.")

Example 9: Checking if a number is a multiple of another number

   num1 = int(input("Enter the first number: "))
   num2 = int(input("Enter the second number: "))
   if num1 % num2 == 0:
       print(num1, "is a multiple of", num2)
   else:
       print(num1, "is not a multiple of", num2)

Example 10: Checking if a year is a leap year (alternative approach)

   year = int(input("Enter a year: "))
   if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
       print("The year is a leap year.")
   else:
       print("The year is not a leap year.")

For loop with range

  1. Printing numbers from 0 to 9:
for i in range(10):
    print(i)
  1. Printing even numbers from 2 to 10:
for i in range(2, 11, 2):
    print(i)
  1. Calculating the sum of numbers from 1 to 100:
total = 0
for i in range(1, 101):
    total += i
print("Sum:", total)
  1. Printing numbers in reverse order from 9 to 0:
for i in range(9, -1, -1):
    print(i)
  1. Multiplying each number in the range by 2 and printing the result:
for i in range(10):
    result = i * 2
    print(result)
  1. Printing the square of each number in the range from 1 to 5:
for i in range(1, 6):
    square = i ** 2
    print(square)
  1. Printing numbers in increments of 5 from 0 to 50:
for i in range(0, 51, 5):
    print(i)
  1. Checking if a number is divisible by 3 in the range from 1 to 20:
for i in range(1, 21):
    if i % 3 == 0:
        print(i, "is divisible by 3")
  1. Printing the ASCII value of each character in a string:
text = "Hello"
for char in text:
    ascii_value = ord(char)
    print(char, ":", ascii_value)
  1. Repeating a specific action a certain number of times using range:
for _ in range(5):
    print("Hello, world!")

LIST

  1. List:
    Example 1: Accessing list elements
   fruits = ["apple", "banana", "orange", "grape", "mango"]
   print(fruits[0])  # "apple"
   print(fruits[2])  # "orange"

Example 2: Modifying list elements

   numbers = [1, 2, 3, 4, 5]
   numbers[2] = 10
   print(numbers)  # [1, 2, 10, 4, 5]

Example 3: Appending elements to a list

   numbers = [1, 2, 3]
   numbers.append(4)
   print(numbers)  # [1, 2, 3, 4]

Example 4: Removing elements from a list

   fruits = ["apple", "banana", "orange", "grape"]
   fruits.remove("banana")
   print(fruits)  # ["apple", "orange", "grape"]

Example 5: Slicing a list

   numbers = [1, 2, 3, 4, 5]
   print(numbers[1:4])  # [2, 3, 4]

Example 6: Checking if an element exists in a list

   fruits = ["apple", "banana", "orange", "grape"]
   if "banana" in fruits:
       print("Banana is in the list.")

Example 7: Counting occurrences of an element in a list

   numbers = [1, 2, 3, 1, 2, 1, 4, 1]
   count = numbers.count(1)
   print("Number of occurrences:", count)

Example 8: Sorting a list

   numbers = [5, 3, 1, 4, 2]
   numbers.sort()
   print(numbers)  # [1, 2, 3, 4, 5]

Example 9: Reversing a list

   fruits = ["apple", "banana", "orange", "grape"]
   fruits.reverse()
   print(fruits)  # ["grape", "orange", "banana", "apple"]

Example 10: Combining two lists

   list1 = [1, 2, 3]
   list2 = [4, 5, 6]
   combined_list = list1 + list2
   print(combined_list)  # [1, 2, 3, 4, 5, 6]

DICTIONARY

  1. Example 1: Accessing dictionary values
   student = {"name": "Alice", "age": 20, "grade": "A"}
   print(student["name"])  # "Alice"
   print(student["age"])   # 20

Example 2: Adding new key-value pairs to a dictionary

   student = {"name": "Alice", "age": 20}
   student["grade"] = "A"
   print(student)  # {"name": "Alice", "age": 20, "grade": "A"}

Example 3: Modifying dictionary values

   student = {"name": "Alice", "age": 20, "grade": "A"}
   student["age"] = 21
   print(student)  # {"name": "Alice", "age": 21, "grade": "A"}

Example 4: Checking if a key exists in a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   if "age" in student:
       print("Age:", student["age"])  # Age: 20

Example 5: Removing a key-value pair from a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   del student["grade"]
   print(student)  # {"name": "Alice", "age": 20}

Example 6: Getting all keys from a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   keys = student.keys()
   print(keys)  # ["name", "age", "grade"]

Example 7: Getting all values from a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   values = student.values()
   print(values)  # ["Alice", 20, "A"]

Example 8: Checking the length of a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   length = len(student)
   print("Length:", length)  # Length: 3

Example 9: Clearing a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   student.clear()
   print(student)  # {}

Example 10: Copying a dictionary

   student = {"name": "Alice", "age": 20, "grade": "A"}
   student_copy = student.copy()
   print(student_copy)  # {"name": "Alice", "age": 20, "grade": "A"}

LIST OF DICTIONARIES

employees = [
    {"name": "John", "age": 32, "department": "HR", "salary": 50000},
    {"name": "Emily", "age": 28, "department": "IT", "salary": 60000},
    {"name": "Michael", "age": 35, "department": "Finance", "salary": 70000},
    {"name": "Sophia", "age": 29, "department": "Sales", "salary": 55000},
    {"name": "Daniel", "age": 31, "department": "IT", "salary": 62000},
    {"name": "Olivia", "age": 27, "department": "HR", "salary": 48000},
    {"name": "William", "age": 33, "department": "Finance", "salary": 75000},
    {"name": "Ava", "age": 30, "department": "Sales", "salary": 58000},
    {"name": "James", "age": 34, "department": "IT", "salary": 65000},
    {"name": "Emma", "age": 26, "department": "HR", "salary": 52000}
]

Now, let’s provide 10 examples using the same list of employees:

  1. Accessing values in the list:
print(employees[0]["name"])     # Output: "John"
print(employees[3]["age"])      # Output: 29
  1. Modifying a value in the list:
employees[2]["salary"] = 72000
print(employees[2])             # Output: {'name': 'Michael', 'age': 35, 'department': 'Finance', 'salary': 72000}
  1. Adding a new key-value pair to a dictionary:
employees[1]["position"] = "Senior Software Engineer"
print(employees[1])             # Output: {'name': 'Emily', 'age': 28, 'department': 'IT', 'salary': 60000, 'position': 'Senior Software Engineer'}
  1. Removing a key-value pair from a dictionary:
del employees[4]["age"]
print(employees[4])             # Output: {'name': 'Daniel', 'department': 'IT', 'salary': 62000}
  1. Counting the number of dictionaries in the list:
count = len(employees)
print("Number of employees:", count)   # Output: Number of employees: 10
  1. Calculating the average age of all employees:
total_salary = 0
num_employees = len(employees)

for employee in employees:
    total_salary += employee["salary"]

average_salary = total_salary / num_employees

print("Average salary:", average_salary)
  1. Finding the employee with the highest salary:
max_salary = 0
employee_with_max_salary = None

for employee in employees:
    if employee["salary"] > max_salary:
        max_salary = employee["salary"]
        employee_with_max_salary = employee

print("Employee with the highest salary:")
print("Name:", employee_with_max_salary["name"])
print("Salary:", employee_with_max_salary["salary"])
  1. Finding all employees having highest salary:
max_salary = 0
employees_with_max_salary = []

for employee in employees:
    if employee["salary"] > max_salary:
        max_salary = employee["salary"]
        employees_with_max_salary = [employee]
    elif employee["salary"] == max_salary:
        employees_with_max_salary.append(employee)

print("Employees with the highest salary:")
for employee in employees_with_max_salary:
    print("Name:", employee["name"])
    print("Salary:", employee["salary"])
    print()
  1. Calculating total, average, highest and lowest salaries all employees:
total_salary = 0
highest_salary = float("-inf")
lowest_salary = float("inf")

for employee in employees:
    salary = employee["salary"]
    total_salary += salary

    if salary > highest_salary:
        highest_salary = salary

    if salary < lowest_salary:
        lowest_salary = salary

average_salary = total_salary / len(employees)

print("Total Salary:", total_salary)
print("Highest Salary:", highest_salary)
print("Lowest Salary:", lowest_salary)
print("Average Salary:", average_salary)
  1. Print all employees using PrettyTable:
# Print all employees
all_employees_table = PrettyTable(["Name", "Department", "Salary"])
for employee in employees:
    all_employees_table.add_row([employee["name"], employee["department"], employee["salary"]])
all_employees_table.title = "All Employees"
print(all_employees_table)

Mini Project

Print department wise highest salaried employees

Expected output