<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Ankit]]></title><description><![CDATA[Ankit]]></description><link>https://piankit.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 12 Nov 2026 10:03:31 GMT</lastBuildDate><atom:link href="https://piankit.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Arduino Height Measurement System]]></title><description><![CDATA[The Arduino-based Height Measurement System uses an ultrasonic sensor to measure the distance between the sensor and a person's head. The sensor is mounted…]]></description><link>https://piankit.hashnode.dev/hcsr04</link><guid isPermaLink="true">https://piankit.hashnode.dev/hcsr04</guid><dc:creator><![CDATA[Ankit Chapagain]]></dc:creator><pubDate>Tue, 03 Nov 2026 16:59:55 GMT</pubDate><content:encoded><![CDATA[<h1></h1>
<h2>1. Project Overview</h2>
<p>The Arduino-based Height Measurement System uses an ultrasonic sensor to measure the distance between the sensor and a person's head.</p>
<p>The sensor is mounted at a fixed height, facing downward. When a person stands beneath it, the system measures the distance from the sensor to the person's head.</p>
<p>Python calculates the person's height using the following formula:</p>
<p><strong>Person's Height = Sensor Mounting Height − Measured Distance</strong></p>
<h3>Technologies Used</h3>
<ul>
<li>Arduino UNO</li>
<li>HC-SR04 Ultrasonic Sensor</li>
<li>Arduino IDE</li>
<li>Python</li>
<li>Flask</li>
<li>PySerial</li>
<li>HTML, CSS and JavaScript</li>
</ul>
<h3>System Architecture</h3>
<pre><code class="language-text">       HC-SR04 Sensor
              |
              v
          Arduino UNO
              |
              v
     USB Serial Communication
              |
              v
       Python Flask Server
              |
              v
       Height Calculation
              |
              v
        Web Dashboard
              |
              v
       Display Height (cm)
</code></pre>
<hr />
<h2>2. Hardware Requirements</h2>
<table>
<thead>
<tr>
<th>Component</th>
<th align="right">Quantity</th>
</tr>
</thead>
<tbody><tr>
<td>Arduino UNO</td>
<td align="right">1</td>
</tr>
<tr>
<td>HC-SR04 Ultrasonic Sensor</td>
<td align="right">1</td>
</tr>
<tr>
<td>Jumper Wires</td>
<td align="right">4</td>
</tr>
<tr>
<td>USB Cable</td>
<td align="right">1</td>
</tr>
<tr>
<td>Computer/Laptop</td>
<td align="right">1</td>
</tr>
<tr>
<td>Fixed mounting frame</td>
<td align="right">1</td>
</tr>
</tbody></table>
<h2>3. Hardware Connections</h2>
<h3>HC-SR04 to Arduino UNO</h3>
<table>
<thead>
<tr>
<th>HC-SR04 Pin</th>
<th>Arduino UNO</th>
</tr>
</thead>
<tbody><tr>
<td>VCC</td>
<td>5V</td>
</tr>
<tr>
<td>GND</td>
<td>GND</td>
</tr>
<tr>
<td>TRIG</td>
<td>Digital Pin 9</td>
</tr>
<tr>
<td>ECHO</td>
<td>Digital Pin 10</td>
</tr>
</tbody></table>
<p><strong>Sensor Installation:</strong></p>
<ul>
<li>Mount the ultrasonic sensor horizontally at a fixed height.</li>
<li>The sensor must face vertically downward.</li>
<li>Keep the sensor stable.</li>
<li>The person should stand directly below the sensor.</li>
<li>Measure the distance from the sensor's ultrasonic face to the floor.</li>
</ul>
<p>For example:</p>
<pre><code class="language-text">       HC-SR04 SENSOR
       (Fixed Position)
       ┌─────────────┐
       │             │
       └─────────────┘
              |
              |
              |  Measured Distance
              |
           _______
          /       \
         |  HEAD   |
         |         |
         | PERSON  |
         |         |
         |         |
         |         |
         |_________|

       ----------------
             FLOOR
</code></pre>
<p><strong>Example:</strong></p>
<ul>
<li>Sensor mounting height = 200 cm</li>
<li>Distance from sensor to head = 30 cm</li>
</ul>
<p>Person's height:</p>
<p>[
H=200-30
]</p>
<p>[
\boxed{H=170\text{ cm}}
]</p>
<p><em>Important: The sensor mounting height must be measured accurately from the sensor's measuring face to the floor.</em></p>
<hr />
<h2>4. Arduino IDE Setup</h2>
<h3>Step 1: Install Arduino IDE</h3>
<p>Download Arduino IDE:</p>
<p><a href="https://www.arduino.cc/en/software">https://www.arduino.cc/en/software</a></p>
<p>Install and open Arduino IDE.</p>
<h3>Step 2: Arduino Code</h3>
<p>The following program measures the distance using the HC-SR04 sensor and sends the measurement to Python through serial communication.</p>
<p>No additional Arduino library is required.</p>
<pre><code class="language-cpp">// HC-SR04 Configuration

#define TRIG_PIN 9
#define ECHO_PIN 10

void setup() {

    // Start serial communication
    Serial.begin(9600);

    // Configure sensor pins
    pinMode(TRIG_PIN, OUTPUT);
    pinMode(ECHO_PIN, INPUT);
}

void loop() {

    // Send ultrasonic trigger pulse
    digitalWrite(TRIG_PIN, LOW);
    delayMicroseconds(2);

    digitalWrite(TRIG_PIN, HIGH);
    delayMicroseconds(10);

    digitalWrite(TRIG_PIN, LOW);

    // Read echo duration
    long duration = pulseIn(ECHO_PIN, HIGH, 30000);

    if (duration == 0) {

        Serial.println("ERROR");

    }
    else {

        // Calculate distance in centimeters
        float distance = duration * 0.0343 / 2;

        // Send distance to Python
        Serial.println(distance);
    }

    delay(500);
}
</code></pre>
<h3>Step 3: Upload the Program</h3>
<ol>
<li>Connect Arduino UNO to your computer.</li>
<li>Select the correct board: Arduino UNO.</li>
<li>Select the correct COM port.</li>
<li>Upload the program.</li>
<li>Check the Serial Monitor at 9600 baud.</li>
</ol>
<p>Expected output:</p>
<pre><code class="language-text">30.20
30.10
30.25
30.15
</code></pre>
<p>These values represent the measured distance between the sensor and the person's head.</p>
<hr />
<h2>5. Python Environment Setup</h2>
<h3>Step 1: Install Python</h3>
<p>Download Python:</p>
<p><a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></p>
<p>Verify installation:</p>
<pre><code class="language-bash">python --version
</code></pre>
<h3>Step 2: Create Project Folder</h3>
<p>Open PowerShell or Command Prompt.</p>
<pre><code class="language-powershell">mkdir Height_Measurement
cd Height_Measurement
</code></pre>
<h3>Step 3: Create Python Virtual Environment</h3>
<pre><code class="language-bash">python -m venv venv
</code></pre>
<h3>Step 4: Activate Virtual Environment</h3>
<p><strong>Windows PowerShell:</strong></p>
<pre><code class="language-powershell">.\venv\Scripts\Activate.ps1
</code></pre>
<p>If PowerShell blocks activation:</p>
<pre><code class="language-powershell">Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
</code></pre>
<p>Then activate again:</p>
<pre><code class="language-powershell">.\venv\Scripts\Activate.ps1
</code></pre>
<p><strong>Windows Command Prompt:</strong></p>
<pre><code class="language-cmd">venv\Scripts\activate.bat
</code></pre>
<p>After activation, you should see:</p>
<pre><code class="language-text">(venv) C:\...\Height_Measurement&gt;
</code></pre>
<h3>Step 5: Install Required Libraries</h3>
<pre><code class="language-bash">pip install flask pyserial
</code></pre>
<p>Save dependencies:</p>
<pre><code class="language-bash">pip freeze &gt; requirements.txt
</code></pre>
<hr />
<h2>6. Project Structure</h2>
<pre><code class="language-text">Height_Measurement/
│
├── venv/
│
├── app.py
│
└── requirements.txt
</code></pre>
<p>The complete website, including HTML, CSS and JavaScript, will be included inside <code>app.py</code>.</p>
<hr />
<h2>7. Create the Python Application</h2>
<p>Create a file named <code>app.py</code>.</p>
<p><strong>Important:</strong> Set <code>SENSOR_HEIGHT_CM</code> according to the actual height of your mounted sensor.</p>
<p>For this example, the sensor is mounted 200 cm above the floor.</p>
<pre><code class="language-python">from flask import Flask, jsonify, render_template_string
import serial
import threading
import time

app = Flask(__name__)

# ==================================
# CONFIGURATION
# ==================================

SERIAL_PORT = "COM3"
BAUD_RATE = 9600

# Sensor height from floor in centimeters
SENSOR_HEIGHT_CM = 200

# Measurement variables
distance = 0
person_height = 0

connection_status = "Disconnected"
last_updated = "--"


# ==================================
# ARDUINO SERIAL COMMUNICATION
# ==================================

def read_arduino():

    global distance, person_height
    global connection_status, last_updated

    while True:

        try:

            print("Connecting to Arduino...")

            arduino = serial.Serial(
                SERIAL_PORT,
                BAUD_RATE,
                timeout=2
            )

            time.sleep(2)

            connection_status = "Connected"

            print("Arduino Connected!")

            while True:

                line = arduino.readline().decode(
                    "utf-8",
                    errors="ignore"
                ).strip()

                if not line or line == "ERROR":
                    continue

                try:

                    measured_distance = float(line)

                    # Validate sensor measurement
                    if not 2 &lt;= measured_distance &lt; SENSOR_HEIGHT_CM:
                        continue

                    # Calculate person's height
                    calculated_height = (
                        SENSOR_HEIGHT_CM - measured_distance
                    )

                    distance = round(measured_distance, 2)

                    person_height = round(
                        calculated_height, 2
                    )

                    last_updated = time.strftime("%H:%M:%S")

                    print(
                        f"Distance: {distance} cm | "
                        f"Height: {person_height} cm"
                    )

                except ValueError:
                    continue

        except Exception as error:

            connection_status = "Disconnected"

            print("Arduino Error:", error)

            time.sleep(3)


# ==================================
# WEB DASHBOARD
# ==================================

HTML_PAGE = """

&lt;!DOCTYPE html&gt;
&lt;html&gt;

&lt;head&gt;

    &lt;title&gt;Height Measurement System&lt;/title&gt;

    &lt;meta name="viewport"
          content="width=device-width, initial-scale=1"&gt;

    &lt;style&gt;

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #eef2f7;
            color: #172554;
        }

        header {
            background: #172554;
            color: white;
            text-align: center;
            padding: 30px 15px;
        }

        header h1 {
            margin: 0 0 10px;
        }

        .container {
            max-width: 900px;
            margin: 50px auto;
            padding: 15px;
        }

        .cards {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 25px;
        }

        .card {
            background: white;
            width: 300px;
            padding: 35px 20px;
            border-radius: 18px;
            text-align: center;
            box-shadow: 0 5px 20px #0001;
        }

        .icon {
            font-size: 45px;
        }

        .value {
            font-size: 45px;
            font-weight: bold;
            margin: 20px 0;
        }

        .height {
            color: #2563eb;
        }

        .distance {
            color: #ea580c;
        }

        .status-box {
            background: white;
            padding: 22px;
            border-radius: 15px;
            margin-top: 30px;
            text-align: center;
        }

        .connected {
            color: #16a34a;
        }

        .disconnected {
            color: #dc2626;
        }

        .info {
            background: white;
            padding: 20px;
            margin-top: 25px;
            border-radius: 15px;
            text-align: center;
        }

        footer {
            text-align: center;
            padding: 25px;
            color: #64748b;
        }

    &lt;/style&gt;

&lt;/head&gt;

&lt;body&gt;

    &lt;header&gt;

        &lt;h1&gt;📏 Height Measurement System&lt;/h1&gt;

        &lt;p&gt;Arduino-Based Smart Height Monitoring&lt;/p&gt;

    &lt;/header&gt;


    &lt;div class="container"&gt;

        &lt;div class="cards"&gt;

            &lt;div class="card"&gt;

                &lt;div class="icon"&gt;🧍&lt;/div&gt;

                &lt;h2&gt;Person's Height&lt;/h2&gt;

                &lt;div class="value height" id="height"&gt;

                    -- cm

                &lt;/div&gt;

                &lt;p&gt;Calculated Height&lt;/p&gt;

            &lt;/div&gt;


            &lt;div class="card"&gt;

                &lt;div class="icon"&gt;📡&lt;/div&gt;

                &lt;h2&gt;Sensor Distance&lt;/h2&gt;

                &lt;div class="value distance" id="distance"&gt;

                    -- cm

                &lt;/div&gt;

                &lt;p&gt;Distance from Sensor to Head&lt;/p&gt;

            &lt;/div&gt;

        &lt;/div&gt;


        &lt;div class="info"&gt;

            &lt;h3&gt;Sensor Mounting Height&lt;/h3&gt;

            &lt;h2 id="mounting"&gt;-- cm&lt;/h2&gt;

        &lt;/div&gt;


        &lt;div class="status-box"&gt;

            &lt;h3&gt;

                Arduino Status:

                &lt;span id="status" class="disconnected"&gt;

                    Checking...

                &lt;/span&gt;

            &lt;/h3&gt;

            &lt;p&gt;

                Last Updated:

                &lt;span id="updated"&gt;--&lt;/span&gt;

            &lt;/p&gt;

        &lt;/div&gt;

    &lt;/div&gt;


    &lt;footer&gt;

        Arduino UNO + HC-SR04 | Python Flask

    &lt;/footer&gt;


    &lt;script&gt;

        async function updateData() {

            try {

                const response = await fetch("/data");

                const data = await response.json();


                document.getElementById("height").innerText =
                    data.height + " cm";


                document.getElementById("distance").innerText =
                    data.distance + " cm";


                document.getElementById("mounting").innerText =
                    data.mounting_height + " cm";


                const status =
                    document.getElementById("status");


                status.innerText = data.status;


                status.className =
                    data.status === "Connected"
                    ? "connected"
                    : "disconnected";


                document.getElementById("updated").innerText =
                    data.updated;

            }

            catch (error) {

                document.getElementById("status").innerText =
                    "Connection Error";

            }

        }


        updateData();

        // Refresh dashboard every second
        setInterval(updateData, 1000);

    &lt;/script&gt;

&lt;/body&gt;

&lt;/html&gt;

"""


# ==================================
# FLASK ROUTES
# ==================================

@app.route("/")
def home():

    return render_template_string(HTML_PAGE)


@app.route("/data")
def get_data():

    return jsonify({

        "height": person_height,

        "distance": distance,

        "mounting_height": SENSOR_HEIGHT_CM,

        "status": connection_status,

        "updated": last_updated

    })


# ==================================
# START APPLICATION
# ==================================

if __name__ == "__main__":

    thread = threading.Thread(
        target=read_arduino,
        daemon=True
    )

    thread.start()

    app.run(
        host="127.0.0.1",
        port=5000,
        debug=False
    )
</code></pre>
<hr />
<h2>8. Configure Sensor Height and COM Port</h2>
<p>Open <code>app.py</code> and change these values:</p>
<pre><code class="language-python">SERIAL_PORT = "COM3"

SENSOR_HEIGHT_CM = 200
</code></pre>
<p>For example, if the sensor is mounted 210 cm above the floor:</p>
<pre><code class="language-python">SENSOR_HEIGHT_CM = 210
</code></pre>
<p>If Arduino is connected to COM5:</p>
<pre><code class="language-python">SERIAL_PORT = "COM5"
</code></pre>
<p><strong>Remember:</strong> The mounting height is measured from the ultrasonic sensor's front measuring surface, not from the Arduino board or mounting bracket.</p>
<hr />
<h2>9. Run the Application</h2>
<ol>
<li>Connect Arduino UNO to your computer.</li>
<li>Upload the Arduino program.</li>
<li>Close Arduino IDE Serial Monitor.</li>
<li>Activate the Python virtual environment.</li>
<li>Run the application:</li>
</ol>
<pre><code class="language-bash">python app.py
</code></pre>
<p>Open the browser:</p>
<pre><code class="language-text">http://127.0.0.1:5000
</code></pre>
<h3>Example Result</h3>
<p>Suppose:</p>
<ul>
<li>Sensor mounting height = 200 cm</li>
<li>Measured distance = 30 cm</li>
</ul>
<p>Then:</p>
<p>[
H=200-30=170\text{ cm}
]</p>
<p>The dashboard will display:</p>
<table>
<thead>
<tr>
<th>Measurement</th>
<th align="right">Value</th>
</tr>
</thead>
<tbody><tr>
<td>Person's Height</td>
<td align="right">170 cm</td>
</tr>
<tr>
<td>Sensor Distance</td>
<td align="right">30 cm</td>
</tr>
<tr>
<td>Sensor Mounting Height</td>
<td align="right">200 cm</td>
</tr>
<tr>
<td>Arduino Status</td>
<td align="right">Connected</td>
</tr>
</tbody></table>
<hr />
<h2>10. Troubleshooting</h2>
<table>
<thead>
<tr>
<th>Problem</th>
<th>Solution</th>
</tr>
</thead>
<tbody><tr>
<td>COM port error</td>
<td>Check Arduino COM port</td>
</tr>
<tr>
<td>Access denied</td>
<td>Close Arduino Serial Monitor</td>
</tr>
<tr>
<td>Arduino disconnected</td>
<td>Check USB connection</td>
</tr>
<tr>
<td>Height shows zero</td>
<td>Check sensor wiring and mounting height</td>
</tr>
<tr>
<td>Unstable readings</td>
<td>Keep the sensor fixed and person stationary</td>
</tr>
<tr>
<td>Incorrect height</td>
<td>Re-measure the sensor-to-floor distance</td>
</tr>
<tr>
<td>No sensor reading</td>
<td>Check TRIG and ECHO connections</td>
</tr>
</tbody></table>
<hr />
<h2>11. Important Accuracy and Safety Notes</h2>
<ul>
<li>Mount the sensor securely and vertically.</li>
<li>Ensure the sensor has a clear view of the person's head.</li>
<li>Ask the person to stand straight and remain still.</li>
<li>Avoid measuring near walls or other objects that can reflect ultrasonic waves.</li>
<li>Take several measurements and use an average for better stability.</li>
<li>HC-SR04 readings can vary depending on the surface, angle and environment.</li>
<li>This is an educational prototype, not a medical-grade height measurement instrument.</li>
</ul>
<hr />
<h2>12. Future Improvements</h2>
<p>Students can extend this project with:</p>
<ol>
<li>Automatic averaging of multiple readings.</li>
<li>Display height in both centimeters and feet/inches.</li>
<li>Save measurements in an SQLite database.</li>
<li>Add student name and measurement history.</li>
<li>Generate height measurement reports.</li>
<li>Add an LCD display.</li>
<li>Develop a school-based student height monitoring system.</li>
</ol>
<p><strong>Project Conclusion:</strong> This project demonstrates how an ultrasonic sensor, Arduino, Python serial communication and Flask web development can be combined to create a practical height measurement system.</p>
]]></content:encoded></item><item><title><![CDATA[Arduino DHT11 Temperature & Humidity Monitoring System]]></title><description><![CDATA[This project uses an Arduino UNO and DHT11 sensor to measure temperature and humidity and display the readings on a live web dashboard using Python Flask…]]></description><link>https://piankit.hashnode.dev/dht11</link><guid isPermaLink="true">https://piankit.hashnode.dev/dht11</guid><dc:creator><![CDATA[Ankit Chapagain]]></dc:creator><pubDate>Tue, 03 Nov 2026 16:56:50 GMT</pubDate><content:encoded><![CDATA[<h2>1. Project Overview</h2>
<p>This project uses an <strong>Arduino UNO and DHT11 sensor</strong> to measure temperature and humidity and display the readings on a live web dashboard using Python Flask.</p>
<h3>Technologies Used</h3>
<ul>
<li>Arduino UNO</li>
<li>DHT11 Temperature and Humidity Sensor</li>
<li>Arduino IDE</li>
<li>Python</li>
<li>Flask</li>
<li>PySerial</li>
<li>HTML, CSS and JavaScript</li>
</ul>
<h3>System Architecture</h3>
<pre><code class="language-text">DHT11 Sensor
     |
     v
Arduino UNO
     |
     v
USB Serial Communication
     |
     v
Python Flask Application
     |
     v
Web Dashboard
     |
     v
Live Temperature &amp; Humidity
</code></pre>
<hr />
<h2>2. Hardware Requirements</h2>
<table>
<thead>
<tr>
<th>Component</th>
<th align="right">Quantity</th>
</tr>
</thead>
<tbody><tr>
<td>Arduino UNO</td>
<td align="right">1</td>
</tr>
<tr>
<td>DHT11 Sensor</td>
<td align="right">1</td>
</tr>
<tr>
<td>Jumper Wires</td>
<td align="right">3</td>
</tr>
<tr>
<td>USB Cable</td>
<td align="right">1</td>
</tr>
<tr>
<td>Computer/Laptop</td>
<td align="right">1</td>
</tr>
</tbody></table>
<h3>DHT11 Connections</h3>
<table>
<thead>
<tr>
<th>DHT11 Pin</th>
<th>Arduino UNO</th>
</tr>
</thead>
<tbody><tr>
<td>VCC</td>
<td>5V</td>
</tr>
<tr>
<td>DATA</td>
<td>Digital Pin 2</td>
</tr>
<tr>
<td>GND</td>
<td>GND</td>
</tr>
</tbody></table>
<p><em>For a bare four-pin DHT11 sensor, check its pinout and use the required pull-up resistor. Three-pin modules often include this resistor.</em></p>
<hr />
<h2>3. Arduino IDE Setup</h2>
<h3>Step 1: Install Arduino IDE</h3>
<p>Download Arduino IDE:</p>
<p><a href="https://www.arduino.cc/en/software">https://www.arduino.cc/en/software</a></p>
<p>Install and open Arduino IDE.</p>
<h3>Step 2: Install DHT11 Library</h3>
<ol>
<li>Open Arduino IDE.</li>
<li>Navigate to <strong>Sketch → Include Library → Manage Libraries</strong>.</li>
<li>Search for <code>DHT sensor library</code>.</li>
<li>Install <strong>DHT sensor library by Adafruit</strong>.</li>
<li>Install <strong>Adafruit Unified Sensor</strong> if requested.</li>
</ol>
<h3>Step 3: Arduino Code</h3>
<p>Create a new Arduino sketch and upload the following code.</p>
<pre><code class="language-cpp">#include &lt;DHT.h&gt;

// Sensor configuration
#define DHTPIN 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {

    // Start serial communication
    Serial.begin(9600);

    // Initialize DHT11
    dht.begin();
}

void loop() {

    // Read sensor values
    float temperature = dht.readTemperature();
    float humidity = dht.readHumidity();

    // Check sensor readings
    if (isnan(temperature) || isnan(humidity)) {

        Serial.println("ERROR");

    }
    else {

        // Send data to Python
        Serial.print(temperature);
        Serial.print(",");
        Serial.println(humidity);

    }

    delay(2000);
}
</code></pre>
<h3>Expected Serial Output</h3>
<pre><code class="language-text">28.00,65.00
29.00,64.00
30.00,63.00
</code></pre>
<p>The first value represents temperature in Celsius, and the second represents humidity in percentage.</p>
<hr />
<h2>4. Python Environment Setup</h2>
<h3>Step 1: Install Python</h3>
<p>Download Python from:</p>
<p><a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></p>
<p>During installation, select <strong>Add Python to PATH</strong>.</p>
<p>Verify installation:</p>
<pre><code class="language-bash">python --version
</code></pre>
<h3>Step 2: Create Project Folder</h3>
<p>Open PowerShell or Command Prompt.</p>
<pre><code class="language-powershell">mkdir DHT11_Website
cd DHT11_Website
</code></pre>
<h3>Step 3: Create Python Virtual Environment</h3>
<p>A virtual environment keeps project dependencies separate from other Python projects.</p>
<pre><code class="language-bash">python -m venv venv
</code></pre>
<h3>Step 4: Activate Virtual Environment</h3>
<p><strong>Windows PowerShell:</strong></p>
<pre><code class="language-powershell">.\venv\Scripts\Activate.ps1
</code></pre>
<p>If PowerShell blocks activation, run:</p>
<pre><code class="language-powershell">Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
</code></pre>
<p>Then activate again:</p>
<pre><code class="language-powershell">.\venv\Scripts\Activate.ps1
</code></pre>
<p><strong>Windows Command Prompt:</strong></p>
<pre><code class="language-cmd">venv\Scripts\activate.bat
</code></pre>
<p>After successful activation, you should see:</p>
<pre><code class="language-text">(venv) C:\...\DHT11_Website&gt;
</code></pre>
<h3>Step 5: Install Required Libraries</h3>
<pre><code class="language-bash">pip install flask pyserial
</code></pre>
<p>Verify installed packages:</p>
<pre><code class="language-bash">pip list
</code></pre>
<h3>Step 6: Save Dependencies</h3>
<pre><code class="language-bash">pip freeze &gt; requirements.txt
</code></pre>
<hr />
<h2>5. Project Structure</h2>
<p>The project will contain one Python application file.</p>
<pre><code class="language-text">DHT11_Website/
│
├── venv/
│
├── app.py
│
└── requirements.txt
</code></pre>
<p>The HTML, CSS and JavaScript code will be included inside <code>app.py</code>, so a separate HTML file is not required.</p>
<hr />
<h2>6. Create the Python Application</h2>
<p>Create a file named <code>app.py</code>.</p>
<p>Copy the following complete code:</p>
<pre><code class="language-python">from flask import Flask, jsonify, render_template_string
import serial
import threading
import time

app = Flask(__name__)

# Arduino Configuration
SERIAL_PORT = "COM3"
BAUD_RATE = 9600

# Sensor Variables
temperature = 0
humidity = 0

connection_status = "Disconnected"
last_updated = "--"


# =====================================
# ARDUINO SERIAL COMMUNICATION
# =====================================

def read_arduino():

    global temperature, humidity
    global connection_status, last_updated

    while True:

        try:

            print("Connecting to Arduino...")

            arduino = serial.Serial(
                SERIAL_PORT,
                BAUD_RATE,
                timeout=2
            )

            time.sleep(2)

            connection_status = "Connected"

            print("Arduino Connected!")

            while True:

                line = arduino.readline().decode(
                    "utf-8",
                    errors="ignore"
                ).strip()

                if not line or line == "ERROR":
                    continue

                try:

                    values = line.split(",")

                    if len(values) == 2:

                        temp = float(values[0])
                        hum = float(values[1])

                        temperature = temp
                        humidity = hum

                        last_updated = time.strftime("%H:%M:%S")

                        print(
                            f"Temperature: {temp} C | "
                            f"Humidity: {hum} %"
                        )

                except ValueError:

                    continue

        except Exception as error:

            connection_status = "Disconnected"

            print("Arduino Error:", error)

            time.sleep(3)


# =====================================
# HTML DASHBOARD
# =====================================

HTML_PAGE = """

&lt;!DOCTYPE html&gt;
&lt;html&gt;

&lt;head&gt;

    &lt;title&gt;DHT11 Monitoring System&lt;/title&gt;

    &lt;meta name="viewport"
          content="width=device-width, initial-scale=1"&gt;

    &lt;style&gt;

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #eef2f7;
            color: #172554;
        }

        header {
            background: #172554;
            color: white;
            padding: 30px 15px;
            text-align: center;
        }

        header h1 {
            margin: 0 0 10px;
        }

        .container {
            max-width: 900px;
            margin: 50px auto;
            padding: 15px;
        }

        .cards {
            display: flex;
            justify-content: center;
            gap: 25px;
            flex-wrap: wrap;
        }

        .card {
            background: white;
            width: 300px;
            padding: 35px 20px;
            border-radius: 18px;
            text-align: center;
            box-shadow: 0 5px 20px #0001;
        }

        .icon {
            font-size: 45px;
        }

        .value {
            font-size: 48px;
            font-weight: bold;
            margin: 20px 0;
        }

        .temperature {
            color: #ef4444;
        }

        .humidity {
            color: #2563eb;
        }

        .status-box {
            background: white;
            padding: 22px;
            border-radius: 15px;
            margin-top: 30px;
            text-align: center;
        }

        .connected {
            color: #16a34a;
        }

        .disconnected {
            color: #dc2626;
        }

        footer {
            text-align: center;
            padding: 25px;
            color: #64748b;
        }

    &lt;/style&gt;

&lt;/head&gt;

&lt;body&gt;

    &lt;header&gt;

        &lt;h1&gt;🌡️ DHT11 Monitoring System&lt;/h1&gt;

        &lt;p&gt;Live Temperature and Humidity Dashboard&lt;/p&gt;

    &lt;/header&gt;


    &lt;div class="container"&gt;

        &lt;div class="cards"&gt;

            &lt;div class="card"&gt;

                &lt;div class="icon"&gt;🌡️&lt;/div&gt;

                &lt;h2&gt;Temperature&lt;/h2&gt;

                &lt;div class="value temperature"
                     id="temperature"&gt;

                    -- °C

                &lt;/div&gt;

                &lt;p&gt;Room Temperature&lt;/p&gt;

            &lt;/div&gt;


            &lt;div class="card"&gt;

                &lt;div class="icon"&gt;💧&lt;/div&gt;

                &lt;h2&gt;Humidity&lt;/h2&gt;

                &lt;div class="value humidity"
                     id="humidity"&gt;

                    -- %

                &lt;/div&gt;

                &lt;p&gt;Air Humidity&lt;/p&gt;

            &lt;/div&gt;

        &lt;/div&gt;


        &lt;div class="status-box"&gt;

            &lt;h3&gt;

                Arduino Status:

                &lt;span id="status" class="disconnected"&gt;

                    Checking...

                &lt;/span&gt;

            &lt;/h3&gt;

            &lt;p&gt;

                Last Updated:

                &lt;span id="updated"&gt;--&lt;/span&gt;

            &lt;/p&gt;

        &lt;/div&gt;

    &lt;/div&gt;


    &lt;footer&gt;

        Arduino UNO + DHT11 | Python Flask IoT Dashboard

    &lt;/footer&gt;


    &lt;script&gt;

        async function updateData() {

            try {

                const response = await fetch("/data");

                const data = await response.json();


                document.getElementById("temperature").innerText =
                    data.temperature + " °C";


                document.getElementById("humidity").innerText =
                    data.humidity + " %";


                const status =
                    document.getElementById("status");


                status.innerText = data.status;


                status.className =
                    data.status === "Connected"
                    ? "connected"
                    : "disconnected";


                document.getElementById("updated").innerText =
                    data.updated;

            }

            catch (error) {

                document.getElementById("status").innerText =
                    "Connection Error";

            }

        }


        updateData();

        // Update every two seconds
        setInterval(updateData, 2000);

    &lt;/script&gt;

&lt;/body&gt;

&lt;/html&gt;

"""


# =====================================
# FLASK ROUTES
# =====================================

@app.route("/")
def home():

    return render_template_string(HTML_PAGE)


@app.route("/data")
def get_data():

    return jsonify({

        "temperature": temperature,

        "humidity": humidity,

        "status": connection_status,

        "updated": last_updated

    })


# =====================================
# START APPLICATION
# =====================================

if __name__ == "__main__":

    thread = threading.Thread(
        target=read_arduino,
        daemon=True
    )

    thread.start()

    app.run(
        host="127.0.0.1",
        port=5000,
        debug=False
    )
</code></pre>
<hr />
<h2>7. Configure Arduino COM Port</h2>
<p>Before running the application, identify the Arduino COM port.</p>
<ol>
<li>Open Arduino IDE.</li>
<li>Connect Arduino UNO.</li>
<li>Select <strong>Tools → Port</strong>.</li>
<li>Note the COM port number.</li>
</ol>
<p>For example:</p>
<pre><code class="language-python">SERIAL_PORT = "COM3"
</code></pre>
<p>If your Arduino uses COM5, change it to:</p>
<pre><code class="language-python">SERIAL_PORT = "COM5"
</code></pre>
<p><strong>Important:</strong> Close Arduino IDE Serial Monitor before running the Python application because both applications cannot normally access the same serial port simultaneously.</p>
<hr />
<h2>8. Run the Application</h2>
<p>Make sure your virtual environment is activated.</p>
<pre><code class="language-bash">python app.py
</code></pre>
<p>Expected terminal output:</p>
<pre><code class="language-text">Connecting to Arduino...
Arduino Connected!

Temperature: 28.0 C | Humidity: 65.0 %
Temperature: 29.0 C | Humidity: 64.0 %

Running on http://127.0.0.1:5000
</code></pre>
<p>Open your web browser:</p>
<pre><code class="language-text">http://127.0.0.1:5000
</code></pre>
<p>Your live dashboard will display the temperature, humidity and Arduino connection status.</p>
<hr />
<h2>9. Troubleshooting</h2>
<table>
<thead>
<tr>
<th>Problem</th>
<th>Possible Solution</th>
</tr>
</thead>
<tbody><tr>
<td>COM port error</td>
<td>Check the correct Arduino COM port</td>
</tr>
<tr>
<td>Access denied</td>
<td>Close Arduino Serial Monitor</td>
</tr>
<tr>
<td>Arduino disconnected</td>
<td>Check USB cable and connection</td>
</tr>
<tr>
<td>No sensor readings</td>
<td>Check DHT11 wiring and library installation</td>
</tr>
<tr>
<td>Website not opening</td>
<td>Check whether Flask is running on port 5000</td>
</tr>
<tr>
<td>Python module not found</td>
<td>Activate virtual environment and install dependencies</td>
</tr>
</tbody></table>
<hr />
<h2>10. Useful Commands</h2>
<table>
<thead>
<tr>
<th>Task</th>
<th>Command</th>
</tr>
</thead>
<tbody><tr>
<td>Create virtual environment</td>
<td><code>python -m venv venv</code></td>
</tr>
<tr>
<td>Activate environment</td>
<td><code>venv\Scripts\activate</code></td>
</tr>
<tr>
<td>Install Flask</td>
<td><code>pip install flask</code></td>
</tr>
<tr>
<td>Install PySerial</td>
<td><code>pip install pyserial</code></td>
</tr>
<tr>
<td>Save dependencies</td>
<td><code>pip freeze &gt; requirements.txt</code></td>
</tr>
<tr>
<td>Run application</td>
<td><code>python app.py</code></td>
</tr>
<tr>
<td>Deactivate environment</td>
<td><code>deactivate</code></td>
</tr>
</tbody></table>
<hr />
<h2>11. Future Improvements</h2>
<p>After completing the basic project, students can extend it with:</p>
<ol>
<li>Live temperature and humidity graphs.</li>
<li>Historical sensor data storage using SQLite.</li>
<li>Download sensor readings as CSV.</li>
<li>Temperature threshold alerts.</li>
<li>Multiple sensor monitoring.</li>
<li>Professional IoT dashboard design.</li>
<li>Remote access through a suitable network deployment.</li>
</ol>
<p><strong>Project Conclusion:</strong> This project demonstrates how Arduino hardware, sensor technology, serial communication and Python web development can be integrated to create a simple real-time IoT monitoring system.</p>
]]></content:encoded></item><item><title><![CDATA[Arduino Height Measurement System]]></title><description><![CDATA[The Arduino-based Height Measurement System uses an ultrasonic sensor to measure the distance between the sensor and a person's head. The sensor is mounted…]]></description><link>https://piankit.hashnode.dev/arduino-height-measurement-system</link><guid isPermaLink="true">https://piankit.hashnode.dev/arduino-height-measurement-system</guid><dc:creator><![CDATA[Ankit Chapagain]]></dc:creator><pubDate>Tue, 03 Nov 2026 16:53:38 GMT</pubDate><content:encoded><![CDATA[<h1></h1>
<h2>1. Project Overview</h2>
<p>The Arduino-based Height Measurement System uses an ultrasonic sensor to measure the distance between the sensor and a person's head.</p>
<p>The sensor is mounted at a fixed height, facing downward. When a person stands beneath it, the system measures the distance from the sensor to the person's head.</p>
<p>Python calculates the person's height using the following formula:</p>
<p><strong>Person's Height = Sensor Mounting Height − Measured Distance</strong></p>
<h3>Technologies Used</h3>
<ul>
<li>Arduino UNO</li>
<li>HC-SR04 Ultrasonic Sensor</li>
<li>Arduino IDE</li>
<li>Python</li>
<li>Flask</li>
<li>PySerial</li>
<li>HTML, CSS and JavaScript</li>
</ul>
<h3>System Architecture</h3>
<pre><code class="language-text">       HC-SR04 Sensor
              |
              v
          Arduino UNO
              |
              v
     USB Serial Communication
              |
              v
       Python Flask Server
              |
              v
       Height Calculation
              |
              v
        Web Dashboard
              |
              v
       Display Height (cm)
</code></pre>
<hr />
<h2>2. Hardware Requirements</h2>
<table>
<thead>
<tr>
<th>Component</th>
<th align="right">Quantity</th>
</tr>
</thead>
<tbody><tr>
<td>Arduino UNO</td>
<td align="right">1</td>
</tr>
<tr>
<td>HC-SR04 Ultrasonic Sensor</td>
<td align="right">1</td>
</tr>
<tr>
<td>Jumper Wires</td>
<td align="right">4</td>
</tr>
<tr>
<td>USB Cable</td>
<td align="right">1</td>
</tr>
<tr>
<td>Computer/Laptop</td>
<td align="right">1</td>
</tr>
<tr>
<td>Fixed mounting frame</td>
<td align="right">1</td>
</tr>
</tbody></table>
<h2>3. Hardware Connections</h2>
<h3>HC-SR04 to Arduino UNO</h3>
<table>
<thead>
<tr>
<th>HC-SR04 Pin</th>
<th>Arduino UNO</th>
</tr>
</thead>
<tbody><tr>
<td>VCC</td>
<td>5V</td>
</tr>
<tr>
<td>GND</td>
<td>GND</td>
</tr>
<tr>
<td>TRIG</td>
<td>Digital Pin 9</td>
</tr>
<tr>
<td>ECHO</td>
<td>Digital Pin 10</td>
</tr>
</tbody></table>
<p><strong>Sensor Installation:</strong></p>
<ul>
<li>Mount the ultrasonic sensor horizontally at a fixed height.</li>
<li>The sensor must face vertically downward.</li>
<li>Keep the sensor stable.</li>
<li>The person should stand directly below the sensor.</li>
<li>Measure the distance from the sensor's ultrasonic face to the floor.</li>
</ul>
<p>For example:</p>
<pre><code class="language-text">       HC-SR04 SENSOR
       (Fixed Position)
       ┌─────────────┐
       │             │
       └─────────────┘
              |
              |
              |  Measured Distance
              |
           _______
          /       \
         |  HEAD   |
         |         |
         | PERSON  |
         |         |
         |         |
         |         |
         |_________|

       ----------------
             FLOOR
</code></pre>
<p><strong>Example:</strong></p>
<ul>
<li>Sensor mounting height = 200 cm</li>
<li>Distance from sensor to head = 30 cm</li>
</ul>
<p>Person's height:</p>
<p>[
H=200-30
]</p>
<p>[
\boxed{H=170\text{ cm}}
]</p>
<p><em>Important: The sensor mounting height must be measured accurately from the sensor's measuring face to the floor.</em></p>
<hr />
<h2>4. Arduino IDE Setup</h2>
<h3>Step 1: Install Arduino IDE</h3>
<p>Download Arduino IDE:</p>
<p><a href="https://www.arduino.cc/en/software">https://www.arduino.cc/en/software</a></p>
<p>Install and open Arduino IDE.</p>
<h3>Step 2: Arduino Code</h3>
<p>The following program measures the distance using the HC-SR04 sensor and sends the measurement to Python through serial communication.</p>
<p>No additional Arduino library is required.</p>
<pre><code class="language-cpp">// HC-SR04 Configuration

#define TRIG_PIN 9
#define ECHO_PIN 10

void setup() {

    // Start serial communication
    Serial.begin(9600);

    // Configure sensor pins
    pinMode(TRIG_PIN, OUTPUT);
    pinMode(ECHO_PIN, INPUT);
}

void loop() {

    // Send ultrasonic trigger pulse
    digitalWrite(TRIG_PIN, LOW);
    delayMicroseconds(2);

    digitalWrite(TRIG_PIN, HIGH);
    delayMicroseconds(10);

    digitalWrite(TRIG_PIN, LOW);

    // Read echo duration
    long duration = pulseIn(ECHO_PIN, HIGH, 30000);

    if (duration == 0) {

        Serial.println("ERROR");

    }
    else {

        // Calculate distance in centimeters
        float distance = duration * 0.0343 / 2;

        // Send distance to Python
        Serial.println(distance);
    }

    delay(500);
}
</code></pre>
<h3>Step 3: Upload the Program</h3>
<ol>
<li>Connect Arduino UNO to your computer.</li>
<li>Select the correct board: Arduino UNO.</li>
<li>Select the correct COM port.</li>
<li>Upload the program.</li>
<li>Check the Serial Monitor at 9600 baud.</li>
</ol>
<p>Expected output:</p>
<pre><code class="language-text">30.20
30.10
30.25
30.15
</code></pre>
<p>These values represent the measured distance between the sensor and the person's head.</p>
<hr />
<h2>5. Python Environment Setup</h2>
<h3>Step 1: Install Python</h3>
<p>Download Python:</p>
<p><a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></p>
<p>Verify installation:</p>
<pre><code class="language-bash">python --version
</code></pre>
<h3>Step 2: Create Project Folder</h3>
<p>Open PowerShell or Command Prompt.</p>
<pre><code class="language-powershell">mkdir Height_Measurement
cd Height_Measurement
</code></pre>
<h3>Step 3: Create Python Virtual Environment</h3>
<pre><code class="language-bash">python -m venv venv
</code></pre>
<h3>Step 4: Activate Virtual Environment</h3>
<p><strong>Windows PowerShell:</strong></p>
<pre><code class="language-powershell">.\venv\Scripts\Activate.ps1
</code></pre>
<p>If PowerShell blocks activation:</p>
<pre><code class="language-powershell">Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
</code></pre>
<p>Then activate again:</p>
<pre><code class="language-powershell">.\venv\Scripts\Activate.ps1
</code></pre>
<p><strong>Windows Command Prompt:</strong></p>
<pre><code class="language-cmd">venv\Scripts\activate.bat
</code></pre>
<p>After activation, you should see:</p>
<pre><code class="language-text">(venv) C:\...\Height_Measurement&gt;
</code></pre>
<h3>Step 5: Install Required Libraries</h3>
<pre><code class="language-bash">pip install flask pyserial
</code></pre>
<p>Save dependencies:</p>
<pre><code class="language-bash">pip freeze &gt; requirements.txt
</code></pre>
<hr />
<h2>6. Project Structure</h2>
<pre><code class="language-text">Height_Measurement/
│
├── venv/
│
├── app.py
│
└── requirements.txt
</code></pre>
<p>The complete website, including HTML, CSS and JavaScript, will be included inside <code>app.py</code>.</p>
<hr />
<h2>7. Create the Python Application</h2>
<p>Create a file named <code>app.py</code>.</p>
<p><strong>Important:</strong> Set <code>SENSOR_HEIGHT_CM</code> according to the actual height of your mounted sensor.</p>
<p>For this example, the sensor is mounted 200 cm above the floor.</p>
<pre><code class="language-python">from flask import Flask, jsonify, render_template_string
import serial
import threading
import time

app = Flask(__name__)

# ==================================
# CONFIGURATION
# ==================================

SERIAL_PORT = "COM3"
BAUD_RATE = 9600

# Sensor height from floor in centimeters
SENSOR_HEIGHT_CM = 200

# Measurement variables
distance = 0
person_height = 0

connection_status = "Disconnected"
last_updated = "--"


# ==================================
# ARDUINO SERIAL COMMUNICATION
# ==================================

def read_arduino():

    global distance, person_height
    global connection_status, last_updated

    while True:

        try:

            print("Connecting to Arduino...")

            arduino = serial.Serial(
                SERIAL_PORT,
                BAUD_RATE,
                timeout=2
            )

            time.sleep(2)

            connection_status = "Connected"

            print("Arduino Connected!")

            while True:

                line = arduino.readline().decode(
                    "utf-8",
                    errors="ignore"
                ).strip()

                if not line or line == "ERROR":
                    continue

                try:

                    measured_distance = float(line)

                    # Validate sensor measurement
                    if not 2 &lt;= measured_distance &lt; SENSOR_HEIGHT_CM:
                        continue

                    # Calculate person's height
                    calculated_height = (
                        SENSOR_HEIGHT_CM - measured_distance
                    )

                    distance = round(measured_distance, 2)

                    person_height = round(
                        calculated_height, 2
                    )

                    last_updated = time.strftime("%H:%M:%S")

                    print(
                        f"Distance: {distance} cm | "
                        f"Height: {person_height} cm"
                    )

                except ValueError:
                    continue

        except Exception as error:

            connection_status = "Disconnected"

            print("Arduino Error:", error)

            time.sleep(3)


# ==================================
# WEB DASHBOARD
# ==================================

HTML_PAGE = """

&lt;!DOCTYPE html&gt;
&lt;html&gt;

&lt;head&gt;

    &lt;title&gt;Height Measurement System&lt;/title&gt;

    &lt;meta name="viewport"
          content="width=device-width, initial-scale=1"&gt;

    &lt;style&gt;

        * {
            box-sizing: border-box;
        }

        body {
            margin: 0;
            font-family: Arial, sans-serif;
            background: #eef2f7;
            color: #172554;
        }

        header {
            background: #172554;
            color: white;
            text-align: center;
            padding: 30px 15px;
        }

        header h1 {
            margin: 0 0 10px;
        }

        .container {
            max-width: 900px;
            margin: 50px auto;
            padding: 15px;
        }

        .cards {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 25px;
        }

        .card {
            background: white;
            width: 300px;
            padding: 35px 20px;
            border-radius: 18px;
            text-align: center;
            box-shadow: 0 5px 20px #0001;
        }

        .icon {
            font-size: 45px;
        }

        .value {
            font-size: 45px;
            font-weight: bold;
            margin: 20px 0;
        }

        .height {
            color: #2563eb;
        }

        .distance {
            color: #ea580c;
        }

        .status-box {
            background: white;
            padding: 22px;
            border-radius: 15px;
            margin-top: 30px;
            text-align: center;
        }

        .connected {
            color: #16a34a;
        }

        .disconnected {
            color: #dc2626;
        }

        .info {
            background: white;
            padding: 20px;
            margin-top: 25px;
            border-radius: 15px;
            text-align: center;
        }

        footer {
            text-align: center;
            padding: 25px;
            color: #64748b;
        }

    &lt;/style&gt;

&lt;/head&gt;

&lt;body&gt;

    &lt;header&gt;

        &lt;h1&gt;📏 Height Measurement System&lt;/h1&gt;

        &lt;p&gt;Arduino-Based Smart Height Monitoring&lt;/p&gt;

    &lt;/header&gt;


    &lt;div class="container"&gt;

        &lt;div class="cards"&gt;

            &lt;div class="card"&gt;

                &lt;div class="icon"&gt;🧍&lt;/div&gt;

                &lt;h2&gt;Person's Height&lt;/h2&gt;

                &lt;div class="value height" id="height"&gt;

                    -- cm

                &lt;/div&gt;

                &lt;p&gt;Calculated Height&lt;/p&gt;

            &lt;/div&gt;


            &lt;div class="card"&gt;

                &lt;div class="icon"&gt;📡&lt;/div&gt;

                &lt;h2&gt;Sensor Distance&lt;/h2&gt;

                &lt;div class="value distance" id="distance"&gt;

                    -- cm

                &lt;/div&gt;

                &lt;p&gt;Distance from Sensor to Head&lt;/p&gt;

            &lt;/div&gt;

        &lt;/div&gt;


        &lt;div class="info"&gt;

            &lt;h3&gt;Sensor Mounting Height&lt;/h3&gt;

            &lt;h2 id="mounting"&gt;-- cm&lt;/h2&gt;

        &lt;/div&gt;


        &lt;div class="status-box"&gt;

            &lt;h3&gt;

                Arduino Status:

                &lt;span id="status" class="disconnected"&gt;

                    Checking...

                &lt;/span&gt;

            &lt;/h3&gt;

            &lt;p&gt;

                Last Updated:

                &lt;span id="updated"&gt;--&lt;/span&gt;

            &lt;/p&gt;

        &lt;/div&gt;

    &lt;/div&gt;


    &lt;footer&gt;

        Arduino UNO + HC-SR04 | Python Flask

    &lt;/footer&gt;


    &lt;script&gt;

        async function updateData() {

            try {

                const response = await fetch("/data");

                const data = await response.json();


                document.getElementById("height").innerText =
                    data.height + " cm";


                document.getElementById("distance").innerText =
                    data.distance + " cm";


                document.getElementById("mounting").innerText =
                    data.mounting_height + " cm";


                const status =
                    document.getElementById("status");


                status.innerText = data.status;


                status.className =
                    data.status === "Connected"
                    ? "connected"
                    : "disconnected";


                document.getElementById("updated").innerText =
                    data.updated;

            }

            catch (error) {

                document.getElementById("status").innerText =
                    "Connection Error";

            }

        }


        updateData();

        // Refresh dashboard every second
        setInterval(updateData, 1000);

    &lt;/script&gt;

&lt;/body&gt;

&lt;/html&gt;

"""


# ==================================
# FLASK ROUTES
# ==================================

@app.route("/")
def home():

    return render_template_string(HTML_PAGE)


@app.route("/data")
def get_data():

    return jsonify({

        "height": person_height,

        "distance": distance,

        "mounting_height": SENSOR_HEIGHT_CM,

        "status": connection_status,

        "updated": last_updated

    })


# ==================================
# START APPLICATION
# ==================================

if __name__ == "__main__":

    thread = threading.Thread(
        target=read_arduino,
        daemon=True
    )

    thread.start()
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Django Workshop Day 2]]></title><description><![CDATA[Creating Django Apps Understanding Views URL Routing Templates render() Sending Data to Templates Loops Conditions Building a Simple Blog Website Think of…]]></description><link>https://piankit.hashnode.dev/django-workshop-day-2</link><guid isPermaLink="true">https://piankit.hashnode.dev/django-workshop-day-2</guid><dc:creator><![CDATA[Ankit Chapagain]]></dc:creator><pubDate>Fri, 19 Jun 2026 04:53:53 GMT</pubDate><content:encoded><![CDATA[<h2>Building a Simple Blog Website</h2>
<h3>What We Will Learn Today</h3>
<ol>
<li><p>Creating Django Apps</p>
</li>
<li><p>Understanding Views</p>
</li>
<li><p>URL Routing</p>
</li>
<li><p>Templates</p>
</li>
<li><p>render()</p>
</li>
<li><p>Sending Data to Templates</p>
</li>
<li><p>Loops</p>
</li>
<li><p>Conditions</p>
</li>
<li><p>Building a Simple Blog Website</p>
</li>
</ol>
<hr />
<h1>11. What is a Django App?</h1>
<p>Think of a project as a school.</p>
<p>Inside the school there are many departments.</p>
<p>Example:</p>
<pre><code class="language-text">School Website

├── Student App
├── Teacher App
├── Attendance App
├── Blog App
</code></pre>
<p>Each part is called an App.</p>
<p>Today we will create a Blog App.</p>
<p>Create app:</p>
<pre><code class="language-bash">python manage.py startapp blog
</code></pre>
<p>Django creates:</p>
<pre><code class="language-text">blog/

├── admin.py
├── apps.py
├── models.py
├── views.py
├── tests.py
└── migrations/
</code></pre>
<p>For now we only need:</p>
<pre><code class="language-text">views.py
</code></pre>
<hr />
<h1>12. Understanding Views</h1>
<p>A View is a Python function.</p>
<p>A View decides what the user sees.</p>
<p>Example:</p>
<pre><code class="language-python">from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to my Blog")
</code></pre>
<p>When a user visits a page, Django calls a View.</p>
<p>Simple Flow:</p>
<pre><code class="language-text">User
 ↓
URL
 ↓
View
 ↓
Response
</code></pre>
<hr />
<h1>13. Creating Multiple Views</h1>
<p>Open:</p>
<pre><code class="language-text">blog/views.py
</code></pre>
<p>Write:</p>
<pre><code class="language-python">from django.http import HttpResponse

def home(request):
    return HttpResponse("Home Page")

def about(request):
    return HttpResponse("About Page")

def contact(request):
    return HttpResponse("Contact Page")
</code></pre>
<p>Now we have three pages.</p>
<hr />
<h1>14. URL Routing</h1>
<p>URL routing tells Django:</p>
<p>"When a user visits this URL, call this View."</p>
<p>Create:</p>
<pre><code class="language-text">blog/urls.py
</code></pre>
<p>Write:</p>
<pre><code class="language-python">from django.urls import path
from .views import *

urlpatterns = [

    path('', home),

    path('about/', about),

    path('contact/', contact),

]
</code></pre>
<p>Meaning:</p>
<pre><code class="language-text">/          → home()

/about/    → about()

/contact/  → contact()
</code></pre>
<hr />
<h1>15. Connect App URLs</h1>
<p>Open:</p>
<pre><code class="language-text">project/urls.py
</code></pre>
<p>Write:</p>
<pre><code class="language-python">from django.contrib import admin
from django.urls import path,include

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', include('blog.urls')),

]
</code></pre>
<p>Now Django can access our app URLs.</p>
<p>Flow:</p>
<pre><code class="language-text">Project URL
      ↓
Blog URL
      ↓
View
</code></pre>
<hr />
<h1>16. Why Templates?</h1>
<p>Suppose we write:</p>
<pre><code class="language-python">return HttpResponse("&lt;h1&gt;Home Page&lt;/h1&gt;")
</code></pre>
<p>This works.</p>
<p>But imagine a website with:</p>
<ul>
<li><p>500 lines of HTML</p>
</li>
<li><p>CSS</p>
</li>
<li><p>Images</p>
</li>
<li><p>Navigation Bar</p>
</li>
</ul>
<p>Writing everything inside Python becomes difficult.</p>
<p>So Django uses Templates.</p>
<p>Template = HTML File</p>
<hr />
<h1>17. Creating Templates Folder</h1>
<p>Create:</p>
<pre><code class="language-text">blog/

└── templates/

    └── blog/

        ├── home.html

        ├── about.html

        └── contact.html
</code></pre>
<hr />
<h1>18. Creating Home Page</h1>
<p>home.html</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;

&lt;html&gt;

&lt;head&gt;
    &lt;title&gt;Home&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;

    &lt;h1&gt;My Blog Website&lt;/h1&gt;

    &lt;p&gt;Welcome to Django Workshop&lt;/p&gt;

&lt;/body&gt;

&lt;/html&gt;
</code></pre>
<hr />
<h1>19. Using render()</h1>
<p>Open views.py</p>
<pre><code class="language-python">from django.shortcuts import render

def home(request):

    return render(
        request,
        "blog/home.html"
    )
</code></pre>
<p>What happens?</p>
<pre><code class="language-text">User opens URL
       ↓
View executes
       ↓
render() finds home.html
       ↓
Browser shows page
</code></pre>
<hr />
<h1>20. Sending Data to HTML</h1>
<p>Instead of hard coding text:</p>
<pre><code class="language-html">&lt;h1&gt;Welcome Ram&lt;/h1&gt;
</code></pre>
<p>We can send data from Python.</p>
<p>View:</p>
<pre><code class="language-python">def home(request):

    context = {

        "name":"Ram"

    }

    return render(
        request,
        "blog/home.html",
        context
    )
</code></pre>
<p>HTML:</p>
<pre><code class="language-html">&lt;h1&gt;Welcome {{ name }}&lt;/h1&gt;
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Welcome Ram
</code></pre>
<hr />
<h1>21. Sending Multiple Data</h1>
<p>View:</p>
<pre><code class="language-python">context = {

    "name":"Ram",

    "course":"Django",

    "day":2

}
</code></pre>
<p>HTML:</p>
<pre><code class="language-html">&lt;h1&gt;{{ name }}&lt;/h1&gt;

&lt;p&gt;{{ course }}&lt;/p&gt;

&lt;p&gt;Day {{ day }}&lt;/p&gt;
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Ram

Django

Day 2
</code></pre>
<hr />
<h1>22. Loops in Templates</h1>
<p>Suppose we have students.</p>
<p>View:</p>
<pre><code class="language-python">context = {

    "students":[

        "Ram",

        "Sita",

        "Hari",

        "Gita"

    ]

}
</code></pre>
<p>HTML:</p>
<pre><code class="language-html">&lt;h2&gt;Student List&lt;/h2&gt;

{% for student in students %}

    &lt;p&gt;{{ student }}&lt;/p&gt;

{% endfor %}
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Ram

Sita

Hari

Gita
</code></pre>
<p>The loop works exactly like Python.</p>
<hr />
<h1>23. Conditions in Templates</h1>
<p>HTML:</p>
<pre><code class="language-html">{% if students %}

    &lt;h2&gt;Students Available&lt;/h2&gt;

{% else %}

    &lt;h2&gt;No Students Available&lt;/h2&gt;

{% endif %}
</code></pre>
<p>Django checks the condition and displays the result.</p>
<hr />
<h1>24. Mini Project - Simple Blog Website</h1>
<p>Now let's build a complete Blog Website.</p>
<p>Instead of using a database, we will store blogs inside a Python list.</p>
<p>This keeps things simple.</p>
<hr />
<h1>Step 1: Create Blog Data</h1>
<p>views.py</p>
<pre><code class="language-python">from django.shortcuts import render

blogs = [

    {
        "title":"Python Basics",
        "author":"Ram"
    },

    {
        "title":"Django Introduction",
        "author":"Sita"
    },

    {
        "title":"HTML Fundamentals",
        "author":"Hari"
    }

]
</code></pre>
<hr />
<h1>Step 2: Send Data to Template</h1>
<pre><code class="language-python">def home(request):

    context = {

        "blogs":blogs

    }

    return render(
        request,
        "blog/home.html",
        context
    )
</code></pre>
<hr />
<h1>Step 3: Display Blogs</h1>
<p>home.html</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;

&lt;html&gt;

&lt;head&gt;
    &lt;title&gt;Blog Website&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;

&lt;h1&gt;My Blog Website&lt;/h1&gt;

{% for blog in blogs %}

    &lt;h2&gt;{{ blog.title }}&lt;/h2&gt;

    &lt;p&gt;Author : {{ blog.author }}&lt;/p&gt;

    &lt;hr&gt;

{% endfor %}

&lt;/body&gt;

&lt;/html&gt;
</code></pre>
<p>Output:</p>
<pre><code class="language-text">My Blog Website

Python Basics
Author : Ram

Django Introduction
Author : Sita

HTML Fundamentals
Author : Hari
</code></pre>
<hr />
<h1>Step 4: Add About Page</h1>
<p>views.py</p>
<pre><code class="language-python">def about(request):

    return render(
        request,
        "blog/about.html"
    )
</code></pre>
<p>about.html</p>
<pre><code class="language-html">&lt;h1&gt;About Us&lt;/h1&gt;

&lt;p&gt;
This website was created using Django.
&lt;/p&gt;
</code></pre>
<hr />
<h1>Step 5: Add Navigation</h1>
<p>home.html</p>
<pre><code class="language-html">&lt;a href="/"&gt;Home&lt;/a&gt;

&lt;a href="/about/"&gt;About&lt;/a&gt;

&lt;hr&gt;
</code></pre>
<p>about.html</p>
<pre><code class="language-html">&lt;a href="/"&gt;Home&lt;/a&gt;

&lt;a href="/about/"&gt;About&lt;/a&gt;

&lt;hr&gt;
</code></pre>
<p>Now users can move between pages.</p>
<hr />
<h1>Final Project Structure</h1>
<pre><code class="language-text">project/

├── manage.py

├── blog/

│   ├── views.py

│   ├── urls.py

│   └── templates/

│       └── blog/

│           ├── home.html

│           └── about.html
</code></pre>
<hr />
<h1>Day 2 Summary</h1>
<p>Today we learned:</p>
<ol>
<li><p>Django Apps</p>
</li>
<li><p>Views</p>
</li>
<li><p>URLs</p>
</li>
<li><p>Templates</p>
</li>
<li><p>render()</p>
</li>
<li><p>Context</p>
</li>
<li><p>Variables</p>
</li>
<li><p>Loops</p>
</li>
<li><p>Conditions</p>
</li>
<li><p>Creating Multiple Pages</p>
</li>
<li><p>Building a Simple Blog Website</p>
</li>
</ol>
<p>Complete Flow:</p>
<pre><code class="language-text">User
 ↓
URL
 ↓
View
 ↓
Context Data
 ↓
Template
 ↓
Browser
</code></pre>
<p>Tomorrow (Day 3) we will connect our Blog Website to a real database using Models and Admin Panel.</p>
]]></content:encoded></item><item><title><![CDATA[Day 1 Django Note]]></title><description><![CDATA[Django is a Python framework used to build websites and web applications. It gives us a proper structure to build web apps easily. With Django, we can…]]></description><link>https://piankit.hashnode.dev/day-1-django-note</link><guid isPermaLink="true">https://piankit.hashnode.dev/day-1-django-note</guid><dc:creator><![CDATA[Ankit Chapagain]]></dc:creator><pubDate>Thu, 18 Jun 2026 10:55:12 GMT</pubDate><content:encoded><![CDATA[<h2>1. What is Django?</h2>
<p>Django is a Python framework used to build websites and web applications.</p>
<p>It gives us a proper structure to build web apps easily.</p>
<p>With Django, we can build:</p>
<ul>
<li><p>Blog website</p>
</li>
<li><p>School system</p>
</li>
<li><p>Inventory system</p>
</li>
<li><p>E-commerce website</p>
</li>
<li><p>Learning platform</p>
</li>
<li><p>Admin dashboard</p>
</li>
</ul>
<p>Django mainly helps us with:</p>
<ul>
<li><p>URL handling</p>
</li>
<li><p>Views</p>
</li>
<li><p>HTML rendering</p>
</li>
<li><p>Database structure</p>
</li>
<li><p>Security</p>
</li>
</ul>
<hr />
<h2>2. How Django Works</h2>
<p>Django works in a simple flow:</p>
<pre><code class="language-text">User opens a URL
        ↓
Django checks urls.py
        ↓
Django calls a view function
        ↓
View returns response or HTML page
        ↓
User sees output in browser
</code></pre>
<p>Simple example:</p>
<pre><code class="language-text">User opens /
        ↓
urls.py finds matching path
        ↓
home view is called
        ↓
home.html is rendered
</code></pre>
<hr />
<h2>3. Django MVT Architecture</h2>
<p>Django follows MVT architecture.</p>
<ul>
<li><p>M = Model</p>
</li>
<li><p>V = View</p>
</li>
<li><p>T = Template</p>
</li>
</ul>
<p>Simple meaning:</p>
<table>
<thead>
<tr>
<th>Component</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td>Model</td>
<td>Database structure</td>
</tr>
<tr>
<td>View</td>
<td>Python logic</td>
</tr>
<tr>
<td>Template</td>
<td>HTML page</td>
</tr>
</tbody></table>
<p>For now, just understand:</p>
<pre><code class="language-text">URL calls View
View renders Template
Model is used to design database table
</code></pre>
<hr />
<h2>4. Create Project Folder</h2>
<pre><code class="language-bash">mkdir django_day_1
cd django_day_1
</code></pre>
<hr />
<h2>5. Create Virtual Environment</h2>
<pre><code class="language-bash">python -m venv venv
</code></pre>
<p>Activate virtual environment.</p>
<h3>Windows</h3>
<pre><code class="language-bash">venv\Scripts\activate
</code></pre>
<h3>Mac/Linux</h3>
<pre><code class="language-bash">source venv/bin/activate
</code></pre>
<hr />
<h2>6. Install Django</h2>
<pre><code class="language-bash">pip install django
</code></pre>
<p>Check version:</p>
<pre><code class="language-bash">django-admin --version
</code></pre>
<hr />
<h2>7. Create Django Project</h2>
<pre><code class="language-bash">django-admin startproject myproject
</code></pre>
<p>Go inside project:</p>
<pre><code class="language-bash">cd myproject
</code></pre>
<p>Run server:</p>
<pre><code class="language-bash">python manage.py runserver
</code></pre>
<p>Open in browser:</p>
<pre><code class="language-text">http://127.0.0.1:8000/
</code></pre>
<p>You should see Django's default welcome page.</p>
<hr />
<h2>8. Important Files</h2>
<p>Project structure:</p>
<pre><code class="language-text">myproject/
│
├── manage.py
│
└── myproject/
    ├── settings.py
    ├── urls.py
    ├── asgi.py
    └── wsgi.py
</code></pre>
<h3>manage.py</h3>
<p>Used to run Django commands.</p>
<p>Example:</p>
<pre><code class="language-bash">python manage.py runserver
</code></pre>
<h3>settings.py</h3>
<p>Contains project settings such as:</p>
<ul>
<li><p>Installed apps</p>
</li>
<li><p>Database settings</p>
</li>
<li><p>Template settings</p>
</li>
<li><p>Middleware</p>
</li>
</ul>
<h3>urls.py</h3>
<p>Connects URL with view function.</p>
<hr />
<h2>9. First Page Using HttpResponse</h2>
<p>Open:</p>
<pre><code class="language-text">myproject/urls.py
</code></pre>
<p>Write:</p>
<pre><code class="language-python">from django.contrib import admin
from django.urls import path
from django.http import HttpResponse

def home(request):
    return HttpResponse("Welcome to Django Day 1")

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", home),
]
</code></pre>
<p>Open:</p>
<pre><code class="language-text">http://127.0.0.1:8000/
</code></pre>
<p>Output:</p>
<pre><code class="language-text">Welcome to Django Day 1
</code></pre>
<hr />
<h2>10. What is HttpResponse?</h2>
<p>HttpResponse sends a direct response from Django to the browser.</p>
<p>Example:</p>
<pre><code class="language-python">return HttpResponse("Hello Django")
</code></pre>
<p>We can also send simple HTML:</p>
<pre><code class="language-python">return HttpResponse("&lt;h1&gt;Hello Django&lt;/h1&gt;")
</code></pre>
<p>But for real pages, we use HTML templates.</p>
]]></content:encoded></item><item><title><![CDATA[Day 2 at Python]]></title><description><![CDATA[In Day 2, we learned about lists. A list is used to store multiple values in one variable. Example: Now, we will learn list slicing. List slicing means…]]></description><link>https://piankit.hashnode.dev/day-2-at-python</link><guid isPermaLink="true">https://piankit.hashnode.dev/day-2-at-python</guid><dc:creator><![CDATA[Ankit Chapagain]]></dc:creator><pubDate>Wed, 17 Jun 2026 01:44:10 GMT</pubDate><content:encoded><![CDATA[<h2>Topics Covered</h2>
<pre><code class="language-text">1. List Slicing
2. Tuple
3. Dictionary
4. Set
5. Exception Handling
6. Different Types of Exceptions
7. File Handling
8. Login System Using File Handling and Exception Handling
</code></pre>
<hr />
<h1>1. List Slicing</h1>
<p>In Day 2, we learned about lists.</p>
<p>A list is used to store multiple values in one variable.</p>
<p>Example:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange", "grapes"]
</code></pre>
<p>Now, we will learn <strong>list slicing</strong>.</p>
<p>List slicing means taking a specific part of a list.</p>
<hr />
<h2>List Index Revision</h2>
<p>In Python, list index starts from <code>0</code>.</p>
<p>Example:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange"]
</code></pre>
<p>Index values:</p>
<pre><code class="language-text">apple   -&gt; index 0
banana  -&gt; index 1
mango   -&gt; index 2
orange  -&gt; index 3
</code></pre>
<p>Example:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange"]

print(fruits[0])
print(fruits[1])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">apple
banana
</code></pre>
<hr />
<h2>Basic List Slicing</h2>
<p>Example:</p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50]

print(numbers[0:3])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[10, 20, 30]
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">numbers[0:3]
</code></pre>
<p>means start from index <code>0</code> and stop before index <code>3</code>.</p>
<p>It includes:</p>
<pre><code class="language-python">numbers[0]
numbers[1]
numbers[2]
</code></pre>
<p>It does not include index <code>3</code>.</p>
<hr />
<h2>More List Slicing Examples</h2>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50, 60]

print(numbers[0:3])
print(numbers[2:5])
print(numbers[:4])
print(numbers[3:])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[10, 20, 30]
[30, 40, 50]
[10, 20, 30, 40]
[40, 50, 60]
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">numbers[0:3]
</code></pre>
<p>starts from index <code>0</code> and stops before index <code>3</code>.</p>
<pre><code class="language-python">numbers[2:5]
</code></pre>
<p>starts from index <code>2</code> and stops before index <code>5</code>.</p>
<pre><code class="language-python">numbers[:4]
</code></pre>
<p>starts from the beginning and stops before index <code>4</code>.</p>
<pre><code class="language-python">numbers[3:]
</code></pre>
<p>starts from index <code>3</code> and goes until the end.</p>
<hr />
<h2>Negative Indexing</h2>
<p>Python also supports negative indexing.</p>
<p>Example:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange"]

print(fruits[-1])
print(fruits[-2])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">orange
mango
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">-1
</code></pre>
<p>means last item.</p>
<pre><code class="language-python">-2
</code></pre>
<p>means second last item.</p>
<hr />
<h2>Negative Slicing</h2>
<p>Example:</p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50, 60]

print(numbers[-3:])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[40, 50, 60]
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">numbers[-3:]
</code></pre>
<p>means take the last three items.</p>
<hr />
<h2>Slicing With Step</h2>
<p>Example:</p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50, 60]

print(numbers[0:6:2])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[10, 30, 50]
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">numbers[0:6:2]
</code></pre>
<p>means:</p>
<pre><code class="language-text">Start from index 0
Stop before index 6
Move by step 2
</code></pre>
<hr />
<h2>Reverse a List Using Slicing</h2>
<p>Example:</p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50]

print(numbers[::-1])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[50, 40, 30, 20, 10]
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">[::-1]
</code></pre>
<p>is used to reverse a list.</p>
<hr />
<h2>List Slicing Questions</h2>
<h3>Question 1</h3>
<p>Print the first three items from a list.</p>
<p>Solution:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange", "grapes"]

print(fruits[0:3])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">['apple', 'banana', 'mango']
</code></pre>
<hr />
<h3>Question 2</h3>
<p>Print the last two items from a list.</p>
<p>Solution:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange", "grapes"]

print(fruits[-2:])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">['orange', 'grapes']
</code></pre>
<hr />
<h3>Question 3</h3>
<p>Reverse a list using slicing.</p>
<p>Solution:</p>
<pre><code class="language-python">numbers = [1, 2, 3, 4, 5]

print(numbers[::-1])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[5, 4, 3, 2, 1]
</code></pre>
<hr />
<h1>2. Tuple</h1>
<p>A tuple is used to store multiple values in one variable.</p>
<p>It is similar to a list.</p>
<p>But the main difference is:</p>
<pre><code class="language-text">List is changeable.
Tuple is not changeable.
</code></pre>
<p>That means after creating a tuple, we cannot directly add, remove, or change its items.</p>
<p>Example:</p>
<pre><code class="language-python">fruits = ("apple", "banana", "mango")

print(fruits)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">('apple', 'banana', 'mango')
</code></pre>
<p>Here, <code>fruits</code> is a tuple.</p>
<hr />
<h2>Accessing Tuple Items</h2>
<p>Tuple index also starts from <code>0</code>, just like list.</p>
<p>Example:</p>
<pre><code class="language-python">fruits = ("apple", "banana", "mango")

print(fruits[0])
print(fruits[1])
print(fruits[2])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">apple
banana
mango
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">fruits[0]
</code></pre>
<p>gives <code>"apple"</code>.</p>
<pre><code class="language-python">fruits[1]
</code></pre>
<p>gives <code>"banana"</code>.</p>
<pre><code class="language-python">fruits[2]
</code></pre>
<p>gives <code>"mango"</code>.</p>
<hr />
<h2>Tuple Cannot Be Changed</h2>
<p>Example:</p>
<pre><code class="language-python">fruits = ("apple", "banana", "mango")

fruits[0] = "orange"

print(fruits)
</code></pre>
<p>This gives an error.</p>
<p>Because tuple does not allow item change.</p>
<hr />
<h2>Why Use Tuple?</h2>
<p>We use tuple when we want to store values that should not change.</p>
<p>Example:</p>
<pre><code class="language-python">days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
</code></pre>
<p>Days of the week are fixed, so tuple is a good choice.</p>
<p>Another example:</p>
<pre><code class="language-python">location = (26.4525, 87.2718)
</code></pre>
<p>This can store latitude and longitude.</p>
<hr />
<h2>Looping Through Tuple</h2>
<p>Example:</p>
<pre><code class="language-python">fruits = ("apple", "banana", "mango")

for fruit in fruits:
    print(fruit)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">apple
banana
mango
</code></pre>
<p>Explanation:</p>
<p>Tuple is iterable.</p>
<p>So we can use a <code>for</code> loop to read each item one by one.</p>
<hr />
<h2>Tuple Question 1</h2>
<p>Write a program to store five student names in a tuple and print them one by one.</p>
<p>Solution:</p>
<pre><code class="language-python">students = ("Ram", "Sita", "Hari", "Gita", "Shyam")

for student in students:
    print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Ram
Sita
Hari
Gita
Shyam
</code></pre>
<hr />
<h2>Tuple Question 2</h2>
<p>Write a program to find the length of a tuple.</p>
<p>Solution:</p>
<pre><code class="language-python">numbers = (10, 20, 30, 40, 50)

print("Total items:", len(numbers))
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Total items: 5
</code></pre>
<p>Explanation:</p>
<p><code>len()</code> counts how many items are inside the tuple.</p>
<hr />
<h2>Tuple Question 3</h2>
<p>Write a program to check whether <code>"apple"</code> exists in a tuple or not.</p>
<p>Solution:</p>
<pre><code class="language-python">fruits = ("apple", "banana", "mango")

if "apple" in fruits:
    print("Apple exists")
else:
    print("Apple does not exist")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Apple exists
</code></pre>
<hr />
<h1>3. Dictionary</h1>
<p>A dictionary is used to store data in <strong>key-value pairs</strong>.</p>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'name': 'Ram', 'age': 18, 'address': 'Kathmandu'}
</code></pre>
<p>Here:</p>
<pre><code class="language-python">"name"
</code></pre>
<p>is a key.</p>
<pre><code class="language-python">"Ram"
</code></pre>
<p>is the value.</p>
<hr />
<h2>Real-Life Example of Dictionary</h2>
<p>A student has different details:</p>
<pre><code class="language-text">Name: Ram
Age: 18
Address: Kathmandu
</code></pre>
<p>In Python, we can store this like:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}
</code></pre>
<p>Dictionary is useful when we want to store related information.</p>
<hr />
<h2>Accessing Dictionary Values</h2>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

print(student["name"])
print(student["age"])
print(student["address"])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Ram
18
Kathmandu
</code></pre>
<p>Explanation:</p>
<p>We use the key to access the value.</p>
<pre><code class="language-python">student["name"]
</code></pre>
<p>gives <code>"Ram"</code>.</p>
<hr />
<h2>Updating Dictionary Value</h2>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18
}

student["age"] = 19

print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'name': 'Ram', 'age': 19}
</code></pre>
<p>Explanation:</p>
<p>The value of <code>"age"</code> was changed from <code>18</code> to <code>19</code>.</p>
<hr />
<h2>Adding New Key-Value Pair</h2>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18
}

student["address"] = "Kathmandu"

print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'name': 'Ram', 'age': 18, 'address': 'Kathmandu'}
</code></pre>
<p>Explanation:</p>
<p>A new key <code>"address"</code> was added to the dictionary.</p>
<hr />
<h2>Removing Item from Dictionary</h2>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

student.pop("age")

print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'name': 'Ram', 'address': 'Kathmandu'}
</code></pre>
<p>Explanation:</p>
<p><code>pop()</code> removes the item with the given key.</p>
<hr />
<h2>Looping Through Dictionary</h2>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

for key in student:
    print(key)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">name
age
address
</code></pre>
<p>This prints only keys.</p>
<p>To print values:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

for key in student:
    print(student[key])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Ram
18
Kathmandu
</code></pre>
<p>To print both key and value:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

for key, value in student.items():
    print(key, ":", value)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">name : Ram
age : 18
address : Kathmandu
</code></pre>
<hr />
<h2>Dictionary Question 1</h2>
<p>Write a program to store student name, age, and address in a dictionary and print them.</p>
<p>Solution:</p>
<pre><code class="language-python">student = {
    "name": "Sita",
    "age": 19,
    "address": "Pokhara"
}

print("Name:", student["name"])
print("Age:", student["age"])
print("Address:", student["address"])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Name: Sita
Age: 19
Address: Pokhara
</code></pre>
<hr />
<h2>Dictionary Question 2</h2>
<p>Write a program to store product name, price, and quantity. Then calculate total price.</p>
<p>Solution:</p>
<pre><code class="language-python">product = {
    "name": "Pen",
    "price": 20,
    "quantity": 5
}

total = product["price"] * product["quantity"]

print("Product:", product["name"])
print("Total price:", total)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Product: Pen
Total price: 100
</code></pre>
<p>Explanation:</p>
<p>Price is <code>20</code>.</p>
<p>Quantity is <code>5</code>.</p>
<p>So:</p>
<pre><code class="language-python">20 * 5 = 100
</code></pre>
<hr />
<h2>Dictionary Question 3</h2>
<p>Write a program to update a student's marks.</p>
<p>Solution:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "marks": 75
}

student["marks"] = 85

print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'name': 'Ram', 'marks': 85}
</code></pre>
<hr />
<h1>4. Set</h1>
<p>A set is used to store multiple values in one variable.</p>
<p>But set has two important features:</p>
<pre><code class="language-text">1. Set does not allow duplicate values.
2. Set does not maintain fixed order.
</code></pre>
<p>Example:</p>
<pre><code class="language-python">numbers = {10, 20, 30, 40}

print(numbers)
</code></pre>
<p>Output may be:</p>
<pre><code class="language-python">{40, 10, 20, 30}
</code></pre>
<p>The order may be different.</p>
<p>That is normal in set.</p>
<hr />
<h2>Set Does Not Allow Duplicate Values</h2>
<p>Example:</p>
<pre><code class="language-python">numbers = {10, 20, 20, 30, 30, 40}

print(numbers)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{40, 10, 20, 30}
</code></pre>
<p>Explanation:</p>
<p>Duplicate values are automatically removed.</p>
<hr />
<h2>Adding Item to Set</h2>
<p>Example:</p>
<pre><code class="language-python">fruits = {"apple", "banana"}

fruits.add("mango")

print(fruits)
</code></pre>
<p>Output may be:</p>
<pre><code class="language-python">{'apple', 'banana', 'mango'}
</code></pre>
<p>The order may be different.</p>
<hr />
<h2>Removing Item from Set</h2>
<p>Example:</p>
<pre><code class="language-python">fruits = {"apple", "banana", "mango"}

fruits.remove("banana")

print(fruits)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'apple', 'mango'}
</code></pre>
<hr />
<h2>Looping Through Set</h2>
<p>Example:</p>
<pre><code class="language-python">fruits = {"apple", "banana", "mango"}

for fruit in fruits:
    print(fruit)
</code></pre>
<p>Output may be:</p>
<pre><code class="language-python">banana
apple
mango
</code></pre>
<p>Explanation:</p>
<p>Set is iterable.</p>
<p>But the order is not fixed.</p>
<hr />
<h2>Why Use Set?</h2>
<p>Set is useful when we want unique values only.</p>
<p>Example:</p>
<pre><code class="language-python">students = {"Ram", "Sita", "Ram", "Hari", "Sita"}

print(students)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'Ram', 'Sita', 'Hari'}
</code></pre>
<p>Duplicate names are removed.</p>
<hr />
<h2>Set Question 1</h2>
<p>Write a program to remove duplicate numbers from a list.</p>
<p>Solution:</p>
<pre><code class="language-python">numbers = [10, 20, 20, 30, 30, 40]

unique_numbers = set(numbers)

print(unique_numbers)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{40, 10, 20, 30}
</code></pre>
<p>Explanation:</p>
<p>The list contains duplicate values.</p>
<p>When we convert it into a set, duplicate values are removed.</p>
<hr />
<h2>Set Question 2</h2>
<p>Write a program to add a new student name in a set.</p>
<p>Solution:</p>
<pre><code class="language-python">students = {"Ram", "Sita", "Hari"}

students.add("Gita")

print(students)
</code></pre>
<p>Output may be:</p>
<pre><code class="language-python">{'Ram', 'Sita', 'Hari', 'Gita'}
</code></pre>
<hr />
<h2>Set Question 3</h2>
<p>Write a program to check whether <code>"Ram"</code> exists in a set or not.</p>
<p>Solution:</p>
<pre><code class="language-python">students = {"Ram", "Sita", "Hari"}

if "Ram" in students:
    print("Ram exists")
else:
    print("Ram does not exist")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Ram exists
</code></pre>
<hr />
<h1>5. Exception Handling</h1>
<p>Exception handling means handling errors in a program.</p>
<p>Sometimes our program may get an error while running.</p>
<p>Example:</p>
<pre><code class="language-python">a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print(a / b)
</code></pre>
<p>If the user enters:</p>
<pre><code class="language-python">10
0
</code></pre>
<p>Then the program gives an error because division by zero is not allowed.</p>
<p>To handle this kind of error, we use:</p>
<pre><code class="language-python">try
except
</code></pre>
<hr />
<h2>Basic Try Except</h2>
<p>Example:</p>
<pre><code class="language-python">try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))

    result = a / b

    print("Result:", result)

except:
    print("Something went wrong")
</code></pre>
<p>Explanation:</p>
<p>The code that may cause an error is written inside <code>try</code>.</p>
<p>If an error happens, the code inside <code>except</code> runs.</p>
<p>So instead of crashing, the program shows a message.</p>
<hr />
<h2>Better Try Except</h2>
<p>It is better to mention the exact error name.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))

    result = a / b

    print("Result:", result)

except ZeroDivisionError:
    print("Cannot divide by zero")

except ValueError:
    print("Please enter numbers only")
</code></pre>
<p>Explanation:</p>
<p><code>ZeroDivisionError</code> happens when we divide by zero.</p>
<p><code>ValueError</code> happens when we enter invalid number input.</p>
<hr />
<h1>6. Different Types of Exceptions</h1>
<p>Python has many types of exceptions.</p>
<p>Some common exceptions are:</p>
<pre><code class="language-text">1. ValueError
2. ZeroDivisionError
3. FileNotFoundError
4. IndexError
5. KeyError
6. TypeError
7. NameError
8. PermissionError
</code></pre>
<hr />
<h2>1. ValueError</h2>
<p><code>ValueError</code> happens when the value is not valid.</p>
<p>Example:</p>
<pre><code class="language-python">age = int("hello")
</code></pre>
<p>This gives an error because <code>"hello"</code> cannot be converted into an integer.</p>
<p>Correct handling:</p>
<pre><code class="language-python">try:
    age = int(input("Enter your age: "))
    print("Your age is", age)

except ValueError:
    print("Please enter a valid number")
</code></pre>
<hr />
<h2>2. ZeroDivisionError</h2>
<p><code>ZeroDivisionError</code> happens when we divide a number by zero.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    a = 10
    b = 0

    result = a / b

    print(result)

except ZeroDivisionError:
    print("Cannot divide by zero")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Cannot divide by zero
</code></pre>
<hr />
<h2>3. FileNotFoundError</h2>
<p><code>FileNotFoundError</code> happens when we try to read a file that does not exist.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    with open("data.txt", "r") as file:
        data = file.read()
        print(data)

except FileNotFoundError:
    print("File not found")
</code></pre>
<hr />
<h2>4. IndexError</h2>
<p><code>IndexError</code> happens when we try to access an index that does not exist in a list.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    numbers = [10, 20, 30]

    print(numbers[5])

except IndexError:
    print("Index does not exist")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Index does not exist
</code></pre>
<p>Explanation:</p>
<p>The list has only three items.</p>
<p>Available indexes are:</p>
<pre><code class="language-python">0, 1, 2
</code></pre>
<p>But we tried to access index <code>5</code>.</p>
<p>So <code>IndexError</code> happened.</p>
<hr />
<h2>5. KeyError</h2>
<p><code>KeyError</code> happens when we try to access a dictionary key that does not exist.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    student = {
        "name": "Ram",
        "age": 18
    }

    print(student["address"])

except KeyError:
    print("Key does not exist")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Key does not exist
</code></pre>
<p>Explanation:</p>
<p>The dictionary has only:</p>
<pre><code class="language-python">name
age
</code></pre>
<p>But we tried to access:</p>
<pre><code class="language-python">address
</code></pre>
<p>So <code>KeyError</code> happened.</p>
<hr />
<h2>6. TypeError</h2>
<p><code>TypeError</code> happens when we perform an operation with the wrong data type.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    result = "Age: " + 20
    print(result)

except TypeError:
    print("Cannot add string and number directly")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Cannot add string and number directly
</code></pre>
<p>Correct way:</p>
<pre><code class="language-python">result = "Age: " + str(20)
print(result)
</code></pre>
<hr />
<h2>7. NameError</h2>
<p><code>NameError</code> happens when we use a variable that has not been created.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    print(username)

except NameError:
    print("Variable is not defined")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Variable is not defined
</code></pre>
<hr />
<h2>8. PermissionError</h2>
<p><code>PermissionError</code> happens when Python does not have permission to read or write a file.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    with open("/root/data.txt", "w") as file:
        file.write("Hello")

except PermissionError:
    print("You do not have permission to write this file")
</code></pre>
<hr />
<h2>Handling Multiple Exceptions Together</h2>
<p>Example:</p>
<pre><code class="language-python">try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))

    result = a / b

    print("Result:", result)

except ValueError:
    print("Please enter numbers only")

except ZeroDivisionError:
    print("Cannot divide by zero")

except Exception as e:
    print("Something went wrong:", e)
</code></pre>
<p>Explanation:</p>
<p><code>ValueError</code> handles invalid input.</p>
<p><code>ZeroDivisionError</code> handles division by zero.</p>
<p><code>Exception</code> handles any other unexpected error.</p>
<hr />
<h2>Try Except Else</h2>
<p><code>else</code> runs only when there is no error.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    age = int(input("Enter your age: "))

except ValueError:
    print("Please enter a valid number")

else:
    print("Your age is", age)
</code></pre>
<p>Explanation:</p>
<p>If the user enters a correct number, <code>else</code> runs.</p>
<p>If the user enters text like <code>"abc"</code>, <code>except</code> runs.</p>
<hr />
<h2>Try Except Finally</h2>
<p><code>finally</code> always runs.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    number = int(input("Enter a number: "))
    print(number)

except ValueError:
    print("Invalid input")

finally:
    print("Program finished")
</code></pre>
<p>Explanation:</p>
<p>Whether error happens or not, <code>finally</code> runs.</p>
<hr />
<h1>7. File Handling</h1>
<p>File handling means working with files using Python.</p>
<p>Using file handling, we can:</p>
<pre><code class="language-text">1. Create a file
2. Write data into a file
3. Read data from a file
4. Add new data into an existing file
</code></pre>
<hr />
<h2>Opening a File</h2>
<p>Python uses <code>open()</code> to open a file.</p>
<p>Syntax:</p>
<pre><code class="language-python">file = open("filename.txt", "mode")
</code></pre>
<p>Common file modes:</p>
<pre><code class="language-text">"r"  read mode
"w"  write mode
"a"  append mode
</code></pre>
<hr />
<h2>Write Mode</h2>
<p>Write mode is used to write data into a file.</p>
<p>Example:</p>
<pre><code class="language-python">file = open("student.txt", "w")

file.write("Hello, this is my first file.")

file.close()
</code></pre>
<p>Explanation:</p>
<p><code>student.txt</code> is the file name.</p>
<p><code>"w"</code> means write mode.</p>
<p><code>write()</code> writes data into the file.</p>
<p><code>close()</code> closes the file.</p>
<p>Important:</p>
<p>If the file does not exist, Python creates it.</p>
<p>If the file already exists, write mode replaces old content.</p>
<hr />
<h2>Reading a File</h2>
<p>Example:</p>
<pre><code class="language-python">file = open("student.txt", "r")

data = file.read()

print(data)

file.close()
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Hello, this is my first file.
</code></pre>
<p>Explanation:</p>
<p><code>"r"</code> means read mode.</p>
<p><code>read()</code> reads the file content.</p>
<hr />
<h2>Append Mode</h2>
<p>Append mode is used to add new data without deleting old data.</p>
<p>Example:</p>
<pre><code class="language-python">file = open("student.txt", "a")

file.write("\nThis is new line.")

file.close()
</code></pre>
<p>Explanation:</p>
<p><code>"a"</code> means append mode.</p>
<p>It adds new content at the end of the file.</p>
<p><code>\n</code> means new line.</p>
<hr />
<h2>Better Way: Using with open()</h2>
<p>The better way to work with files is:</p>
<pre><code class="language-python">with open("student.txt", "w") as file:
    file.write("Hello Python")
</code></pre>
<p>Here, we do not need to write:</p>
<pre><code class="language-python">file.close()
</code></pre>
<p>Python automatically closes the file.</p>
<hr />
<h2>Read File Using with open()</h2>
<p>Example:</p>
<pre><code class="language-python">with open("student.txt", "r") as file:
    data = file.read()
    print(data)
</code></pre>
<hr />
<h2>File Handling With Exception Handling</h2>
<p>File handling and exception handling are often used together.</p>
<p>Why?</p>
<p>Because file errors can happen.</p>
<p>For example:</p>
<pre><code class="language-text">1. File may not exist.
2. User may enter wrong input.
3. Program may not have permission to read/write file.
</code></pre>
<p>Example:</p>
<pre><code class="language-python">try:
    with open("student.txt", "r") as file:
        data = file.read()
        print(data)

except FileNotFoundError:
    print("File does not exist")
</code></pre>
<p>Explanation:</p>
<p>If <code>student.txt</code> exists, Python reads the file.</p>
<p>If it does not exist, <code>FileNotFoundError</code> happens.</p>
<p>Then <code>except</code> block runs.</p>
<hr />
<h1>8. File-Based Login System</h1>
<p>Now we will create a simple login system using file handling.</p>
<p>In this system:</p>
<pre><code class="language-text">Each user will have their own file.
The username will be used as the file name.
The password will be saved inside that file.
</code></pre>
<p>Example:</p>
<p>If username is:</p>
<pre><code class="language-python">ram
</code></pre>
<p>Then Python creates:</p>
<pre><code class="language-python">ram.txt
</code></pre>
<p>Inside <code>ram.txt</code>, the password is saved.</p>
<hr />
<h2>Full Login System Code</h2>
<pre><code class="language-python">def register():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        print("Username already exists")
        file.close()

    except FileNotFoundError:
        with open(f"{username}.txt", "w") as f:
            f.write(password)

        print("User registered successfully")

    except Exception as e:
        print("Something went wrong while registering:", e)


def login():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        file.close()

    except FileNotFoundError:
        print("User not found")
        return

    except Exception as e:
        print("Something went wrong while opening user file:", e)
        return

    try:
        with open(f"{username}.txt", "r") as f:
            checkpass = f.readline()

            if password == checkpass:
                print("Welcome")
            else:
                print("Sorry, incorrect password")

    except Exception as e:
        print("Something went wrong while checking password:", e)


def ask():
    x = input("Do you want to register or login? Press r for register and l for login: ")

    if x == "r":
        register()

    elif x == "l":
        login()

    else:
        print("Invalid choice")


ask()
</code></pre>
<hr />
<h1>9. Explanation of Login System</h1>
<h2>Register Function</h2>
<pre><code class="language-python">def register():
</code></pre>
<p>This function is used to register a new user.</p>
<pre><code class="language-python">username = input("Enter your username: ")
password = input("Enter your password: ")
</code></pre>
<p>Here, the program asks the user to enter username and password.</p>
<hr />
<h2>Checking If Username Already Exists</h2>
<pre><code class="language-python">try:
    file = open(f"{username}.txt", "r")
    print("Username already exists")
    file.close()
</code></pre>
<p>Here, the program tries to open a file with the username.</p>
<p>Example:</p>
<p>If username is:</p>
<pre><code class="language-python">ram
</code></pre>
<p>Then it tries to open:</p>
<pre><code class="language-python">ram.txt
</code></pre>
<p>If the file exists, it means the username is already registered.</p>
<p>So the program prints:</p>
<pre><code class="language-python">Username already exists
</code></pre>
<hr />
<h2>Creating File for New User</h2>
<pre><code class="language-python">except FileNotFoundError:
    with open(f"{username}.txt", "w") as f:
        f.write(password)

    print("User registered successfully")
</code></pre>
<p>If the file does not exist, Python gives <code>FileNotFoundError</code>.</p>
<p>That means the username is new.</p>
<p>So the program creates a new file and saves the password inside it.</p>
<p>Example:</p>
<p>If username is:</p>
<pre><code class="language-python">sita
</code></pre>
<p>Then file name becomes:</p>
<pre><code class="language-python">sita.txt
</code></pre>
<p>And inside that file, the password is saved.</p>
<hr />
<h2>Login Function</h2>
<pre><code class="language-python">def login():
</code></pre>
<p>This function is used to login an existing user.</p>
<pre><code class="language-python">username = input("Enter your username: ")
password = input("Enter your password: ")
</code></pre>
<p>The program asks for username and password.</p>
<hr />
<h2>Checking If User Exists</h2>
<pre><code class="language-python">try:
    file = open(f"{username}.txt", "r")
    file.close()
</code></pre>
<p>The program tries to open the user's file.</p>
<p>If the file exists, the user exists.</p>
<hr />
<h2>User Not Found</h2>
<pre><code class="language-python">except FileNotFoundError:
    print("User not found")
    return
</code></pre>
<p>If the file does not exist, the program prints:</p>
<pre><code class="language-python">User not found
</code></pre>
<p>Here, <code>return</code> is used to stop the function.</p>
<p>This is better than <code>exit()</code> because <code>exit()</code> closes the whole program immediately.</p>
<hr />
<h2>Reading Saved Password</h2>
<pre><code class="language-python">with open(f"{username}.txt", "r") as f:
    checkpass = f.readline()
</code></pre>
<p>This opens the user's file and reads the saved password.</p>
<p>The saved password is stored in:</p>
<pre><code class="language-python">checkpass
</code></pre>
<hr />
<h2>Checking Password</h2>
<pre><code class="language-python">if password == checkpass:
    print("Welcome")
else:
    print("Sorry, incorrect password")
</code></pre>
<p>If entered password and saved password are same, login is successful.</p>
<p>Otherwise, it prints incorrect password.</p>
<hr />
<h1>10. Simpler Version Like Your Original Code</h1>
<p>This is very close to your original code.</p>
<pre><code class="language-python">def register():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        print("Username already exists")
        file.close()

    except:
        with open(f"{username}.txt", "w") as f:
            f.write(password)

        print("User registered successfully")


def login():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        file.close()

    except:
        print("User not found")
        return

    with open(f"{username}.txt", "r") as f:
        checkpass = f.readline()

        if password == checkpass:
            print("Welcome")
        else:
            print("Sorry, incorrect password")


def ask():
    x = input("Do you want to register or login? Press r for register and l for login: ")

    if x == "r":
        register()
    else:
        login()


ask()
</code></pre>
<p>This version is okay for beginners.</p>
<p>But for better practice, this is preferred:</p>
<pre><code class="language-python">except FileNotFoundError:
</code></pre>
<p>instead of only:</p>
<pre><code class="language-python">except:
</code></pre>
<p>Because <code>except:</code> catches all errors, but <code>FileNotFoundError</code> catches only file-not-found error.</p>
<hr />
<h1>11. Important Note About This Login System</h1>
<p>This login system is only for learning.</p>
<p>It teaches:</p>
<pre><code class="language-text">1. Function
2. Input
3. File handling
4. Try and except
5. User already exists
6. User not found
7. Password checking
</code></pre>
<p>But in real websites or real applications, passwords should not be saved directly like this.</p>
<p>In real projects, passwords should be hashed before saving.</p>
<p>For now, this is good for beginner-level Python file handling practice.</p>
<hr />
<h1>12. Class Explanation Flow</h1>
<p>You can explain the login system like this:</p>
<pre><code class="language-text">When registering:
Python checks if username.txt exists.
If it exists, the user already exists.
If it does not exist, Python creates the file and saves the password.

When logging in:
Python checks if username.txt exists.
If it does not exist, user not found.
If it exists, Python reads the saved password.
Then it compares the saved password with the entered password.
</code></pre>
<hr />
<h1>13. Day 3 Practice Questions</h1>
<h2>List Slicing Questions</h2>
<ol>
<li><p>Create a list of 10 numbers and print the first 5 numbers.</p>
</li>
<li><p>Print the last 3 numbers from a list.</p>
</li>
<li><p>Reverse a list using slicing.</p>
</li>
<li><p>Print every second item from a list.</p>
</li>
</ol>
<hr />
<h2>Tuple Questions</h2>
<ol>
<li><p>Create a tuple of five fruits and print each fruit.</p>
</li>
<li><p>Create a tuple of numbers and find its length.</p>
</li>
<li><p>Check whether <code>"Python"</code> exists in a tuple.</p>
</li>
<li><p>Try to change a tuple item and observe the error.</p>
</li>
</ol>
<hr />
<h2>Dictionary Questions</h2>
<ol>
<li><p>Create a dictionary for a student with name, age, class, and address.</p>
</li>
<li><p>Create a dictionary for a product and calculate total price.</p>
</li>
<li><p>Update the marks of a student in a dictionary.</p>
</li>
<li><p>Print all keys and values from a dictionary.</p>
</li>
</ol>
<hr />
<h2>Set Questions</h2>
<ol>
<li><p>Create a set of numbers with duplicate values and print it.</p>
</li>
<li><p>Add a new item to a set.</p>
</li>
<li><p>Remove an item from a set.</p>
</li>
<li><p>Convert a list with duplicate values into a set.</p>
</li>
</ol>
<hr />
<h2>Exception Handling Questions</h2>
<ol>
<li><p>Take two numbers and divide them. Handle <code>ZeroDivisionError</code>.</p>
</li>
<li><p>Take age from user. Handle <code>ValueError</code>.</p>
</li>
<li><p>Try to access an invalid list index. Handle <code>IndexError</code>.</p>
</li>
<li><p>Try to access an invalid dictionary key. Handle <code>KeyError</code>.</p>
</li>
<li><p>Try to read a file that does not exist. Handle <code>FileNotFoundError</code>.</p>
</li>
</ol>
<hr />
<h2>File Handling Questions</h2>
<ol>
<li><p>Create a file named <code>message.txt</code> and write <code>"Hello Python"</code> into it.</p>
</li>
<li><p>Read and print the content of <code>message.txt</code>.</p>
</li>
<li><p>Append three student names into <code>students.txt</code>.</p>
</li>
<li><p>Read a file and handle <code>FileNotFoundError</code>.</p>
</li>
</ol>
<hr />
<h2>Final Project Question</h2>
<p>Create a login system using file handling.</p>
<p>Requirements:</p>
<pre><code class="language-text">1. Register user.
2. Login user.
3. If user already exists, show message.
4. If user does not exist, show user not found.
5. If password is correct, show welcome.
6. If password is wrong, show incorrect password.
7. Use try and except.
8. Store each user password in username.txt file.
</code></pre>
<hr />
<h1>14. Day 3 Final Summary</h1>
<p>Today we learned:</p>
<pre><code class="language-text">List slicing:
Used to get part of a list.

Tuple:
Used to store multiple values that should not change.

Dictionary:
Used to store data in key-value pairs.

Set:
Used to store unique values.

Exception handling:
Used to handle errors without crashing the program.

File handling:
Used to create, read, write, and append files.

Login system:
Used file handling and exception handling together.
</code></pre>
<p>Final simple memory:</p>
<pre><code class="language-text">List      -&gt; changeable collection
Tuple     -&gt; unchangeable collection
Dictionary -&gt; key-value collection
Set       -&gt; unique value collection
try-except -&gt; error handling
File      -&gt; permanent data storage
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Second Day At Workshop Python]]></title><description><![CDATA[After installing Python and setting up the virtual environment, the first program we usually write is: A variable is a name used to store data in a…]]></description><link>https://piankit.hashnode.dev/second-day-at-workshop-python</link><guid isPermaLink="true">https://piankit.hashnode.dev/second-day-at-workshop-python</guid><dc:creator><![CDATA[Ankit Chapagain]]></dc:creator><pubDate>Tue, 16 Jun 2026 06:11:20 GMT</pubDate><content:encoded><![CDATA[<p>After installing Python and setting up the virtual environment, the first program we usually write is:</p>
<pre><code class="language-plaintext">print("Hello, World!")
</code></pre>
<h2>1. Variables</h2>
<p>A variable is a name used to store data in a program.</p>
<p>When we write a program, we need to store different values like name, age, marks, price, address, total amount, and so on. For that, we use variables.</p>
<p>Example:</p>
<pre><code class="language-plaintext">name = "Ram"
age = 18
</code></pre>
<p>Here, <code>name</code> is a variable that stores <code>"Ram"</code>.</p>
<p><code>age</code> is a variable that stores <code>18</code>.</p>
<p>We can print the values stored in variables using <code>print()</code>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">name = "Ram"
age = 18

print(name)
print(age)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Ram
18
</code></pre>
<p>In Python, we do not need to write the data type manually. Python automatically understands the type of value.</p>
<p>For example:</p>
<pre><code class="language-plaintext">name = "Sita"
age = 20
</code></pre>
<p>Python understands that <code>"Sita"</code> is text and <code>20</code> is a number.</p>
<p>A variable name should be meaningful.</p>
<p>Good variable names:</p>
<pre><code class="language-plaintext">student_name = "Ram"
total_marks = 450
product_price = 500
</code></pre>
<p>Bad variable names:</p>
<pre><code class="language-plaintext">a = "Ram"
x = 450
p = 500
</code></pre>
<p>These are not wrong, but they are not clear. Good variable names help us understand the program easily.</p>
<p>Question:</p>
<p>Write a program to store student name, age, and address. Then print all details.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">name = "Sita"
age = 19
address = "Pokhara"

print("Name:", name)
print("Age:", age)
print("Address:", address)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Name: Sita
Age: 19
Address: Pokhara
</code></pre>
<p>Explanation:</p>
<p>Here, we created three variables.</p>
<p><code>name</code> stores the student name.</p>
<p><code>age</code> stores the student age.</p>
<p><code>address</code> stores the student address.</p>
<p>Then we used <code>print()</code> to display all values.</p>
<h2>2. Data Types</h2>
<p>Data type means the type of value stored in a variable.</p>
<p>Different types of data are used in programming. Some values are numbers, some are text, some are decimal numbers, and some are true or false values.</p>
<p>Common data types in Python are:</p>
<p><code>int</code> means integer or whole number.</p>
<p>Example:</p>
<pre><code class="language-plaintext">age = 20
</code></pre>
<p><code>float</code> means decimal number.</p>
<p>Example:</p>
<pre><code class="language-plaintext">price = 99.5
</code></pre>
<p><code>str</code> means string or text.</p>
<p>Example:</p>
<pre><code class="language-plaintext">name = "Ram"
</code></pre>
<p><code>bool</code> means boolean value. It can be either <code>True</code> or <code>False</code>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">is_student = True
</code></pre>
<p><code>list</code> means collection of multiple values.</p>
<p>Example:</p>
<pre><code class="language-plaintext">marks = [80, 90, 85]
</code></pre>
<p>We can check the data type of any variable using <code>type()</code>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">age = 20
price = 99.5
name = "Ram"
is_student = True
marks = [80, 90, 85]

print(type(age))
print(type(price))
print(type(name))
print(type(is_student))
print(type(marks))
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">&lt;class 'int'&gt;
&lt;class 'float'&gt;
&lt;class 'str'&gt;
&lt;class 'bool'&gt;
&lt;class 'list'&gt;
</code></pre>
<p>Question:</p>
<p>Write a program to create variables of different data types and print their types.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">name = "Hari"
age = 21
height = 5.7
passed = True
numbers = [10, 20, 30]

print(type(name))
print(type(age))
print(type(height))
print(type(passed))
print(type(numbers))
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">&lt;class 'str'&gt;
&lt;class 'int'&gt;
&lt;class 'float'&gt;
&lt;class 'bool'&gt;
&lt;class 'list'&gt;
</code></pre>
<p>Explanation:</p>
<p><code>"Hari"</code> is text, so its type is <code>str</code>.</p>
<p><code>21</code> is a whole number, so its type is <code>int</code>.</p>
<p><code>5.7</code> is a decimal number, so its type is <code>float</code>.</p>
<p><code>True</code> is a boolean value, so its type is <code>bool</code>.</p>
<p><code>[10, 20, 30]</code> is a list, so its type is <code>list</code>.</p>
<h2>3. Input</h2>
<p>Input means taking data from the user.</p>
<p>In real programs, values are not always fixed. Sometimes we need to ask the user to enter data.</p>
<p>For example, in a billing system, the user may enter product name, quantity, and price.</p>
<p>In Python, we use <code>input()</code> to take input from the user.</p>
<p>Example:</p>
<pre><code class="language-plaintext">name = input("Enter your name: ")

print("Hello", name)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Enter your name: Ram
Hello Ram
</code></pre>
<p>Here, the program asks the user to enter a name. The entered value is stored in the variable <code>name</code>.</p>
<p>Important point:</p>
<p><code>input()</code> always takes value as a string.</p>
<p>Example:</p>
<pre><code class="language-plaintext">age = input("Enter your age: ")

print(type(age))
</code></pre>
<p>If the user enters <code>20</code>, Python still treats it as string.</p>
<p>Output:</p>
<pre><code class="language-plaintext">&lt;class 'str'&gt;
</code></pre>
<p>That is why we need type casting when we want to perform mathematical calculations.</p>
<p>Question:</p>
<p>Write a program to take name and city from the user and print them.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">name = input("Enter your name: ")
city = input("Enter your city: ")

print("Your name is", name)
print("You live in", city)
</code></pre>
<p>Example Output:</p>
<pre><code class="language-plaintext">Enter your name: Ram
Enter your city: Kathmandu
Your name is Ram
You live in Kathmandu
</code></pre>
<p>Explanation:</p>
<p>The first <code>input()</code> takes the user's name.</p>
<p>The second <code>input()</code> takes the user's city.</p>
<p>Then both values are printed using <code>print()</code>.</p>
<h2>4. Type Casting</h2>
<p>Type casting means converting one data type into another data type.</p>
<p>Sometimes data comes in one type, but we need it in another type.</p>
<p>For example, <code>input()</code> gives value as string. But if we want to add two numbers, we must convert them into integer or float.</p>
<p>Common type casting functions are:</p>
<p><code>int()</code> converts value into integer.</p>
<p><code>float()</code> converts value into decimal number.</p>
<p><code>str()</code> converts value into string.</p>
<p>Example:</p>
<pre><code class="language-plaintext">num = "10"
num = int(num)

print(num)
print(type(num))
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">10
&lt;class 'int'&gt;
</code></pre>
<p>Here, <code>"10"</code> was a string. After using <code>int()</code>, it became an integer.</p>
<p>Why type casting is needed:</p>
<pre><code class="language-plaintext">a = input("Enter first number: ")
b = input("Enter second number: ")

print(a + b)
</code></pre>
<p>If user enters <code>10</code> and <code>20</code>, output will be:</p>
<pre><code class="language-plaintext">1020
</code></pre>
<p>This happens because both values are strings. Python joins strings using <code>+</code>.</p>
<p>Correct way:</p>
<pre><code class="language-plaintext">a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print(a + b)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">30
</code></pre>
<p>Question:</p>
<p>Write a program to take two numbers from the user and print their sum.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

total = a + b

print("Total is", total)
</code></pre>
<p>Example Output:</p>
<pre><code class="language-plaintext">Enter first number: 10
Enter second number: 20
Total is 30
</code></pre>
<p>Explanation:</p>
<p><code>input()</code> takes values from the user.</p>
<p><code>int()</code> converts those values into numbers.</p>
<p>Then <code>+</code> adds the numbers.</p>
<p>Without <code>int()</code>, Python would join the values as strings.</p>
<h2>5. Operators</h2>
<p>Operators are symbols used to perform operations.</p>
<p>For example:</p>
<pre><code class="language-plaintext">a = 10
b = 5

print(a + b)
</code></pre>
<p>Here, <code>+</code> is an operator.</p>
<p>It adds two numbers.</p>
<p>Common arithmetic operators are:</p>
<p><code>+</code> is used for addition.</p>
<p><code>-</code> is used for subtraction.</p>
<p><code>*</code> is used for multiplication.</p>
<p><code>/</code> is used for division.</p>
<p><code>//</code> is used for floor division.</p>
<p><code>%</code> is used to find remainder.</p>
<p><code>**</code> is used for power.</p>
<p>Example:</p>
<pre><code class="language-plaintext">a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">13
7
30
3.3333333333333335
3
1
1000
</code></pre>
<p>Explanation:</p>
<p><code>10 + 3</code> gives <code>13</code>.</p>
<p><code>10 - 3</code> gives <code>7</code>.</p>
<p><code>10 * 3</code> gives <code>30</code>.</p>
<p><code>10 / 3</code> gives decimal division result.</p>
<p><code>10 // 3</code> gives only the whole number part.</p>
<p><code>10 % 3</code> gives the remainder.</p>
<p><code>10 ** 3</code> means 10 to the power 3.</p>
<p>Question:</p>
<p>Write a program to take two numbers and perform addition, subtraction, multiplication, and division.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
</code></pre>
<p>Example Output:</p>
<pre><code class="language-plaintext">Enter first number: 20
Enter second number: 5
Addition: 25
Subtraction: 15
Multiplication: 100
Division: 4.0
</code></pre>
<p>Explanation:</p>
<p>The program takes two numbers from the user.</p>
<p>Then it uses different operators to perform calculations.</p>
<p><code>+</code> adds the values.</p>
<p><code>-</code> subtracts the values.</p>
<p><code>*</code> multiplies the values.</p>
<p><code>/</code> divides the values.</p>
<h2>6. Conditional Statement</h2>
<p>Conditional statement is used to make decisions in a program.</p>
<p>Sometimes we want to run code only when a condition is true.</p>
<p>For example:</p>
<p>If age is greater than or equal to 18, the person can vote.</p>
<p>Otherwise, the person cannot vote.</p>
<p>Example:</p>
<pre><code class="language-plaintext">age = 18

if age &gt;= 18:
    print("You can vote")
else:
    print("You cannot vote")
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">You can vote
</code></pre>
<p>Here, Python checks the condition:</p>
<pre><code class="language-plaintext">age &gt;= 18
</code></pre>
<p>If the condition is true, the code inside <code>if</code> runs.</p>
<p>If the condition is false, the code inside <code>else</code> runs.</p>
<p>Example with marks:</p>
<pre><code class="language-plaintext">marks = 75

if marks &gt;= 40:
    print("Pass")
else:
    print("Fail")
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Pass
</code></pre>
<p>Question:</p>
<p>Write a program to check whether a number is even or odd.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">num = int(input("Enter a number: "))

if num % 2 == 0:
    print("Even number")
else:
    print("Odd number")
</code></pre>
<p>Example Output:</p>
<pre><code class="language-plaintext">Enter a number: 7
Odd number
</code></pre>
<p>Explanation:</p>
<p>The <code>%</code> operator gives the remainder.</p>
<p>If a number is divided by <code>2</code> and the remainder is <code>0</code>, the number is even.</p>
<p>For example:</p>
<pre><code class="language-plaintext">8 % 2
</code></pre>
<p>gives <code>0</code>, so <code>8</code> is even.</p>
<p>But:</p>
<pre><code class="language-plaintext">7 % 2
</code></pre>
<p>gives <code>1</code>, so <code>7</code> is odd.</p>
<h2>7. For Loop</h2>
<p>A for loop is used to repeat code.</p>
<p>When we want to do the same work again and again, we use loops.</p>
<p>Example:</p>
<pre><code class="language-plaintext">for i in range(5):
    print(i)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">0
1
2
3
4
</code></pre>
<p>Here, <code>range(5)</code> gives numbers from <code>0</code> to <code>4</code>.</p>
<p>The loop runs one time for each number.</p>
<p>First time, <code>i</code> is <code>0</code>.</p>
<p>Second time, <code>i</code> is <code>1</code>.</p>
<p>Third time, <code>i</code> is <code>2</code>.</p>
<p>This continues until <code>4</code>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">for i in range(1, 6):
    print(i)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">1
2
3
4
5
</code></pre>
<p>Here, <code>range(1, 6)</code> starts from <code>1</code> and stops before <code>6</code>.</p>
<p>So it prints <code>1</code> to <code>5</code>.</p>
<p>Example with step:</p>
<pre><code class="language-plaintext">for i in range(1, 10, 2):
    print(i)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">1
3
5
7
9
</code></pre>
<p>Here:</p>
<p><code>1</code> is the starting value.</p>
<p><code>10</code> is the stopping value, but it is not included.</p>
<p><code>2</code> is the step value.</p>
<p>Question:</p>
<p>Write a program to print numbers from 1 to 10 using for loop.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">for i in range(1, 11):
    print(i)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">1
2
3
4
5
6
7
8
9
10
</code></pre>
<p>Explanation:</p>
<p><code>range(1, 11)</code> starts from <code>1</code>.</p>
<p>It stops before <code>11</code>.</p>
<p>So the loop prints numbers from <code>1</code> to <code>10</code>.</p>
<p>Each value is stored in <code>i</code> one by one and printed.</p>
<h2>8. Iterable</h2>
<p>An iterable is something that we can loop through.</p>
<p>In simple words, iterable means a value that gives items one by one.</p>
<p>Examples of iterables are:</p>
<p>String</p>
<p>List</p>
<p>Range</p>
<p>Tuple</p>
<p>Dictionary</p>
<p>A string is iterable because we can get each letter one by one.</p>
<p>Example:</p>
<pre><code class="language-plaintext">name = "Ram"

for letter in name:
    print(letter)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">R
a
m
</code></pre>
<p>Here, Python reads the string letter by letter.</p>
<p>A list is also iterable.</p>
<p>Example:</p>
<pre><code class="language-plaintext">fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print(fruit)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">apple
banana
mango
</code></pre>
<p>Here, Python reads the list item by item.</p>
<p>So, when we use a for loop, we mostly loop through an iterable.</p>
<p>Question:</p>
<p>Write a program to print each letter of the word Python.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">word = "Python"

for letter in word:
    print(letter)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">P
y
t
h
o
n
</code></pre>
<p>Explanation:</p>
<p>The word <code>"Python"</code> is a string.</p>
<p>A string is iterable.</p>
<p>So the for loop takes one letter at a time and prints it.</p>
<h2>9. List</h2>
<p>A list is used to store multiple values in one variable.</p>
<p>Example:</p>
<pre><code class="language-plaintext">fruits = ["apple", "banana", "mango"]
</code></pre>
<p>Here, <code>fruits</code> is a list.</p>
<p>It stores three values.</p>
<p>Lists are useful when we have many related values.</p>
<p>Example:</p>
<pre><code class="language-plaintext">marks = [80, 90, 75, 85]
</code></pre>
<p>Instead of creating many variables like this:</p>
<pre><code class="language-plaintext">mark1 = 80
mark2 = 90
mark3 = 75
mark4 = 85
</code></pre>
<p>We can store all marks in one list.</p>
<pre><code class="language-plaintext">marks = [80, 90, 75, 85]
</code></pre>
<p>Accessing list items:</p>
<p>List index starts from <code>0</code>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">fruits = ["apple", "banana", "mango"]

print(fruits[0])
print(fruits[1])
print(fruits[2])
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">apple
banana
mango
</code></pre>
<p>Here:</p>
<p><code>fruits[0]</code> gives <code>"apple"</code>.</p>
<p><code>fruits[1]</code> gives <code>"banana"</code>.</p>
<p><code>fruits[2]</code> gives <code>"mango"</code>.</p>
<p>Adding item to list:</p>
<pre><code class="language-plaintext">fruits = ["apple", "banana"]

fruits.append("mango")

print(fruits)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">['apple', 'banana', 'mango']
</code></pre>
<p><code>append()</code> adds a new item at the end of the list.</p>
<p>Removing item from list:</p>
<pre><code class="language-plaintext">fruits = ["apple", "banana", "mango"]

fruits.remove("banana")

print(fruits)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">['apple', 'mango']
</code></pre>
<p><code>remove()</code> removes the given item from the list.</p>
<p>Looping through list:</p>
<pre><code class="language-plaintext">fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print(fruit)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">apple
banana
mango
</code></pre>
<p>Question:</p>
<p>Write a program to find total marks from a list.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">marks = [80, 90, 75, 85]

total = 0

for mark in marks:
    total = total + mark

print("Total marks:", total)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Total marks: 330
</code></pre>
<p>Explanation:</p>
<p><code>marks</code> is a list.</p>
<p>At first, <code>total</code> is <code>0</code>.</p>
<p>The for loop takes each mark from the list.</p>
<p>First, <code>80</code> is added to total.</p>
<p>Then, <code>90</code> is added.</p>
<p>Then, <code>75</code> is added.</p>
<p>Then, <code>85</code> is added.</p>
<p>Finally, the total becomes <code>330</code>.</p>
<h2>10. Function</h2>
<p>A function is a reusable block of code.</p>
<p>When we write the same code again and again, our program becomes long and difficult to manage.</p>
<p>To solve this problem, we use functions.</p>
<p>A function is created using <code>def</code>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">def greet():
    print("Hello")

greet()
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello
</code></pre>
<p>Explanation:</p>
<p><code>def</code> is used to define a function.</p>
<p><code>greet</code> is the function name.</p>
<p>The code inside the function runs only when we call the function.</p>
<p>Here:</p>
<pre><code class="language-plaintext">greet()
</code></pre>
<p>calls the function.</p>
<p>Why do we use functions?</p>
<p>We use functions to avoid repeating code.</p>
<p>We use functions to make code clean.</p>
<p>We use functions to divide a big program into small parts.</p>
<p>We use functions to reuse code many times.</p>
<p>Function with parameter:</p>
<p>A parameter is a value received by a function.</p>
<p>Example:</p>
<pre><code class="language-plaintext">def greet(name):
    print("Hello", name)

greet("Ram")
greet("Sita")
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello Ram
Hello Sita
</code></pre>
<p>Explanation:</p>
<p>Here, <code>name</code> is a parameter.</p>
<p>When we call the function, we send a value.</p>
<p>In <code>greet("Ram")</code>, <code>"Ram"</code> is sent to the function.</p>
<p>So the function prints:</p>
<pre><code class="language-plaintext">Hello Ram
</code></pre>
<p>Function with return:</p>
<p><code>return</code> sends value back from the function.</p>
<p>Example:</p>
<pre><code class="language-plaintext">def add(a, b):
    return a + b

result = add(10, 20)

print(result)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">30
</code></pre>
<p>Explanation:</p>
<p>The function receives two numbers.</p>
<p>It adds them.</p>
<p>Then it returns the answer.</p>
<p>The returned answer is stored in <code>result</code>.</p>
<p>Difference between print and return:</p>
<p><code>print()</code> only displays the value.</p>
<p><code>return</code> sends the value back so we can use it later.</p>
<p>Example:</p>
<pre><code class="language-plaintext">def add(a, b):
    return a + b

answer = add(10, 20)

final = answer + 50

print(final)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">80
</code></pre>
<p>Here, the returned value is used again in another calculation.</p>
<p>Function Question 1:</p>
<p>Create a function to add two numbers.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">def add(a, b):
    total = a + b
    return total

answer = add(10, 20)

print("Sum is", answer)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Sum is 30
</code></pre>
<p>Explanation:</p>
<p>The function name is <code>add</code>.</p>
<p>It receives two values: <code>a</code> and <code>b</code>.</p>
<p>Inside the function, both values are added.</p>
<p>The result is returned using <code>return</code>.</p>
<p>Then the returned value is stored in <code>answer</code>.</p>
<p>Function Question 2:</p>
<p>Create a function to check whether a number is even or odd.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">def check_even_odd(num):
    if num % 2 == 0:
        return "Even"
    else:
        return "Odd"

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

result = check_even_odd(number)

print(result)
</code></pre>
<p>Example Output:</p>
<pre><code class="language-plaintext">Enter a number: 8
Even
</code></pre>
<p>Explanation:</p>
<p>The function receives a number.</p>
<p>Inside the function, we check:</p>
<pre><code class="language-plaintext">num % 2 == 0
</code></pre>
<p>If the remainder is <code>0</code>, the number is even.</p>
<p>Otherwise, the number is odd.</p>
<p>The function returns <code>"Even"</code> or <code>"Odd"</code>.</p>
<p>Function Question 3:</p>
<p>Create a function to find total marks from a list.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">def calculate_total(marks):
    total = 0

    for mark in marks:
        total = total + mark

    return total

student_marks = [80, 90, 75, 85]

answer = calculate_total(student_marks)

print("Total marks:", answer)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Total marks: 330
</code></pre>
<p>Explanation:</p>
<p>The function receives a list of marks.</p>
<p>At first, <code>total</code> is <code>0</code>.</p>
<p>The for loop goes through each mark.</p>
<p>Each mark is added to total.</p>
<p>Finally, the function returns the total marks.</p>
<p>Function Question 4:</p>
<p>Create a function to find the largest number from a list.</p>
<p>Solution:</p>
<pre><code class="language-plaintext">def find_largest(numbers):
    largest = numbers[0]

    for number in numbers:
        if number &gt; largest:
            largest = number

    return largest

numbers = [10, 25, 7, 90, 45]

answer = find_largest(numbers)

print("Largest number is", answer)
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Largest number is 90
</code></pre>
<p>Explanation:</p>
<p>The function receives a list of numbers.</p>
<p>At first, we assume the first number is the largest.</p>
<pre><code class="language-plaintext">largest = numbers[0]
</code></pre>
<p>Then the for loop checks each number.</p>
<p>If any number is greater than the current largest number, we update the largest value.</p>
<p>At the end, the function returns the largest number.</p>
<p>Tricky Function Question:</p>
<p>What will be the output of this program?</p>
<pre><code class="language-plaintext">def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item("apple"))
print(add_item("banana"))
print(add_item("mango"))
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">['apple']
['apple', 'banana']
['apple', 'banana', 'mango']
</code></pre>
<p>Explanation:</p>
<p>This is tricky because the default list <code>items=[]</code> is created only once.</p>
<p>It is not created again every time the function is called.</p>
<p>So every function call uses the same list.</p>
<p>First call:</p>
<pre><code class="language-plaintext">add_item("apple")
</code></pre>
<p>The list becomes:</p>
<pre><code class="language-plaintext">['apple']
</code></pre>
<p>Second call:</p>
<pre><code class="language-plaintext">add_item("banana")
</code></pre>
<p>The same list becomes:</p>
<pre><code class="language-plaintext">['apple', 'banana']
</code></pre>
<p>Third call:</p>
<pre><code class="language-plaintext">add_item("mango")
</code></pre>
<p>The same list becomes:</p>
<pre><code class="language-plaintext">['apple', 'banana', 'mango']
</code></pre>
<p>Correct way:</p>
<pre><code class="language-plaintext">def add_item(item, items=None):
    if items is None:
        itexuu

    items.append(item)
    return items

print(add_item("apple"))
print(add_item("banana"))
print(add_item("mango"))
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">['apple']
['banana']
['mango']
</code></pre>
<p>Explanation:</p>
<p>Here, we used <code>None</code> instead of an empty list.</p>
<p>Every time the function is called without a list, a new empty list is created.</p>
<p>So old values are not reused.</p>
]]></content:encoded></item><item><title><![CDATA[Day 5 topics]]></title><description><![CDATA[a name Until now, we learned: In Python, we can store student data like this: This works while the program is running. But after the program is closed…]]></description><link>https://piankit.hashnode.dev/day-5-topics</link><guid isPermaLink="true">https://piankit.hashnode.dev/day-5-topics</guid><dc:creator><![CDATA[Ankit Chapagain]]></dc:creator><pubDate>Sun, 24 May 2026 02:20:48 GMT</pubDate><content:encoded><![CDATA[<p>a name</p>
<hr />
<pre><code class="language-plaintext">1\. Quick revision of Python and OOP
2. Very simple database concept
3. Creating table and selecting data using SQLite
4. Linux terminal commands
5. Basic Vim commands
6. Git introduction
7. GitHub introduction
8. Git staging area
9. Git commit and snapshot
10. Basic Git workflow practice
</code></pre>
<hr />
<h1>Part 1: Quick Python Revision</h1>
<p>Until now, we learned:</p>
<pre><code class="language-plaintext">Variables
Data types
Conditionals
Loops
Functions
File handling
Exception handling
Dictionaries
OOP basics
</code></pre>
<p>In Python, we can store student data like this:</p>
<pre><code class="language-plaintext">student = {
    "name": "Ram",
    "age": 18,
    "marks": 80
}
</code></pre>
<p>This works while the program is running.</p>
<p>But after the program is closed, this data is lost.</p>
<p>So we need a database.</p>
<hr />
<h1>Part 2: Little Bit of Database</h1>
<h2>What is a database?</h2>
<p>A <strong>database</strong> is a place where we store data permanently in an organized way.</p>
<p>Example:</p>
<p>A school may store:</p>
<pre><code class="language-plaintext">Student name
Age
Class
Marks
Address
Phone number
</code></pre>
<p>A database stores data in tables.</p>
<hr />
<h2>What is a table?</h2>
<p>A table is like a register.</p>
<p>Example:</p>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>marks</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>Ram</td>
<td>18</td>
<td>80</td>
</tr>
<tr>
<td>2</td>
<td>Sita</td>
<td>19</td>
<td>90</td>
</tr>
</tbody></table>
<p>Here:</p>
<pre><code class="language-plaintext">id, name, age, marks = columns
Ram and Sita data = rows
</code></pre>
<hr />
<h2>What is SQLite?</h2>
<p>SQLite is a simple database.</p>
<p>It is good for beginners because:</p>
<pre><code class="language-plaintext">It is simple.
It stores data in one file.
Python already supports it.
No extra installation is needed.
</code></pre>
<p>Example database file:</p>
<pre><code class="language-plaintext">students.db
</code></pre>
<hr />
<h1>Part 3: Simple SQLite Code</h1>
<p>For Day 5, we are not learning full CRUD.</p>
<p>We are only learning:</p>
<pre><code class="language-plaintext">Create table
Insert simple data
Select/read data
</code></pre>
<h2>Simple code</h2>
<pre><code class="language-plaintext">import sqlite3

connection = sqlite3.connect("students.db")
cursor = connection.cursor()

cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    age INTEGER,
    marks REAL
)
""")

cursor.execute("""
INSERT INTO students (name, age, marks)
VALUES ('Ram', 18, 80)
""")

cursor.execute("SELECT * FROM students")

students = cursor.fetchall()

for student in students:
    print(student)

connection.commit()
connection.close()
</code></pre>
<h2>Explanation</h2>
<pre><code class="language-plaintext">import sqlite3
</code></pre>
<p>This imports the SQLite database module.</p>
<pre><code class="language-plaintext">connection = sqlite3.connect("students.db")
</code></pre>
<p>This connects Python to the database.</p>
<p>If <code>students.db</code> does not exist, Python creates it.</p>
<pre><code class="language-plaintext">cursor = connection.cursor()
</code></pre>
<p>Cursor is used to run SQL commands.</p>
<pre><code class="language-plaintext">CREATE TABLE IF NOT EXISTS students
</code></pre>
<p>This creates a table named <code>students</code>.</p>
<pre><code class="language-plaintext">SELECT * FROM students
</code></pre>
<p>This reads all data from the students table.</p>
<hr />
<h1>Part 4: Now Main Topic: Git and GitHub</h1>
<p>Before learning Git, students should understand one problem.</p>
<p>Imagine you are building a Python project.</p>
<p>Day 1:</p>
<pre><code class="language-plaintext">print("Hello")
</code></pre>
<p>Day 2:</p>
<p>You add a menu.</p>
<p>Day 3:</p>
<p>You add student management.</p>
<p>Day 4:</p>
<p>You add database.</p>
<p>Day 5:</p>
<p>Something breaks.</p>
<p>Now the problem is:</p>
<pre><code class="language-plaintext">Which file changed?
When did it change?
What was working before?
Can we go back to old code?
How can multiple students work on the same project?
</code></pre>
<p>This is where Git helps.</p>
<hr />
<h1>Part 5: What is Git?</h1>
<p>Git is a <strong>version control system</strong>.</p>
<p>Simple meaning:</p>
<p><strong>Git tracks changes in our project.</strong></p>
<p>It remembers the history of our code.</p>
<p>With Git, we can see:</p>
<pre><code class="language-plaintext">What changed
When it changed
Who changed it
Why it changed
Previous versions of the project
</code></pre>
<hr />
<h2>Simple definition for students</h2>
<p>Git is a tool that helps us save different versions of our project properly.</p>
<p>Instead of doing this:</p>
<pre><code class="language-plaintext">project-final
project-final-new
project-final-latest
project-final-real
project-final-last
</code></pre>
<p>We use Git.</p>
<p>Git manages versions professionally.</p>
<hr />
<h1>Part 6: Why is Git Important?</h1>
<p>Git is important because it helps us:</p>
<pre><code class="language-plaintext">Track code changes
Save project history
Go back to old versions
Work safely on new features
Work in teams
Upload code to GitHub
Avoid losing code
</code></pre>
<hr />
<h2>Real-life example</h2>
<p>Suppose you are working on a student management system.</p>
<p>Your project is working properly.</p>
<p>Then you try to add a database.</p>
<p>After adding the database, the project stops working.</p>
<p>Without Git:</p>
<pre><code class="language-plaintext">You may not know what went wrong.
You may not know which file changed.
You may have to rewrite code again.
</code></pre>
<p>With Git:</p>
<pre><code class="language-plaintext">You can check previous versions.
You can compare changes.
You can return to the working version.
</code></pre>
<hr />
<h1>Part 7: What is GitHub?</h1>
<p>GitHub is a website/platform where we can store our Git projects online.</p>
<p>Simple meaning:</p>
<pre><code class="language-plaintext">Git = tool on your computer
GitHub = website to store and share Git projects
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">Git tracks your project locally.
GitHub stores your project online.
</code></pre>
<hr />
<h2>Simple analogy</h2>
<pre><code class="language-plaintext">Git = camera
GitHub = online photo album
</code></pre>
<p>Git takes snapshots of your code.</p>
<p>GitHub stores those snapshots online.</p>
<hr />
<h1>Part 8: Git vs GitHub</h1>
<table>
<thead>
<tr>
<th>Git</th>
<th>GitHub</th>
</tr>
</thead>
<tbody><tr>
<td>Installed on your computer</td>
<td>Website/platform</td>
</tr>
<tr>
<td>Tracks code changes</td>
<td>Stores code online</td>
</tr>
<tr>
<td>Works locally</td>
<td>Works on the internet</td>
</tr>
<tr>
<td>Can be used without GitHub</td>
<td>Needs Git project</td>
</tr>
<tr>
<td>Tool</td>
<td>Hosting service</td>
</tr>
</tbody></table>
<p>Simple line:</p>
<p><strong>Git is the tool. GitHub is the place where we upload Git projects.</strong></p>
<hr />
<h1>Part 9: Basic Linux Commands for Git</h1>
<p>Before using Git, students should know basic terminal commands.</p>
<h2>Check current folder</h2>
<pre><code class="language-c">pwd
</code></pre>
<p>This shows where you are.</p>
<hr />
<h2>List files and folders</h2>
<pre><code class="language-plaintext">ls
</code></pre>
<p>Show hidden files also:</p>
<pre><code class="language-plaintext">ls -a
</code></pre>
<hr />
<h2>Change folder</h2>
<pre><code class="language-plaintext">cd folder_name
</code></pre>
<p>Go back one folder:</p>
<pre><code class="language-plaintext">cd ..
</code></pre>
<p>Go to home folder:</p>
<pre><code class="language-plaintext">cd ~
</code></pre>
<hr />
<h2>Create folder</h2>
<pre><code class="language-plaintext">mkdir my_project
</code></pre>
<hr />
<h2>Create file</h2>
<pre><code class="language-plaintext">touch app.py
</code></pre>
<hr />
<h2>Clear terminal</h2>
<pre><code class="language-plaintext">clear
</code></pre>
<hr />
<h2>Remove file</h2>
<pre><code class="language-plaintext">rm app.py
</code></pre>
<hr />
<h2>Remove folder</h2>
<pre><code class="language-plaintext">rm -r my_project
</code></pre>
<p>Be careful with <code>rm</code>.</p>
<hr />
<h2>Show file content</h2>
<pre><code class="language-plaintext">cat app.py
</code></pre>
<hr />
<h2>Run Python file</h2>
<pre><code class="language-plaintext">python3 app.py
</code></pre>
<p>or:</p>
<pre><code class="language-plaintext">python app.py
</code></pre>
<hr />
<h1>Part 10: Basic Vim Commands</h1>
<p>Sometimes Git may open Vim.</p>
<p>For example, when writing commit messages.</p>
<p>Students do not need to master Vim now.</p>
<p>They only need basic survival commands.</p>
<hr />
<h2>Open file in Vim</h2>
<pre><code class="language-plaintext">vim app.py
</code></pre>
<hr />
<h2>Insert mode</h2>
<p>Press:</p>
<pre><code class="language-plaintext">i
</code></pre>
<p>Now you can write.</p>
<hr />
<h2>Save and exit</h2>
<p>Press:</p>
<pre><code class="language-plaintext">Esc
</code></pre>
<p>Then type:</p>
<pre><code class="language-plaintext">:wq
</code></pre>
<p>Then press Enter.</p>
<hr />
<h2>Exit without saving</h2>
<p>Press:</p>
<pre><code class="language-plaintext">Esc
</code></pre>
<p>Then type:</p>
<pre><code class="language-plaintext">:q!
</code></pre>
<p>Then press Enter.</p>
<hr />
<h2>Save only</h2>
<p>Press:</p>
<pre><code class="language-plaintext">Esc
</code></pre>
<p>Then type:</p>
<pre><code class="language-plaintext">:w
</code></pre>
<hr />
<h1>Part 11: Git Installation Check</h1>
<p>To check if Git is installed:</p>
<pre><code class="language-plaintext">git --version
</code></pre>
<p>Example output:</p>
<pre><code class="language-plaintext">git version 2.39.0
</code></pre>
<p>If this shows a version, Git is installed.</p>
<hr />
<h1>Part 12: Git Configuration</h1>
<p>Before using Git, we should set name and email.</p>
<pre><code class="language-plaintext">git config --global user.name "Your Name"
git config --global user.email "your@email.com"
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">git config --global user.name "Ram Sharma"
git config --global user.email "ram@gmail.com"
</code></pre>
<p>To check configuration:</p>
<pre><code class="language-plaintext">git config --list
</code></pre>
<hr />
<h1>Part 13: What is a Git Repository?</h1>
<p>A Git repository means a project folder where Git is tracking changes.</p>
<p>To create a Git repository:</p>
<pre><code class="language-plaintext">git init
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">mkdir student_project
cd student_project
git init
</code></pre>
<p>Now Git starts tracking this project.</p>
<hr />
<h2>What happens after <code>git init</code>?</h2>
<p>Git creates a hidden folder named:</p>
<pre><code class="language-plaintext">.git
</code></pre>
<p>This <code>.git</code> folder stores Git history and information.</p>
<p>To see it:</p>
<pre><code class="language-plaintext">ls -a
</code></pre>
<p>You will see:</p>
<pre><code class="language-plaintext">.git
</code></pre>
<p>Important:</p>
<p>Do not delete the <code>.git</code> folder unless you want to remove Git tracking from the project.</p>
<hr />
<h1>Part 14: Git Workflow</h1>
<p>Git has three main areas:</p>
<pre><code class="language-plaintext">1\. Working Directory
2. Staging Area
3. Repository
</code></pre>
<p>This is very important.</p>
<hr />
<h2>1. Working Directory</h2>
<p>This is your normal project folder.</p>
<p>This is where you create and edit files.</p>
<p>Example:</p>
<pre><code class="language-plaintext">app.py
main.py
students.db
README.md
</code></pre>
<p>When you change a file, the change first stays in the working directory.</p>
<hr />
<h2>2. Staging Area</h2>
<p>The staging area is a preparation area.</p>
<p>Before saving changes permanently in Git history, we first add them to staging.</p>
<p>Command:</p>
<pre><code class="language-plaintext">git add app.py
</code></pre>
<p>or:</p>
<pre><code class="language-plaintext">git add .
</code></pre>
<hr />
<h2>3. Repository</h2>
<p>The repository is where Git permanently saves the committed history.</p>
<p>Command:</p>
<pre><code class="language-plaintext">git commit -m "message"
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">git commit -m "Add student management code"
</code></pre>
<hr />
<h1>Part 15: What is Git Staging?</h1>
<p>Staging means choosing which changes should go into the next commit.</p>
<p>Imagine you changed three files:</p>
<pre><code class="language-plaintext">app.py
database.py
notes.txt
</code></pre>
<p>But you only want to save <code>app.py</code> and <code>database.py</code> in one commit.</p>
<p>You can do:</p>
<pre><code class="language-plaintext">git add app.py
git add database.py
git commit -m "Add database feature"
</code></pre>
<p>Now <code>notes.txt</code> is not included in that commit.</p>
<p>So staging gives control.</p>
<hr />
<h2>Simple classroom analogy</h2>
<p>Imagine you are packing a school bag.</p>
<p>On the table, you have:</p>
<pre><code class="language-plaintext">Math book
Science book
Copy
Pen
Lunch box
Football
</code></pre>
<p>You do not put everything into the bag.</p>
<p>You choose only what is needed.</p>
<p>That choosing step is like <strong>staging</strong>.</p>
<pre><code class="language-plaintext">Table = working directory
Selected items = staging area
Packed bag = commit
</code></pre>
<hr />
<h1>Part 16: What is a Git Commit?</h1>
<p>A commit is a saved version of your project.</p>
<p>When we commit, Git saves the staged changes into history.</p>
<p>Command:</p>
<pre><code class="language-plaintext">git commit -m "Initial commit"
</code></pre>
<p>The message should explain what changed.</p>
<p>Good commit messages:</p>
<pre><code class="language-plaintext">Add student model
Create database table
Fix login error
Update README file
</code></pre>
<p>Bad commit messages:</p>
<pre><code class="language-plaintext">done
final
changes
abc
test
</code></pre>
<hr />
<h1>Part 17: What is a Snapshot in Git?</h1>
<p>A snapshot is a saved picture of your project at a specific time.</p>
<p>When you commit, Git creates a snapshot.</p>
<p>Example:</p>
<pre><code class="language-plaintext">Commit 1: Initial project
Commit 2: Add student management
Commit 3: Add database connection
Commit 4: Fix marks calculation
</code></pre>
<p>Each commit is like a photo of your project.</p>
<p>If something breaks later, you can check old snapshots.</p>
<hr />
<h2>Simple analogy</h2>
<p>Imagine taking photos while building a house.</p>
<p>Photo 1:</p>
<pre><code class="language-plaintext">Empty land
</code></pre>
<p>Photo 2:</p>
<pre><code class="language-plaintext">Foundation completed
</code></pre>
<p>Photo 3:</p>
<pre><code class="language-plaintext">Walls completed
</code></pre>
<p>Photo 4:</p>
<pre><code class="language-plaintext">Roof completed
</code></pre>
<p>Git commit is like taking these photos of your code.</p>
<hr />
<h1>Part 18: Important Git Commands</h1>
<h2>1. Initialize Git</h2>
<pre><code class="language-plaintext">git init
</code></pre>
<p>Starts Git tracking in a folder.</p>
<hr />
<h2>2. Check status</h2>
<pre><code class="language-plaintext">git status
</code></pre>
<p>Shows current condition of files.</p>
<p>It tells:</p>
<pre><code class="language-plaintext">Untracked files
Modified files
Staged files
Clean working tree
</code></pre>
<hr />
<h2>3. Add file to staging</h2>
<pre><code class="language-plaintext">git add app.py
</code></pre>
<p>Add all changes:</p>
<pre><code class="language-plaintext">git add .
</code></pre>
<hr />
<h2>4. Commit changes</h2>
<pre><code class="language-plaintext">git commit -m "Initial commit"
</code></pre>
<p>This saves staged changes into Git history.</p>
<hr />
<h2>5. View commit history</h2>
<pre><code class="language-plaintext">git log
</code></pre>
<p>Short version:</p>
<pre><code class="language-plaintext">git log --oneline
</code></pre>
<hr />
<h2>6. See changes</h2>
<pre><code class="language-plaintext">git diff
</code></pre>
<p>This shows what changed before staging.</p>
<hr />
<h2>7. See staged changes</h2>
<pre><code class="language-plaintext">git diff --staged
</code></pre>
<p>This shows what is already staged.</p>
<hr />
<h1>Part 19: First Git Practice</h1>
<p>Ask students to do this step by step.</p>
<h2>Step 1: Create project folder</h2>
<pre><code class="language-plaintext">mkdir git_practice
cd git_practice
</code></pre>
<h2>Step 2: Initialize Git</h2>
<pre><code class="language-plaintext">git init
</code></pre>
<h2>Step 3: Create Python file</h2>
<pre><code class="language-plaintext">touch app.py
</code></pre>
<h2>Step 4: Write Python code</h2>
<p>Open file:</p>
<pre><code class="language-plaintext">vim app.py
</code></pre>
<p>Press:</p>
<pre><code class="language-plaintext">i
</code></pre>
<p>Write:</p>
<pre><code class="language-plaintext">print("Hello Git")
</code></pre>
<p>Save and exit:</p>
<pre><code class="language-plaintext">Esc
:wq
</code></pre>
<hr />
<h2>Step 5: Check status</h2>
<pre><code class="language-plaintext">git status
</code></pre>
<p>Git will show <code>app.py</code> as untracked.</p>
<p>Untracked means:</p>
<pre><code class="language-plaintext">Git sees the file, but Git is not tracking it yet.
</code></pre>
<hr />
<h2>Step 6: Add to staging</h2>
<pre><code class="language-plaintext">git add app.py
</code></pre>
<p>Now check status again:</p>
<pre><code class="language-plaintext">git status
</code></pre>
<p>Now the file is staged.</p>
<hr />
<h2>Step 7: Commit</h2>
<pre><code class="language-plaintext">git commit -m "Create first Python file"
</code></pre>
<p>Now Git has saved the first snapshot.</p>
<hr />
<h2>Step 8: Check history</h2>
<pre><code class="language-plaintext">git log --oneline
</code></pre>
<p>You will see your commit.</p>
<hr />
<h1>Part 20: Second Git Practice</h1>
<p>Now edit <code>app.py</code>.</p>
<pre><code class="language-plaintext">vim app.py
</code></pre>
<p>Change code to:</p>
<pre><code class="language-plaintext">print("Hello Git")
print("This is my second line")
</code></pre>
<p>Save and exit.</p>
<p>Now check status:</p>
<pre><code class="language-plaintext">git status
</code></pre>
<p>Git will show that <code>app.py</code> is modified.</p>
<hr />
<h2>See what changed</h2>
<pre><code class="language-plaintext">git diff
</code></pre>
<p>This shows the new line added.</p>
<hr />
<h2>Stage and commit again</h2>
<pre><code class="language-plaintext">git add app.py
git commit -m "Add second print message"
</code></pre>
<p>Now check history:</p>
<pre><code class="language-plaintext">git log --oneline
</code></pre>
<p>You will see two commits.</p>
<hr />
<h1>Part 21: Understanding File States in Git</h1>
<p>A file in Git can have different states.</p>
<h2>1. Untracked</h2>
<p>Git sees the file but is not tracking it.</p>
<p>Example:</p>
<pre><code class="language-plaintext">touch notes.txt
git status
</code></pre>
<p><code>notes.txt</code> will be untracked.</p>
<hr />
<h2>2. Modified</h2>
<p>Git is already tracking the file, but you changed it.</p>
<p>Example:</p>
<pre><code class="language-plaintext">vim app.py
git status
</code></pre>
<p>Now <code>app.py</code> may show as modified.</p>
<hr />
<h2>3. Staged</h2>
<p>The file is ready to be committed.</p>
<p>Example:</p>
<pre><code class="language-plaintext">git add app.py
git status
</code></pre>
<p>Now it is staged.</p>
<hr />
<h2>4. Committed</h2>
<p>The file is saved in Git history.</p>
<p>Example:</p>
<pre><code class="language-plaintext">git commit -m "Update app"
</code></pre>
<p>Now it is committed.</p>
<hr />
<h1>Part 22: Simple Git Flow Diagram</h1>
<pre><code class="language-plaintext">Working Directory
      |
      | git add
      v
Staging Area
      |
      | git commit
      v
Repository / Git History
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">Write code
↓
git status
↓
git add .
↓
git status
↓
git commit -m "message"
↓
git log --oneline
</code></pre>
<hr />
<h1>Part 23: What is GitHub Account?</h1>
<p>GitHub is an online platform.</p>
<p>To use GitHub, students need:</p>
<pre><code class="language-plaintext">GitHub account
Repository on GitHub
Git installed locally
Internet connection
</code></pre>
<p>GitHub helps us:</p>
<pre><code class="language-plaintext">Upload projects
Share projects
Collaborate with team
Show portfolio
Submit assignments
Work with companies
</code></pre>
<hr />
<h1>Part 24: What is a Remote Repository?</h1>
<p>A remote repository is a Git repository stored online.</p>
<p>Example:</p>
<pre><code class="language-plaintext">Local repository = project on your laptop
Remote repository = project on GitHub
</code></pre>
<p>To connect local project with GitHub, we use:</p>
<pre><code class="language-plaintext">git remote add origin repository_url
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">git remote add origin https://github.com/username/project-name.git
</code></pre>
<hr />
<h1>Part 25: Push and Pull</h1>
<h2>Push</h2>
<p>Push means sending local commits to GitHub.</p>
<pre><code class="language-plaintext">git push
</code></pre>
<p>Simple meaning:</p>
<pre><code class="language-plaintext">Laptop to GitHub
</code></pre>
<hr />
<h2>Pull</h2>
<p>Pull means bringing latest code from GitHub to your laptop.</p>
<pre><code class="language-plaintext">git pull
</code></pre>
<p>Simple meaning:</p>
<pre><code class="language-plaintext">GitHub to laptop
</code></pre>
<hr />
<h2>Clone</h2>
<p>Clone means downloading a GitHub project to your laptop.</p>
<pre><code class="language-plaintext">git clone repository_url
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">git clone https://github.com/username/project-name.git
</code></pre>
<hr />
<h1>Part 26: First GitHub Upload Practice</h1>
<h2>Step 1: Create a repository on GitHub</h2>
<p>Go to GitHub and create a new repository.</p>
<p>Example name:</p>
<pre><code class="language-plaintext">git-practice
</code></pre>
<p>Do not add README from GitHub for now.</p>
<hr />
<h2>Step 2: Connect local project to GitHub</h2>
<p>Inside your local project folder:</p>
<pre><code class="language-plaintext">git remote add origin https://github.com/username/git-practice.git
</code></pre>
<hr />
<h2>Step 3: Rename branch to main</h2>
<pre><code class="language-plaintext">git branch -M main
</code></pre>
<hr />
<h2>Step 4: Push code</h2>
<pre><code class="language-plaintext">git push -u origin main
</code></pre>
<p>Now the code is uploaded to GitHub.</p>
<hr />
<h1>Part 27: Common GitHub Upload Flow</h1>
<p>After the first upload, the regular flow is:</p>
<pre><code class="language-plaintext">git status
git add .
git commit -m "Your message"
git push
</code></pre>
<p>This is the most common Git workflow.</p>
<p>Students should memorize this flow.</p>
<hr />
<h1>Part 28: README File</h1>
<p>A <code>README.md</code> file explains the project.</p>
<p>Create README:</p>
<pre><code class="language-plaintext">touch README.md
</code></pre>
<p>Write:</p>
<pre><code class="language-plaintext"># Student Management System

This is a simple Python project.

## Features

- Add student
- View student
- Learn Git and GitHub
</code></pre>
<p>Then:</p>
<pre><code class="language-plaintext">git add README.md
git commit -m "Add README file"
git push
</code></pre>
<hr />
<h1>Part 29: What is <code>.gitignore</code>?</h1>
<p><code>.gitignore</code> tells Git which files not to track.</p>
<p>Example:</p>
<p>We may not want to track:</p>
<pre><code class="language-plaintext">__pycache__
.env
database files
temporary files
</code></pre>
<p>Create <code>.gitignore</code>:</p>
<pre><code class="language-plaintext">touch .gitignore
</code></pre>
<p>Example content:</p>
<pre><code class="language-plaintext">__pycache__/
*.pyc
.env
</code></pre>
<p>Then commit it:</p>
<pre><code class="language-plaintext">git add .gitignore
git commit -m "Add gitignore file"
</code></pre>
<hr />
<h1>Part 30: Important Git Terms</h1>
<h2>Repository</h2>
<p>A Git-tracked project.</p>
<h2>Commit</h2>
<p>A saved version of the project.</p>
<h2>Staging</h2>
<p>Preparing selected changes for commit.</p>
<h2>Snapshot</h2>
<p>A saved picture of project state at a point in time.</p>
<h2>Remote</h2>
<p>Online Git repository, usually on GitHub.</p>
<h2>Push</h2>
<p>Send local commits to GitHub.</p>
<h2>Pull</h2>
<p>Bring latest changes from GitHub to local computer.</p>
<h2>Clone</h2>
<p>Download a GitHub repository.</p>
<h2>Branch</h2>
<p>A separate line of development.</p>
<p>Branches can be covered more deeply on Day 6.</p>
<hr />
<h1>Part 31: Common Mistakes Students Make</h1>
<h2>Mistake 1: Forgetting <code>git add</code></h2>
<p>Wrong:</p>
<pre><code class="language-plaintext">git commit -m "Update code"
</code></pre>
<p>If files are not staged, commit may not include changes.</p>
<p>Correct:</p>
<pre><code class="language-plaintext">git add .
git commit -m "Update code"
</code></pre>
<hr />
<h2>Mistake 2: Bad commit messages</h2>
<p>Bad:</p>
<pre><code class="language-plaintext">git commit -m "done"
</code></pre>
<p>Good:</p>
<pre><code class="language-plaintext">git commit -m "Add student database table"
</code></pre>
<hr />
<h2>Mistake 3: Using GitHub without committing</h2>
<p>Students may think code goes to GitHub automatically.</p>
<p>It does not.</p>
<p>Correct flow:</p>
<pre><code class="language-plaintext">git add .
git commit -m "message"
git push
</code></pre>
<hr />
<h2>Mistake 4: Confusing Git and GitHub</h2>
<p>Remember:</p>
<pre><code class="language-plaintext">Git is local.
GitHub is online.
</code></pre>
<hr />
<h1>Part 32: Class Activity</h1>
<p>Give students this task:</p>
<h2>Task: Create and upload a simple Python project</h2>
<h3>Requirements</h3>
<p>Create a folder:</p>
<pre><code class="language-plaintext">student_git_project
</code></pre>
<p>Create a file:</p>
<pre><code class="language-plaintext">app.py
</code></pre>
<p>Write:</p>
<pre><code class="language-plaintext">print("Student Management System")

name = input("Enter student name: ")
age = input("Enter student age: ")

print("Name:", name)
print("Age:", age)
</code></pre>
<p>Then use Git:</p>
<pre><code class="language-plaintext">git init
git status
git add app.py
git commit -m "Create student input program"
</code></pre>
<p>Create <code>README.md</code>:</p>
<pre><code class="language-plaintext"># Student Git Project

This is a simple Python project for learning Git and GitHub.
</code></pre>
<p>Then:</p>
<pre><code class="language-plaintext">git add README.md
git commit -m "Add README"
</code></pre>
<p>Finally upload to GitHub:</p>
<pre><code class="language-plaintext">git remote add origin https://github.com/username/student_git_project.git
git branch -M main
git push -u origin main
</code></pre>
<hr />
<h1>Part 33: Teacher Explanation Script</h1>
<p>You can explain like this:</p>
<p>"Until now, we wrote Python code and saved files normally. But in real projects, simply saving files is not enough. We need to track changes. We need to know what changed, when it changed, and how to go back if something breaks. Git helps us manage the history of our project. GitHub helps us store that project online and share it with others."</p>
<p>Then say:</p>
<p>"Git works in three steps. First, we write code in the working directory. Second, we stage the changes using <code>git add</code>. Third, we save the changes using <code>git commit</code>. A commit is like a snapshot of our project."</p>
<hr />
<h1>Part 34: Final Summary for Students</h1>
<p>Today we learned:</p>
<pre><code class="language-plaintext">Database stores data permanently.
SQLite is a simple database.
Git tracks code changes.
GitHub stores Git projects online.
Git and GitHub are different.
Git has working directory, staging area, and repository.
Staging means preparing changes before commit.
Commit means saving a snapshot.
Push means uploading to GitHub.
Pull means downloading latest changes from GitHub.
Clone means copying a GitHub project to local computer.
</code></pre>
<hr />
<h1>Day 5 Homework</h1>
<h2>Homework 1: Git practice</h2>
<p>Create a new folder:</p>
<pre><code class="language-plaintext">day5_homework
</code></pre>
<p>Create a Python file:</p>
<pre><code class="language-plaintext">main.py
</code></pre>
<p>Write any simple Python program.</p>
<p>Then use:</p>
<pre><code class="language-plaintext">git init
git add .
git commit -m "Initial homework commit"
</code></pre>
<p>Modify the file and commit again:</p>
<pre><code class="language-plaintext">git add .
git commit -m "Update homework program"
</code></pre>
<p>Check history:</p>
<pre><code class="language-plaintext">git log --oneline
</code></pre>
<hr />
<h2>Homework 2: GitHub practice</h2>
<p>Upload the homework project to GitHub.</p>
<p>Commands:</p>
<pre><code class="language-plaintext">git remote add origin your_repository_url
git branch -M main
git push -u origin main
</code></pre>
<hr />
<h2>Homework 3: Write answers</h2>
<p>Students should write short answers:</p>
<pre><code class="language-plaintext">1\. What is Git?
2. What is GitHub?
3. What is the difference between Git and GitHub?
4. What is staging?
5. What is a commit?
6. What is a snapshot?
7. What is push?
8. What is pull?
9. What is clone?
10. Why is Git important?
</code></pre>
<hr />
<h1>Best One-Line Explanation</h1>
<p><strong>Git helps us track project history, and GitHub helps us store and share that project online.</strong></p>
]]></content:encoded></item><item><title><![CDATA[Day 4 Python Notes]]></title><description><![CDATA[What is a Database? What is SQLite? Difference Between File Handling and Database Basic SQL Commands Python with SQLite Create Table Insert Data Fetch Data]]></description><link>https://piankit.hashnode.dev/day-4-python-notes</link><guid isPermaLink="true">https://piankit.hashnode.dev/day-4-python-notes</guid><dc:creator><![CDATA[Ankit Chapagain]]></dc:creator><pubDate>Fri, 22 May 2026 15:10:19 GMT</pubDate><content:encoded><![CDATA[<h1>Topic: Python with SQLite Database</h1>
<h2>Topics Covered</h2>
<ol>
<li><p>What is a Database?</p>
</li>
<li><p>What is SQLite?</p>
</li>
<li><p>Difference Between File Handling and Database</p>
</li>
<li><p>Basic SQL Commands</p>
</li>
<li><p>Python with SQLite</p>
</li>
<li><p>Create Table</p>
</li>
<li><p>Insert Data</p>
</li>
<li><p>Fetch Data</p>
</li>
<li><p>Update Data</p>
</li>
<li><p>Delete Data</p>
</li>
<li><p>Complete SQLite CRUD Program</p>
</li>
<li><p>Practice Questions</p>
</li>
<li><p>Day 4 Summary</p>
</li>
</ol>
<hr />
<h1>1. What is a Database?</h1>
<p>A database is used to store data in an organized way.</p>
<p>In Day 3, we stored data using files.</p>
<p>Example:</p>
<pre><code class="language-plaintext">ram.txt
sita.txt
hari.txt
</code></pre>
<p>But file handling becomes difficult when we have lots of data.</p>
<p>Example:</p>
<p>If we want to store student details:</p>
<pre><code class="language-plaintext">Name: Ram
Age: 18
Address: Kathmandu
</code></pre>
<p>Using files is possible, but searching, updating, and deleting data becomes hard.</p>
<p>So we use a database.</p>
<p>A database stores data in tables.</p>
<p>Example:</p>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>address</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>Ram</td>
<td>18</td>
<td>Kathmandu</td>
</tr>
<tr>
<td>2</td>
<td>Sita</td>
<td>19</td>
<td>Pokhara</td>
</tr>
<tr>
<td>3</td>
<td>Hari</td>
<td>20</td>
<td>Biratnagar</td>
</tr>
</tbody></table>
<hr />
<h1>2. What is SQLite?</h1>
<p>SQLite is a small and simple database.</p>
<p>It stores data inside a single file.</p>
<p>Example:</p>
<pre><code class="language-plaintext">school.db
</code></pre>
<p>SQLite is good for learning because:</p>
<ol>
<li><p>It is simple.</p>
</li>
<li><p>It does not need server setup.</p>
</li>
<li><p>It works directly with Python.</p>
</li>
<li><p>Python already has SQLite built in.</p>
</li>
</ol>
<p>We do not need to install anything extra.</p>
<p>We only need to import:</p>
<pre><code class="language-plaintext">import sqlite3
</code></pre>
<hr />
<h1>3. File Handling vs Database</h1>
<h2>File Handling</h2>
<p>In file handling, we store data in text files.</p>
<p>Example:</p>
<pre><code class="language-plaintext">ram.txt
</code></pre>
<p>Inside the file:</p>
<pre><code class="language-plaintext">12345
</code></pre>
<p>This is okay for small programs.</p>
<p>But it is not good for storing many users or many student records.</p>
<h2>Database</h2>
<p>In a database, data is stored in tables.</p>
<p>Example:</p>
<table>
<thead>
<tr>
<th>id</th>
<th>username</th>
<th>password</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>ram</td>
<td>12345</td>
</tr>
<tr>
<td>2</td>
<td>sita</td>
<td>abc123</td>
</tr>
</tbody></table>
<p>Database makes it easier to:</p>
<ol>
<li><p>Add data</p>
</li>
<li><p>View data</p>
</li>
<li><p>Search data</p>
</li>
<li><p>Update data</p>
</li>
<li><p>Delete data</p>
</li>
</ol>
<p>These operations are called CRUD.</p>
<hr />
<h1>4. What is CRUD?</h1>
<p>CRUD means:</p>
<table>
<thead>
<tr>
<th>Letter</th>
<th>Meaning</th>
<th>Example</th>
</tr>
</thead>
<tbody><tr>
<td>C</td>
<td>Create</td>
<td>Add new student</td>
</tr>
<tr>
<td>R</td>
<td>Read</td>
<td>View students</td>
</tr>
<tr>
<td>U</td>
<td>Update</td>
<td>Edit student data</td>
</tr>
<tr>
<td>D</td>
<td>Delete</td>
<td>Remove student</td>
</tr>
</tbody></table>
<p>In database:</p>
<table>
<thead>
<tr>
<th>CRUD</th>
<th>SQL Command</th>
</tr>
</thead>
<tbody><tr>
<td>Create</td>
<td><code>INSERT</code></td>
</tr>
<tr>
<td>Read</td>
<td><code>SELECT</code></td>
</tr>
<tr>
<td>Update</td>
<td><code>UPDATE</code></td>
</tr>
<tr>
<td>Delete</td>
<td><code>DELETE</code></td>
</tr>
</tbody></table>
<hr />
<h1>5. What is SQL?</h1>
<p>SQL means <strong>Structured Query Language</strong>.</p>
<p>SQL is used to talk with the database.</p>
<p>We use SQL commands to create tables, insert data, read data, update data, and delete data.</p>
<p>Example:</p>
<pre><code class="language-plaintext">SELECT * FROM students;
</code></pre>
<p>This means:</p>
<p>Show all data from the students table.</p>
<hr />
<h1>6. Basic SQL Commands</h1>
<h2>1. CREATE TABLE</h2>
<p>Used to create a new table.</p>
<p>Example:</p>
<pre><code class="language-plaintext">CREATE TABLE students (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    age INTEGER,
    address TEXT
);
</code></pre>
<p>Explanation:</p>
<pre><code class="language-plaintext">id INTEGER PRIMARY KEY AUTOINCREMENT
</code></pre>
<p>This creates an ID that increases automatically.</p>
<pre><code class="language-plaintext">name TEXT
</code></pre>
<p>This stores text data.</p>
<pre><code class="language-plaintext">age INTEGER
</code></pre>
<p>This stores number data.</p>
<pre><code class="language-plaintext">address TEXT
</code></pre>
<p>This stores text data.</p>
<hr />
<h2>2. INSERT</h2>
<p>Used to add data into a table.</p>
<p>Example:</p>
<pre><code class="language-plaintext">INSERT INTO students (name, age, address)
VALUES ('Ram', 18, 'Kathmandu');
</code></pre>
<p>This adds one student into the students table.</p>
<hr />
<h2>3. SELECT</h2>
<p>Used to read data from a table.</p>
<p>Example:</p>
<pre><code class="language-plaintext">SELECT * FROM students;
</code></pre>
<p>This shows all students.</p>
<p>Example:</p>
<pre><code class="language-plaintext">SELECT name, age FROM students;
</code></pre>
<p>This shows only name and age.</p>
<hr />
<h2>4. WHERE</h2>
<p>Used to filter data.</p>
<p>Example:</p>
<pre><code class="language-plaintext">SELECT * FROM students
WHERE id = 1;
</code></pre>
<p>This shows only the student whose ID is 1.</p>
<hr />
<h2>5. UPDATE</h2>
<p>Used to change existing data.</p>
<p>Example:</p>
<pre><code class="language-plaintext">UPDATE students
SET age = 20
WHERE id = 1;
</code></pre>
<p>This changes the age of the student whose ID is 1.</p>
<p>Important:</p>
<p>Always use <code>WHERE</code> while updating.</p>
<p>Without <code>WHERE</code>, all rows may be updated.</p>
<hr />
<h2>6. DELETE</h2>
<p>Used to remove data.</p>
<p>Example:</p>
<pre><code class="language-plaintext">DELETE FROM students
WHERE id = 1;
</code></pre>
<p>This deletes the student whose ID is 1.</p>
<p>Important:</p>
<p>Always use <code>WHERE</code> while deleting.</p>
<p>Without <code>WHERE</code>, all data may be deleted.</p>
<hr />
<h1>7. Python with SQLite</h1>
<p>To use SQLite in Python, we use:</p>
<pre><code class="language-plaintext">import sqlite3
</code></pre>
<p>Basic structure:</p>
<pre><code class="language-plaintext">import sqlite3

connection = sqlite3.connect("school.db")

cursor = connection.cursor()

cursor.execute("SQL command here")

connection.commit()

connection.close()
</code></pre>
<hr />
<h1>8. Meaning of Important Lines</h1>
<h2><code>sqlite3.connect()</code></h2>
<pre><code class="language-plaintext">connection = sqlite3.connect("school.db")
</code></pre>
<p>This connects Python to the SQLite database.</p>
<p>If <code>school.db</code> does not exist, Python creates it automatically.</p>
<hr />
<h2><code>cursor</code></h2>
<pre><code class="language-plaintext">cursor = connection.cursor()
</code></pre>
<p>A cursor is a helper that runs SQL commands.</p>
<p>Simple explanation:</p>
<p>Database is like a notebook.</p>
<p>Connection opens the notebook.</p>
<p>Cursor is like a pen that writes or reads inside the notebook.</p>
<hr />
<h2><code>execute()</code></h2>
<pre><code class="language-plaintext">cursor.execute("SELECT * FROM students")
</code></pre>
<p>This runs SQL commands.</p>
<hr />
<h2><code>commit()</code></h2>
<pre><code class="language-plaintext">connection.commit()
</code></pre>
<p>This saves changes.</p>
<p>We use <code>commit()</code> after:</p>
<ol>
<li><p>Create table</p>
</li>
<li><p>Insert data</p>
</li>
<li><p>Update data</p>
</li>
<li><p>Delete data</p>
</li>
</ol>
<p>For <code>SELECT</code>, commit is not necessary.</p>
<hr />
<h2><code>close()</code></h2>
<pre><code class="language-plaintext">connection.close()
</code></pre>
<p>This closes the database connection.</p>
<hr />
<h1>9. Create Table Using Python</h1>
<pre><code class="language-plaintext">import sqlite3

connection = sqlite3.connect("school.db")
cursor = connection.cursor()

cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    age INTEGER NOT NULL,
    address TEXT NOT NULL
)
""")

connection.commit()
connection.close()

print("Table created successfully")
</code></pre>
<p>Explanation:</p>
<pre><code class="language-plaintext">CREATE TABLE IF NOT EXISTS students
</code></pre>
<p>This creates the students table only if it does not already exist.</p>
<hr />
<h1>10. Insert Data Using Python</h1>
<pre><code class="language-plaintext">import sqlite3

connection = sqlite3.connect("school.db")
cursor = connection.cursor()

cursor.execute("""
INSERT INTO students (name, age, address)
VALUES (?, ?, ?)
""", ("Ram", 18, "Kathmandu"))

connection.commit()
connection.close()

print("Student inserted successfully")
</code></pre>
<p>Explanation:</p>
<pre><code class="language-plaintext">VALUES (?, ?, ?)
</code></pre>
<p>The question marks are placeholders.</p>
<p>The actual values are passed here:</p>
<pre><code class="language-plaintext">("Ram", 18, "Kathmandu")
</code></pre>
<p>This is safer than writing values directly inside SQL.</p>
<hr />
<h1>11. Fetch Data Using Python</h1>
<pre><code class="language-plaintext">import sqlite3

connection = sqlite3.connect("school.db")
cursor = connection.cursor()

cursor.execute("SELECT * FROM students")

students = cursor.fetchall()

for student in students:
    print(student)

connection.close()
</code></pre>
<p>Output example:</p>
<pre><code class="language-plaintext">(1, 'Ram', 18, 'Kathmandu')
(2, 'Sita', 19, 'Pokhara')
</code></pre>
<hr />
<h1>12. <code>fetchone()</code> vs <code>fetchall()</code></h1>
<h2><code>fetchone()</code></h2>
<p>Gets only one row.</p>
<pre><code class="language-plaintext">student = cursor.fetchone()
</code></pre>
<p>Example output:</p>
<pre><code class="language-plaintext">(1, 'Ram', 18, 'Kathmandu')
</code></pre>
<h2><code>fetchall()</code></h2>
<p>Gets all rows.</p>
<pre><code class="language-plaintext">students = cursor.fetchall()
</code></pre>
<p>Example output:</p>
<pre><code class="language-plaintext">[
    (1, 'Ram', 18, 'Kathmandu'),
    (2, 'Sita', 19, 'Pokhara')
]
</code></pre>
<hr />
<h1>13. Update Data Using Python</h1>
<pre><code class="language-plaintext">import sqlite3

connection = sqlite3.connect("school.db")
cursor = connection.cursor()

cursor.execute("""
UPDATE students
SET name = ?, age = ?, address = ?
WHERE id = ?
""", ("Ram Sharma", 20, "Biratnagar", 1))

connection.commit()
connection.close()

print("Student updated successfully")
</code></pre>
<p>Explanation:</p>
<p>This updates the student whose ID is 1.</p>
<hr />
<h1>14. Delete Data Using Python</h1>
<pre><code class="language-plaintext">import sqlite3

connection = sqlite3.connect("school.db")
cursor = connection.cursor()

cursor.execute("""
DELETE FROM students
WHERE id = ?
""", (1,))

connection.commit()
connection.close()

print("Student deleted successfully")
</code></pre>
<p>Important:</p>
<pre><code class="language-plaintext">(1,)
</code></pre>
<p>This is a single-value tuple.</p>
<p>Do not write:</p>
<pre><code class="language-plaintext">(1)
</code></pre>
<p>Because <code>(1)</code> is just a number, not a tuple.</p>
<hr />
<h1>15. Complete SQLite CRUD Program</h1>
<p>Save the file as:</p>
<pre><code class="language-plaintext">student_database.py
</code></pre>
<pre><code class="language-plaintext">import sqlite3

def connect_db():
    connection = sqlite3.connect("school.db")
    return connection

def create_table():
    connection = connect_db()
    cursor = connection.cursor()

    cursor.execute("""
    CREATE TABLE IF NOT EXISTS students (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        age INTEGER NOT NULL,
        address TEXT NOT NULL
    )
    """)

    connection.commit()
    connection.close()

    print("Table created successfully")

def insert_student():
    name = input("Enter student name: ")
    age = int(input("Enter student age: "))
    address = input("Enter student address: ")

    connection = connect_db()
    cursor = connection.cursor()

    cursor.execute("""
    INSERT INTO students (name, age, address)
    VALUES (?, ?, ?)
    """, (name, age, address))

    connection.commit()
    connection.close()

    print("Student inserted successfully")

def view_students():
    connection = connect_db()
    cursor = connection.cursor()

    cursor.execute("SELECT * FROM students")

    students = cursor.fetchall()

    connection.close()

    if len(students) == 0:
        print("No students found")
    else:
        print("\n--- Student List ---")

        for student in students:
            print("ID:", student[0])
            print("Name:", student[1])
            print("Age:", student[2])
            print("Address:", student[3])
            print("--------------------")

def search_student():
    student_id = int(input("Enter student ID: "))

    connection = connect_db()
    cursor = connection.cursor()

    cursor.execute("""
    SELECT * FROM students
    WHERE id = ?
    """, (student_id,))

    student = cursor.fetchone()

    connection.close()

    if student:
        print("ID:", student[0])
        print("Name:", student[1])
        print("Age:", student[2])
        print("Address:", student[3])
    else:
        print("Student not found")

def update_student():
    student_id = int(input("Enter student ID to update: "))

    new_name = input("Enter new name: ")
    new_age = int(input("Enter new age: "))
    new_address = input("Enter new address: ")

    connection = connect_db()
    cursor = connection.cursor()

    cursor.execute("""
    UPDATE students
    SET name = ?, age = ?, address = ?
    WHERE id = ?
    """, (new_name, new_age, new_address, student_id))

    connection.commit()

    if cursor.rowcount == 0:
        print("Student not found")
    else:
        print("Student updated successfully")

    connection.close()

def delete_student():
    student_id = int(input("Enter student ID to delete: "))

    connection = connect_db()
    cursor = connection.cursor()

    cursor.execute("""
    DELETE FROM students
    WHERE id = ?
    """, (student_id,))

    connection.commit()

    if cursor.rowcount == 0:
        print("Student not found")
    else:
        print("Student deleted successfully")

    connection.close()

def menu():
    create_table()

    while True:
        print("\n===== Student Management System =====")
        print("1. Insert Student")
        print("2. View Students")
        print("3. Search Student")
        print("4. Update Student")
        print("5. Delete Student")
        print("6. Exit")

        choice = input("Enter your choice: ")

        if choice == "1":
            insert_student()

        elif choice == "2":
            view_students()

        elif choice == "3":
            search_student()

        elif choice == "4":
            update_student()

        elif choice == "5":
            delete_student()

        elif choice == "6":
            print("Program closed")
            break

        else:
            print("Invalid choice. Please try again")

menu()
</code></pre>
<hr />
<h1>16. Explanation of Complete Program</h1>
<h2><code>connect_db()</code></h2>
<pre><code class="language-plaintext">def connect_db():
    connection = sqlite3.connect("school.db")
    return connection
</code></pre>
<p>This function connects to the database.</p>
<p>We created a separate function so we do not need to write this again and again:</p>
<pre><code class="language-plaintext">sqlite3.connect("school.db")
</code></pre>
<hr />
<h2><code>create_table()</code></h2>
<p>This function creates the students table.</p>
<pre><code class="language-plaintext">CREATE TABLE IF NOT EXISTS students
</code></pre>
<p>If the table already exists, it does not create another table.</p>
<hr />
<h2><code>insert_student()</code></h2>
<p>This function adds a new student.</p>
<p>It takes input from user:</p>
<pre><code class="language-plaintext">name = input("Enter student name: ")
age = int(input("Enter student age: "))
address = input("Enter student address: ")
</code></pre>
<p>Then inserts the data:</p>
<pre><code class="language-plaintext">INSERT INTO students (name, age, address)
VALUES (?, ?, ?)
</code></pre>
<hr />
<h2><code>view_students()</code></h2>
<p>This function shows all students.</p>
<pre><code class="language-plaintext">SELECT * FROM students
</code></pre>
<p>This means:</p>
<p>Select all columns from students table.</p>
<hr />
<h2><code>search_student()</code></h2>
<p>This function searches one student by ID.</p>
<pre><code class="language-plaintext">SELECT * FROM students
WHERE id = ?
</code></pre>
<p>This means:</p>
<p>Find the student whose ID matches the given ID.</p>
<hr />
<h2><code>update_student()</code></h2>
<p>This function updates student details.</p>
<pre><code class="language-plaintext">UPDATE students
SET name = ?, age = ?, address = ?
WHERE id = ?
</code></pre>
<p>This means:</p>
<p>Change name, age, and address of the student whose ID matches.</p>
<hr />
<h2><code>delete_student()</code></h2>
<p>This function deletes a student.</p>
<pre><code class="language-plaintext">DELETE FROM students
WHERE id = ?
</code></pre>
<p>This means:</p>
<p>Delete the student whose ID matches.</p>
<hr />
<h1>17. Important SQL Keywords</h1>
<table>
<thead>
<tr>
<th>Keyword</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td><code>CREATE TABLE</code></td>
<td>Creates a table</td>
</tr>
<tr>
<td><code>INSERT INTO</code></td>
<td>Adds data</td>
</tr>
<tr>
<td><code>SELECT</code></td>
<td>Reads data</td>
</tr>
<tr>
<td><code>UPDATE</code></td>
<td>Changes data</td>
</tr>
<tr>
<td><code>DELETE</code></td>
<td>Removes data</td>
</tr>
<tr>
<td><code>WHERE</code></td>
<td>Filters data</td>
</tr>
<tr>
<td><code>ORDER BY</code></td>
<td>Sorts data</td>
</tr>
<tr>
<td><code>LIMIT</code></td>
<td>Limits result</td>
</tr>
</tbody></table>
<hr />
<h1>18. More SQL Examples</h1>
<h2>Show all students</h2>
<pre><code class="language-plaintext">SELECT * FROM students;
</code></pre>
<h2>Show only name and age</h2>
<pre><code class="language-plaintext">SELECT name, age FROM students;
</code></pre>
<h2>Search student by address</h2>
<pre><code class="language-plaintext">SELECT * FROM students
WHERE address = 'Kathmandu';
</code></pre>
<h2>Sort students by age</h2>
<pre><code class="language-plaintext">SELECT * FROM students
ORDER BY age;
</code></pre>
<h2>Show only first 5 students</h2>
<pre><code class="language-plaintext">SELECT * FROM students
LIMIT 5;
</code></pre>
<h2>Delete all students carefully</h2>
<pre><code class="language-plaintext">DELETE FROM students;
</code></pre>
<p>This deletes all records, so use carefully.</p>
<hr />
<h1>19. Why We Use <code>?</code> in Python SQLite</h1>
<p>We write:</p>
<pre><code class="language-plaintext">cursor.execute("""
INSERT INTO students (name, age, address)
VALUES (?, ?, ?)
""", (name, age, address))
</code></pre>
<p>This is better than:</p>
<pre><code class="language-plaintext">cursor.execute(f"""
INSERT INTO students (name, age, address)
VALUES ('{name}', {age}, '{address}')
""")
</code></pre>
<p>Why?</p>
<p>Because <code>?</code> is safer.</p>
<p>It prevents many SQL errors and also helps protect from SQL injection.</p>
<p>For students, explain simply:</p>
<blockquote>
<p>The question mark is an empty space. Python safely fills that empty space with the value we provide.</p>
</blockquote>
<hr />
<h1>20. Common Mistakes</h1>
<h2>Mistake 1: Forgetting <code>commit()</code></h2>
<p>Wrong:</p>
<pre><code class="language-plaintext">cursor.execute("INSERT INTO students (name, age, address) VALUES (?, ?, ?)", ("Ram", 18, "Kathmandu"))
connection.close()
</code></pre>
<p>Correct:</p>
<pre><code class="language-plaintext">cursor.execute("INSERT INTO students (name, age, address) VALUES (?, ?, ?)", ("Ram", 18, "Kathmandu"))
connection.commit()
connection.close()
</code></pre>
<p>Without <code>commit()</code>, data may not be saved.</p>
<hr />
<h2>Mistake 2: Forgetting <code>WHERE</code> in UPDATE</h2>
<p>Wrong:</p>
<pre><code class="language-plaintext">UPDATE students
SET age = 20;
</code></pre>
<p>This changes age for all students.</p>
<p>Correct:</p>
<pre><code class="language-plaintext">UPDATE students
SET age = 20
WHERE id = 1;
</code></pre>
<hr />
<h2>Mistake 3: Forgetting <code>WHERE</code> in DELETE</h2>
<p>Wrong:</p>
<pre><code class="language-plaintext">DELETE FROM students;
</code></pre>
<p>This deletes all students.</p>
<p>Correct:</p>
<pre><code class="language-plaintext">DELETE FROM students
WHERE id = 1;
</code></pre>
<hr />
<h2>Mistake 4: Wrong Single Tuple</h2>
<p>Wrong:</p>
<pre><code class="language-plaintext">cursor.execute("DELETE FROM students WHERE id = ?", (student_id))
</code></pre>
<p>Correct:</p>
<pre><code class="language-plaintext">cursor.execute("DELETE FROM students WHERE id = ?", (student_id,))
</code></pre>
<p>For one value, we need comma:</p>
<pre><code class="language-plaintext">(student_id,)
</code></pre>
<hr />
<h1>21. Day 4 Practice Questions</h1>
<h2>SQL Practice</h2>
<ol>
<li><p>Create a table named <code>products</code>.</p>
</li>
<li><p>Add columns: <code>id</code>, <code>name</code>, <code>price</code>, <code>quantity</code>.</p>
</li>
<li><p>Insert three products.</p>
</li>
<li><p>Show all products.</p>
</li>
<li><p>Search product by ID.</p>
</li>
<li><p>Update product price.</p>
</li>
<li><p>Delete one product.</p>
</li>
</ol>
<hr />
<h2>Python SQLite Practice</h2>
<p>Create a product management system.</p>
<p>Requirements:</p>
<ol>
<li><p>Create product table.</p>
</li>
<li><p>Add product.</p>
</li>
<li><p>View all products.</p>
</li>
<li><p>Search product.</p>
</li>
<li><p>Update product.</p>
</li>
<li><p>Delete product.</p>
</li>
<li><p>Use menu system.</p>
</li>
</ol>
<p>Product table:</p>
<pre><code class="language-plaintext">CREATE TABLE products (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    price REAL NOT NULL,
    quantity INTEGER NOT NULL
);
</code></pre>
<hr />
<h1>22. Product Management Practice Code Structure</h1>
<p>Students should create functions like this:</p>
<pre><code class="language-plaintext">def create_table():
    pass

def add_product():
    pass

def view_products():
    pass

def search_product():
    pass

def update_product():
    pass

def delete_product():
    pass

def menu():
    pass
</code></pre>
<p>This helps students practice functions and SQLite together.</p>
<hr />
<h1>23. Class Explanation Flow</h1>
<p>You can teach in this order:</p>
<ol>
<li><p>First revise file handling from Day 3.</p>
</li>
<li><p>Explain the problem with file handling.</p>
</li>
<li><p>Introduce database as a better storage system.</p>
</li>
<li><p>Explain table using Excel example.</p>
</li>
<li><p>Teach basic SQL commands.</p>
</li>
<li><p>Show SQLite connection in Python.</p>
</li>
<li><p>Explain cursor.</p>
</li>
<li><p>Create table.</p>
</li>
<li><p>Insert data.</p>
</li>
<li><p>Fetch data.</p>
</li>
<li><p>Update data.</p>
</li>
<li><p>Delete data.</p>
</li>
<li><p>Build complete CRUD app.</p>
</li>
<li><p>Give product management as practice.</p>
</li>
</ol>
<hr />
<h1>24. Day 4 Final Summary</h1>
<p>Today we learned:</p>
<h2>Database</h2>
<p>A database stores data in an organized way.</p>
<h2>SQLite</h2>
<p>SQLite is a simple database that stores data in a <code>.db</code> file.</p>
<h2>SQL</h2>
<p>SQL is the language used to talk with a database.</p>
<h2>Cursor</h2>
<p>Cursor is used to run SQL commands from Python.</p>
<h2>CRUD</h2>
<p>CRUD means:</p>
<pre><code class="language-plaintext">Create
Read
Update
Delete
</code></pre>
<h2>Important SQL Commands</h2>
<pre><code class="language-plaintext">CREATE TABLE
INSERT INTO
SELECT
UPDATE
DELETE
WHERE
</code></pre>
<h2>Important Python SQLite Lines</h2>
<pre><code class="language-plaintext">import sqlite3
</code></pre>
<p>Used to use SQLite in Python.</p>
<pre><code class="language-plaintext">sqlite3.connect("school.db")
</code></pre>
<p>Used to connect to database.</p>
<pre><code class="language-plaintext">connection.cursor()
</code></pre>
<p>Used to create cursor.</p>
<pre><code class="language-plaintext">cursor.execute()
</code></pre>
<p>Used to run SQL command.</p>
<pre><code class="language-plaintext">connection.commit()
</code></pre>
<p>Used to save changes.</p>
<pre><code class="language-plaintext">connection.close()
</code></pre>
<p>Used to close database.</p>
<hr />
<h1>Final Memory for Students</h1>
<pre><code class="language-plaintext">File handling stores data in files.

Database stores data in tables.

SQLite is a simple database.

SQL is used to talk with database.

Cursor runs SQL commands.

commit() saves changes.

CRUD means create, read, update, delete.
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Day 3 Python Notes]]></title><description><![CDATA[In Day 2, we learned about lists. A list is used to store multiple values in one variable. Example: Now, we will learn list slicing. List slicing means…]]></description><link>https://piankit.hashnode.dev/day-3-python-notes</link><guid isPermaLink="true">https://piankit.hashnode.dev/day-3-python-notes</guid><dc:creator><![CDATA[Ankit Chapagain]]></dc:creator><pubDate>Thu, 21 May 2026 15:35:56 GMT</pubDate><content:encoded><![CDATA[<h2>Topics Covered</h2>
<pre><code class="language-text">1. List Slicing
2. Tuple
3. Dictionary
4. Set
5. Exception Handling
6. Different Types of Exceptions
7. File Handling
8. Login System Using File Handling and Exception Handling
</code></pre>
<hr />
<h1>1. List Slicing</h1>
<p>In Day 2, we learned about lists.</p>
<p>A list is used to store multiple values in one variable.</p>
<p>Example:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange", "grapes"]
</code></pre>
<p>Now, we will learn <strong>list slicing</strong>.</p>
<p>List slicing means taking a specific part of a list.</p>
<hr />
<h2>List Index Revision</h2>
<p>In Python, list index starts from <code>0</code>.</p>
<p>Example:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange"]
</code></pre>
<p>Index values:</p>
<pre><code class="language-text">apple   -&gt; index 0
banana  -&gt; index 1
mango   -&gt; index 2
orange  -&gt; index 3
</code></pre>
<p>Example:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange"]

print(fruits[0])
print(fruits[1])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">apple
banana
</code></pre>
<hr />
<h2>Basic List Slicing</h2>
<p>Example:</p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50]

print(numbers[0:3])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[10, 20, 30]
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">numbers[0:3]
</code></pre>
<p>means start from index <code>0</code> and stop before index <code>3</code>.</p>
<p>It includes:</p>
<pre><code class="language-python">numbers[0]
numbers[1]
numbers[2]
</code></pre>
<p>It does not include index <code>3</code>.</p>
<hr />
<h2>More List Slicing Examples</h2>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50, 60]

print(numbers[0:3])
print(numbers[2:5])
print(numbers[:4])
print(numbers[3:])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[10, 20, 30]
[30, 40, 50]
[10, 20, 30, 40]
[40, 50, 60]
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">numbers[0:3]
</code></pre>
<p>starts from index <code>0</code> and stops before index <code>3</code>.</p>
<pre><code class="language-python">numbers[2:5]
</code></pre>
<p>starts from index <code>2</code> and stops before index <code>5</code>.</p>
<pre><code class="language-python">numbers[:4]
</code></pre>
<p>starts from the beginning and stops before index <code>4</code>.</p>
<pre><code class="language-python">numbers[3:]
</code></pre>
<p>starts from index <code>3</code> and goes until the end.</p>
<hr />
<h2>Negative Indexing</h2>
<p>Python also supports negative indexing.</p>
<p>Example:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange"]

print(fruits[-1])
print(fruits[-2])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">orange
mango
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">-1
</code></pre>
<p>means last item.</p>
<pre><code class="language-python">-2
</code></pre>
<p>means second last item.</p>
<hr />
<h2>Negative Slicing</h2>
<p>Example:</p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50, 60]

print(numbers[-3:])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[40, 50, 60]
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">numbers[-3:]
</code></pre>
<p>means take the last three items.</p>
<hr />
<h2>Slicing With Step</h2>
<p>Example:</p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50, 60]

print(numbers[0:6:2])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[10, 30, 50]
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">numbers[0:6:2]
</code></pre>
<p>means:</p>
<pre><code class="language-text">Start from index 0
Stop before index 6
Move by step 2
</code></pre>
<hr />
<h2>Reverse a List Using Slicing</h2>
<p>Example:</p>
<pre><code class="language-python">numbers = [10, 20, 30, 40, 50]

print(numbers[::-1])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[50, 40, 30, 20, 10]
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">[::-1]
</code></pre>
<p>is used to reverse a list.</p>
<hr />
<h2>List Slicing Questions</h2>
<h3>Question 1</h3>
<p>Print the first three items from a list.</p>
<p>Solution:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange", "grapes"]

print(fruits[0:3])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">['apple', 'banana', 'mango']
</code></pre>
<hr />
<h3>Question 2</h3>
<p>Print the last two items from a list.</p>
<p>Solution:</p>
<pre><code class="language-python">fruits = ["apple", "banana", "mango", "orange", "grapes"]

print(fruits[-2:])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">['orange', 'grapes']
</code></pre>
<hr />
<h3>Question 3</h3>
<p>Reverse a list using slicing.</p>
<p>Solution:</p>
<pre><code class="language-python">numbers = [1, 2, 3, 4, 5]

print(numbers[::-1])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">[5, 4, 3, 2, 1]
</code></pre>
<hr />
<h1>2. Tuple</h1>
<p>A tuple is used to store multiple values in one variable.</p>
<p>It is similar to a list.</p>
<p>But the main difference is:</p>
<pre><code class="language-text">List is changeable.
Tuple is not changeable.
</code></pre>
<p>That means after creating a tuple, we cannot directly add, remove, or change its items.</p>
<p>Example:</p>
<pre><code class="language-python">fruits = ("apple", "banana", "mango")

print(fruits)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">('apple', 'banana', 'mango')
</code></pre>
<p>Here, <code>fruits</code> is a tuple.</p>
<hr />
<h2>Accessing Tuple Items</h2>
<p>Tuple index also starts from <code>0</code>, just like list.</p>
<p>Example:</p>
<pre><code class="language-python">fruits = ("apple", "banana", "mango")

print(fruits[0])
print(fruits[1])
print(fruits[2])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">apple
banana
mango
</code></pre>
<p>Explanation:</p>
<pre><code class="language-python">fruits[0]
</code></pre>
<p>gives <code>"apple"</code>.</p>
<pre><code class="language-python">fruits[1]
</code></pre>
<p>gives <code>"banana"</code>.</p>
<pre><code class="language-python">fruits[2]
</code></pre>
<p>gives <code>"mango"</code>.</p>
<hr />
<h2>Tuple Cannot Be Changed</h2>
<p>Example:</p>
<pre><code class="language-python">fruits = ("apple", "banana", "mango")

fruits[0] = "orange"

print(fruits)
</code></pre>
<p>This gives an error.</p>
<p>Because tuple does not allow item change.</p>
<hr />
<h2>Why Use Tuple?</h2>
<p>We use tuple when we want to store values that should not change.</p>
<p>Example:</p>
<pre><code class="language-python">days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
</code></pre>
<p>Days of the week are fixed, so tuple is a good choice.</p>
<p>Another example:</p>
<pre><code class="language-python">location = (26.4525, 87.2718)
</code></pre>
<p>This can store latitude and longitude.</p>
<hr />
<h2>Looping Through Tuple</h2>
<p>Example:</p>
<pre><code class="language-python">fruits = ("apple", "banana", "mango")

for fruit in fruits:
    print(fruit)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">apple
banana
mango
</code></pre>
<p>Explanation:</p>
<p>Tuple is iterable.</p>
<p>So we can use a <code>for</code> loop to read each item one by one.</p>
<hr />
<h2>Tuple Question 1</h2>
<p>Write a program to store five student names in a tuple and print them one by one.</p>
<p>Solution:</p>
<pre><code class="language-python">students = ("Ram", "Sita", "Hari", "Gita", "Shyam")

for student in students:
    print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Ram
Sita
Hari
Gita
Shyam
</code></pre>
<hr />
<h2>Tuple Question 2</h2>
<p>Write a program to find the length of a tuple.</p>
<p>Solution:</p>
<pre><code class="language-python">numbers = (10, 20, 30, 40, 50)

print("Total items:", len(numbers))
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Total items: 5
</code></pre>
<p>Explanation:</p>
<p><code>len()</code> counts how many items are inside the tuple.</p>
<hr />
<h2>Tuple Question 3</h2>
<p>Write a program to check whether <code>"apple"</code> exists in a tuple or not.</p>
<p>Solution:</p>
<pre><code class="language-python">fruits = ("apple", "banana", "mango")

if "apple" in fruits:
    print("Apple exists")
else:
    print("Apple does not exist")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Apple exists
</code></pre>
<hr />
<h1>3. Dictionary</h1>
<p>A dictionary is used to store data in <strong>key-value pairs</strong>.</p>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'name': 'Ram', 'age': 18, 'address': 'Kathmandu'}
</code></pre>
<p>Here:</p>
<pre><code class="language-python">"name"
</code></pre>
<p>is a key.</p>
<pre><code class="language-python">"Ram"
</code></pre>
<p>is the value.</p>
<hr />
<h2>Real-Life Example of Dictionary</h2>
<p>A student has different details:</p>
<pre><code class="language-text">Name: Ram
Age: 18
Address: Kathmandu
</code></pre>
<p>In Python, we can store this like:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}
</code></pre>
<p>Dictionary is useful when we want to store related information.</p>
<hr />
<h2>Accessing Dictionary Values</h2>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

print(student["name"])
print(student["age"])
print(student["address"])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Ram
18
Kathmandu
</code></pre>
<p>Explanation:</p>
<p>We use the key to access the value.</p>
<pre><code class="language-python">student["name"]
</code></pre>
<p>gives <code>"Ram"</code>.</p>
<hr />
<h2>Updating Dictionary Value</h2>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18
}

student["age"] = 19

print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'name': 'Ram', 'age': 19}
</code></pre>
<p>Explanation:</p>
<p>The value of <code>"age"</code> was changed from <code>18</code> to <code>19</code>.</p>
<hr />
<h2>Adding New Key-Value Pair</h2>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18
}

student["address"] = "Kathmandu"

print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'name': 'Ram', 'age': 18, 'address': 'Kathmandu'}
</code></pre>
<p>Explanation:</p>
<p>A new key <code>"address"</code> was added to the dictionary.</p>
<hr />
<h2>Removing Item from Dictionary</h2>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

student.pop("age")

print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'name': 'Ram', 'address': 'Kathmandu'}
</code></pre>
<p>Explanation:</p>
<p><code>pop()</code> removes the item with the given key.</p>
<hr />
<h2>Looping Through Dictionary</h2>
<p>Example:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

for key in student:
    print(key)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">name
age
address
</code></pre>
<p>This prints only keys.</p>
<p>To print values:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

for key in student:
    print(student[key])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Ram
18
Kathmandu
</code></pre>
<p>To print both key and value:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "age": 18,
    "address": "Kathmandu"
}

for key, value in student.items():
    print(key, ":", value)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">name : Ram
age : 18
address : Kathmandu
</code></pre>
<hr />
<h2>Dictionary Question 1</h2>
<p>Write a program to store student name, age, and address in a dictionary and print them.</p>
<p>Solution:</p>
<pre><code class="language-python">student = {
    "name": "Sita",
    "age": 19,
    "address": "Pokhara"
}

print("Name:", student["name"])
print("Age:", student["age"])
print("Address:", student["address"])
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Name: Sita
Age: 19
Address: Pokhara
</code></pre>
<hr />
<h2>Dictionary Question 2</h2>
<p>Write a program to store product name, price, and quantity. Then calculate total price.</p>
<p>Solution:</p>
<pre><code class="language-python">product = {
    "name": "Pen",
    "price": 20,
    "quantity": 5
}

total = product["price"] * product["quantity"]

print("Product:", product["name"])
print("Total price:", total)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Product: Pen
Total price: 100
</code></pre>
<p>Explanation:</p>
<p>Price is <code>20</code>.</p>
<p>Quantity is <code>5</code>.</p>
<p>So:</p>
<pre><code class="language-python">20 * 5 = 100
</code></pre>
<hr />
<h2>Dictionary Question 3</h2>
<p>Write a program to update a student's marks.</p>
<p>Solution:</p>
<pre><code class="language-python">student = {
    "name": "Ram",
    "marks": 75
}

student["marks"] = 85

print(student)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'name': 'Ram', 'marks': 85}
</code></pre>
<hr />
<h1>4. Set</h1>
<p>A set is used to store multiple values in one variable.</p>
<p>But set has two important features:</p>
<pre><code class="language-text">1. Set does not allow duplicate values.
2. Set does not maintain fixed order.
</code></pre>
<p>Example:</p>
<pre><code class="language-python">numbers = {10, 20, 30, 40}

print(numbers)
</code></pre>
<p>Output may be:</p>
<pre><code class="language-python">{40, 10, 20, 30}
</code></pre>
<p>The order may be different.</p>
<p>That is normal in set.</p>
<hr />
<h2>Set Does Not Allow Duplicate Values</h2>
<p>Example:</p>
<pre><code class="language-python">numbers = {10, 20, 20, 30, 30, 40}

print(numbers)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{40, 10, 20, 30}
</code></pre>
<p>Explanation:</p>
<p>Duplicate values are automatically removed.</p>
<hr />
<h2>Adding Item to Set</h2>
<p>Example:</p>
<pre><code class="language-python">fruits = {"apple", "banana"}

fruits.add("mango")

print(fruits)
</code></pre>
<p>Output may be:</p>
<pre><code class="language-python">{'apple', 'banana', 'mango'}
</code></pre>
<p>The order may be different.</p>
<hr />
<h2>Removing Item from Set</h2>
<p>Example:</p>
<pre><code class="language-python">fruits = {"apple", "banana", "mango"}

fruits.remove("banana")

print(fruits)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'apple', 'mango'}
</code></pre>
<hr />
<h2>Looping Through Set</h2>
<p>Example:</p>
<pre><code class="language-python">fruits = {"apple", "banana", "mango"}

for fruit in fruits:
    print(fruit)
</code></pre>
<p>Output may be:</p>
<pre><code class="language-python">banana
apple
mango
</code></pre>
<p>Explanation:</p>
<p>Set is iterable.</p>
<p>But the order is not fixed.</p>
<hr />
<h2>Why Use Set?</h2>
<p>Set is useful when we want unique values only.</p>
<p>Example:</p>
<pre><code class="language-python">students = {"Ram", "Sita", "Ram", "Hari", "Sita"}

print(students)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{'Ram', 'Sita', 'Hari'}
</code></pre>
<p>Duplicate names are removed.</p>
<hr />
<h2>Set Question 1</h2>
<p>Write a program to remove duplicate numbers from a list.</p>
<p>Solution:</p>
<pre><code class="language-python">numbers = [10, 20, 20, 30, 30, 40]

unique_numbers = set(numbers)

print(unique_numbers)
</code></pre>
<p>Output:</p>
<pre><code class="language-python">{40, 10, 20, 30}
</code></pre>
<p>Explanation:</p>
<p>The list contains duplicate values.</p>
<p>When we convert it into a set, duplicate values are removed.</p>
<hr />
<h2>Set Question 2</h2>
<p>Write a program to add a new student name in a set.</p>
<p>Solution:</p>
<pre><code class="language-python">students = {"Ram", "Sita", "Hari"}

students.add("Gita")

print(students)
</code></pre>
<p>Output may be:</p>
<pre><code class="language-python">{'Ram', 'Sita', 'Hari', 'Gita'}
</code></pre>
<hr />
<h2>Set Question 3</h2>
<p>Write a program to check whether <code>"Ram"</code> exists in a set or not.</p>
<p>Solution:</p>
<pre><code class="language-python">students = {"Ram", "Sita", "Hari"}

if "Ram" in students:
    print("Ram exists")
else:
    print("Ram does not exist")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Ram exists
</code></pre>
<hr />
<h1>5. Exception Handling</h1>
<p>Exception handling means handling errors in a program.</p>
<p>Sometimes our program may get an error while running.</p>
<p>Example:</p>
<pre><code class="language-python">a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print(a / b)
</code></pre>
<p>If the user enters:</p>
<pre><code class="language-python">10
0
</code></pre>
<p>Then the program gives an error because division by zero is not allowed.</p>
<p>To handle this kind of error, we use:</p>
<pre><code class="language-python">try
except
</code></pre>
<hr />
<h2>Basic Try Except</h2>
<p>Example:</p>
<pre><code class="language-python">try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))

    result = a / b

    print("Result:", result)

except:
    print("Something went wrong")
</code></pre>
<p>Explanation:</p>
<p>The code that may cause an error is written inside <code>try</code>.</p>
<p>If an error happens, the code inside <code>except</code> runs.</p>
<p>So instead of crashing, the program shows a message.</p>
<hr />
<h2>Better Try Except</h2>
<p>It is better to mention the exact error name.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))

    result = a / b

    print("Result:", result)

except ZeroDivisionError:
    print("Cannot divide by zero")

except ValueError:
    print("Please enter numbers only")
</code></pre>
<p>Explanation:</p>
<p><code>ZeroDivisionError</code> happens when we divide by zero.</p>
<p><code>ValueError</code> happens when we enter invalid number input.</p>
<hr />
<h1>6. Different Types of Exceptions</h1>
<p>Python has many types of exceptions.</p>
<p>Some common exceptions are:</p>
<pre><code class="language-text">1. ValueError
2. ZeroDivisionError
3. FileNotFoundError
4. IndexError
5. KeyError
6. TypeError
7. NameError
8. PermissionError
</code></pre>
<hr />
<h2>1. ValueError</h2>
<p><code>ValueError</code> happens when the value is not valid.</p>
<p>Example:</p>
<pre><code class="language-python">age = int("hello")
</code></pre>
<p>This gives an error because <code>"hello"</code> cannot be converted into an integer.</p>
<p>Correct handling:</p>
<pre><code class="language-python">try:
    age = int(input("Enter your age: "))
    print("Your age is", age)

except ValueError:
    print("Please enter a valid number")
</code></pre>
<hr />
<h2>2. ZeroDivisionError</h2>
<p><code>ZeroDivisionError</code> happens when we divide a number by zero.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    a = 10
    b = 0

    result = a / b

    print(result)

except ZeroDivisionError:
    print("Cannot divide by zero")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Cannot divide by zero
</code></pre>
<hr />
<h2>3. FileNotFoundError</h2>
<p><code>FileNotFoundError</code> happens when we try to read a file that does not exist.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    with open("data.txt", "r") as file:
        data = file.read()
        print(data)

except FileNotFoundError:
    print("File not found")
</code></pre>
<hr />
<h2>4. IndexError</h2>
<p><code>IndexError</code> happens when we try to access an index that does not exist in a list.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    numbers = [10, 20, 30]

    print(numbers[5])

except IndexError:
    print("Index does not exist")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Index does not exist
</code></pre>
<p>Explanation:</p>
<p>The list has only three items.</p>
<p>Available indexes are:</p>
<pre><code class="language-python">0, 1, 2
</code></pre>
<p>But we tried to access index <code>5</code>.</p>
<p>So <code>IndexError</code> happened.</p>
<hr />
<h2>5. KeyError</h2>
<p><code>KeyError</code> happens when we try to access a dictionary key that does not exist.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    student = {
        "name": "Ram",
        "age": 18
    }

    print(student["address"])

except KeyError:
    print("Key does not exist")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Key does not exist
</code></pre>
<p>Explanation:</p>
<p>The dictionary has only:</p>
<pre><code class="language-python">name
age
</code></pre>
<p>But we tried to access:</p>
<pre><code class="language-python">address
</code></pre>
<p>So <code>KeyError</code> happened.</p>
<hr />
<h2>6. TypeError</h2>
<p><code>TypeError</code> happens when we perform an operation with the wrong data type.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    result = "Age: " + 20
    print(result)

except TypeError:
    print("Cannot add string and number directly")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Cannot add string and number directly
</code></pre>
<p>Correct way:</p>
<pre><code class="language-python">result = "Age: " + str(20)
print(result)
</code></pre>
<hr />
<h2>7. NameError</h2>
<p><code>NameError</code> happens when we use a variable that has not been created.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    print(username)

except NameError:
    print("Variable is not defined")
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Variable is not defined
</code></pre>
<hr />
<h2>8. PermissionError</h2>
<p><code>PermissionError</code> happens when Python does not have permission to read or write a file.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    with open("/root/data.txt", "w") as file:
        file.write("Hello")

except PermissionError:
    print("You do not have permission to write this file")
</code></pre>
<hr />
<h2>Handling Multiple Exceptions Together</h2>
<p>Example:</p>
<pre><code class="language-python">try:
    a = int(input("Enter first number: "))
    b = int(input("Enter second number: "))

    result = a / b

    print("Result:", result)

except ValueError:
    print("Please enter numbers only")

except ZeroDivisionError:
    print("Cannot divide by zero")

except Exception as e:
    print("Something went wrong:", e)
</code></pre>
<p>Explanation:</p>
<p><code>ValueError</code> handles invalid input.</p>
<p><code>ZeroDivisionError</code> handles division by zero.</p>
<p><code>Exception</code> handles any other unexpected error.</p>
<hr />
<h2>Try Except Else</h2>
<p><code>else</code> runs only when there is no error.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    age = int(input("Enter your age: "))

except ValueError:
    print("Please enter a valid number")

else:
    print("Your age is", age)
</code></pre>
<p>Explanation:</p>
<p>If the user enters a correct number, <code>else</code> runs.</p>
<p>If the user enters text like <code>"abc"</code>, <code>except</code> runs.</p>
<hr />
<h2>Try Except Finally</h2>
<p><code>finally</code> always runs.</p>
<p>Example:</p>
<pre><code class="language-python">try:
    number = int(input("Enter a number: "))
    print(number)

except ValueError:
    print("Invalid input")

finally:
    print("Program finished")
</code></pre>
<p>Explanation:</p>
<p>Whether error happens or not, <code>finally</code> runs.</p>
<hr />
<h1>7. File Handling</h1>
<p>File handling means working with files using Python.</p>
<p>Using file handling, we can:</p>
<pre><code class="language-text">1. Create a file
2. Write data into a file
3. Read data from a file
4. Add new data into an existing file
</code></pre>
<hr />
<h2>Opening a File</h2>
<p>Python uses <code>open()</code> to open a file.</p>
<p>Syntax:</p>
<pre><code class="language-python">file = open("filename.txt", "mode")
</code></pre>
<p>Common file modes:</p>
<pre><code class="language-text">"r"  read mode
"w"  write mode
"a"  append mode
</code></pre>
<hr />
<h2>Write Mode</h2>
<p>Write mode is used to write data into a file.</p>
<p>Example:</p>
<pre><code class="language-python">file = open("student.txt", "w")

file.write("Hello, this is my first file.")

file.close()
</code></pre>
<p>Explanation:</p>
<p><code>student.txt</code> is the file name.</p>
<p><code>"w"</code> means write mode.</p>
<p><code>write()</code> writes data into the file.</p>
<p><code>close()</code> closes the file.</p>
<p>Important:</p>
<p>If the file does not exist, Python creates it.</p>
<p>If the file already exists, write mode replaces old content.</p>
<hr />
<h2>Reading a File</h2>
<p>Example:</p>
<pre><code class="language-python">file = open("student.txt", "r")

data = file.read()

print(data)

file.close()
</code></pre>
<p>Output:</p>
<pre><code class="language-python">Hello, this is my first file.
</code></pre>
<p>Explanation:</p>
<p><code>"r"</code> means read mode.</p>
<p><code>read()</code> reads the file content.</p>
<hr />
<h2>Append Mode</h2>
<p>Append mode is used to add new data without deleting old data.</p>
<p>Example:</p>
<pre><code class="language-python">file = open("student.txt", "a")

file.write("\nThis is new line.")

file.close()
</code></pre>
<p>Explanation:</p>
<p><code>"a"</code> means append mode.</p>
<p>It adds new content at the end of the file.</p>
<p><code>\n</code> means new line.</p>
<hr />
<h2>Better Way: Using with open()</h2>
<p>The better way to work with files is:</p>
<pre><code class="language-python">with open("student.txt", "w") as file:
    file.write("Hello Python")
</code></pre>
<p>Here, we do not need to write:</p>
<pre><code class="language-python">file.close()
</code></pre>
<p>Python automatically closes the file.</p>
<hr />
<h2>Read File Using with open()</h2>
<p>Example:</p>
<pre><code class="language-python">with open("student.txt", "r") as file:
    data = file.read()
    print(data)
</code></pre>
<hr />
<h2>File Handling With Exception Handling</h2>
<p>File handling and exception handling are often used together.</p>
<p>Why?</p>
<p>Because file errors can happen.</p>
<p>For example:</p>
<pre><code class="language-text">1. File may not exist.
2. User may enter wrong input.
3. Program may not have permission to read/write file.
</code></pre>
<p>Example:</p>
<pre><code class="language-python">try:
    with open("student.txt", "r") as file:
        data = file.read()
        print(data)

except FileNotFoundError:
    print("File does not exist")
</code></pre>
<p>Explanation:</p>
<p>If <code>student.txt</code> exists, Python reads the file.</p>
<p>If it does not exist, <code>FileNotFoundError</code> happens.</p>
<p>Then <code>except</code> block runs.</p>
<hr />
<h1>8. File-Based Login System</h1>
<p>Now we will create a simple login system using file handling.</p>
<p>In this system:</p>
<pre><code class="language-text">Each user will have their own file.
The username will be used as the file name.
The password will be saved inside that file.
</code></pre>
<p>Example:</p>
<p>If username is:</p>
<pre><code class="language-python">ram
</code></pre>
<p>Then Python creates:</p>
<pre><code class="language-python">ram.txt
</code></pre>
<p>Inside <code>ram.txt</code>, the password is saved.</p>
<hr />
<h2>Full Login System Code</h2>
<pre><code class="language-python">def register():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        print("Username already exists")
        file.close()

    except FileNotFoundError:
        with open(f"{username}.txt", "w") as f:
            f.write(password)

        print("User registered successfully")

    except Exception as e:
        print("Something went wrong while registering:", e)


def login():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        file.close()

    except FileNotFoundError:
        print("User not found")
        return

    except Exception as e:
        print("Something went wrong while opening user file:", e)
        return

    try:
        with open(f"{username}.txt", "r") as f:
            checkpass = f.readline()

            if password == checkpass:
                print("Welcome")
            else:
                print("Sorry, incorrect password")

    except Exception as e:
        print("Something went wrong while checking password:", e)


def ask():
    x = input("Do you want to register or login? Press r for register and l for login: ")

    if x == "r":
        register()

    elif x == "l":
        login()

    else:
        print("Invalid choice")


ask()
</code></pre>
<hr />
<h1>9. Explanation of Login System</h1>
<h2>Register Function</h2>
<pre><code class="language-python">def register():
</code></pre>
<p>This function is used to register a new user.</p>
<pre><code class="language-python">username = input("Enter your username: ")
password = input("Enter your password: ")
</code></pre>
<p>Here, the program asks the user to enter username and password.</p>
<hr />
<h2>Checking If Username Already Exists</h2>
<pre><code class="language-python">try:
    file = open(f"{username}.txt", "r")
    print("Username already exists")
    file.close()
</code></pre>
<p>Here, the program tries to open a file with the username.</p>
<p>Example:</p>
<p>If username is:</p>
<pre><code class="language-python">ram
</code></pre>
<p>Then it tries to open:</p>
<pre><code class="language-python">ram.txt
</code></pre>
<p>If the file exists, it means the username is already registered.</p>
<p>So the program prints:</p>
<pre><code class="language-python">Username already exists
</code></pre>
<hr />
<h2>Creating File for New User</h2>
<pre><code class="language-python">except FileNotFoundError:
    with open(f"{username}.txt", "w") as f:
        f.write(password)

    print("User registered successfully")
</code></pre>
<p>If the file does not exist, Python gives <code>FileNotFoundError</code>.</p>
<p>That means the username is new.</p>
<p>So the program creates a new file and saves the password inside it.</p>
<p>Example:</p>
<p>If username is:</p>
<pre><code class="language-python">sita
</code></pre>
<p>Then file name becomes:</p>
<pre><code class="language-python">sita.txt
</code></pre>
<p>And inside that file, the password is saved.</p>
<hr />
<h2>Login Function</h2>
<pre><code class="language-python">def login():
</code></pre>
<p>This function is used to login an existing user.</p>
<pre><code class="language-python">username = input("Enter your username: ")
password = input("Enter your password: ")
</code></pre>
<p>The program asks for username and password.</p>
<hr />
<h2>Checking If User Exists</h2>
<pre><code class="language-python">try:
    file = open(f"{username}.txt", "r")
    file.close()
</code></pre>
<p>The program tries to open the user's file.</p>
<p>If the file exists, the user exists.</p>
<hr />
<h2>User Not Found</h2>
<pre><code class="language-python">except FileNotFoundError:
    print("User not found")
    return
</code></pre>
<p>If the file does not exist, the program prints:</p>
<pre><code class="language-python">User not found
</code></pre>
<p>Here, <code>return</code> is used to stop the function.</p>
<p>This is better than <code>exit()</code> because <code>exit()</code> closes the whole program immediately.</p>
<hr />
<h2>Reading Saved Password</h2>
<pre><code class="language-python">with open(f"{username}.txt", "r") as f:
    checkpass = f.readline()
</code></pre>
<p>This opens the user's file and reads the saved password.</p>
<p>The saved password is stored in:</p>
<pre><code class="language-python">checkpass
</code></pre>
<hr />
<h2>Checking Password</h2>
<pre><code class="language-python">if password == checkpass:
    print("Welcome")
else:
    print("Sorry, incorrect password")
</code></pre>
<p>If entered password and saved password are same, login is successful.</p>
<p>Otherwise, it prints incorrect password.</p>
<hr />
<h1>10. Simpler Version Like Your Original Code</h1>
<p>This is very close to your original code.</p>
<pre><code class="language-python">def register():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        print("Username already exists")
        file.close()

    except:
        with open(f"{username}.txt", "w") as f:
            f.write(password)

        print("User registered successfully")


def login():
    username = input("Enter your username: ")
    password = input("Enter your password: ")

    try:
        file = open(f"{username}.txt", "r")
        file.close()

    except:
        print("User not found")
        return

    with open(f"{username}.txt", "r") as f:
        checkpass = f.readline()

        if password == checkpass:
            print("Welcome")
        else:
            print("Sorry, incorrect password")


def ask():
    x = input("Do you want to register or login? Press r for register and l for login: ")

    if x == "r":
        register()
    else:
        login()


ask()
</code></pre>
<p>This version is okay for beginners.</p>
<p>But for better practice, this is preferred:</p>
<pre><code class="language-python">except FileNotFoundError:
</code></pre>
<p>instead of only:</p>
<pre><code class="language-python">except:
</code></pre>
<p>Because <code>except:</code> catches all errors, but <code>FileNotFoundError</code> catches only file-not-found error.</p>
<hr />
<h1>11. Important Note About This Login System</h1>
<p>This login system is only for learning.</p>
<p>It teaches:</p>
<pre><code class="language-text">1. Function
2. Input
3. File handling
4. Try and except
5. User already exists
6. User not found
7. Password checking
</code></pre>
<p>But in real websites or real applications, passwords should not be saved directly like this.</p>
<p>In real projects, passwords should be hashed before saving.</p>
<p>For now, this is good for beginner-level Python file handling practice.</p>
<hr />
<h1>12. Class Explanation Flow</h1>
<p>You can explain the login system like this:</p>
<pre><code class="language-text">When registering:
Python checks if username.txt exists.
If it exists, the user already exists.
If it does not exist, Python creates the file and saves the password.

When logging in:
Python checks if username.txt exists.
If it does not exist, user not found.
If it exists, Python reads the saved password.
Then it compares the saved password with the entered password.
</code></pre>
<hr />
<h1>13. Day 3 Practice Questions</h1>
<h2>List Slicing Questions</h2>
<ol>
<li><p>Create a list of 10 numbers and print the first 5 numbers.</p>
</li>
<li><p>Print the last 3 numbers from a list.</p>
</li>
<li><p>Reverse a list using slicing.</p>
</li>
<li><p>Print every second item from a list.</p>
</li>
</ol>
<hr />
<h2>Tuple Questions</h2>
<ol>
<li><p>Create a tuple of five fruits and print each fruit.</p>
</li>
<li><p>Create a tuple of numbers and find its length.</p>
</li>
<li><p>Check whether <code>"Python"</code> exists in a tuple.</p>
</li>
<li><p>Try to change a tuple item and observe the error.</p>
</li>
</ol>
<hr />
<h2>Dictionary Questions</h2>
<ol>
<li><p>Create a dictionary for a student with name, age, class, and address.</p>
</li>
<li><p>Create a dictionary for a product and calculate total price.</p>
</li>
<li><p>Update the marks of a student in a dictionary.</p>
</li>
<li><p>Print all keys and values from a dictionary.</p>
</li>
</ol>
<hr />
<h2>Set Questions</h2>
<ol>
<li><p>Create a set of numbers with duplicate values and print it.</p>
</li>
<li><p>Add a new item to a set.</p>
</li>
<li><p>Remove an item from a set.</p>
</li>
<li><p>Convert a list with duplicate values into a set.</p>
</li>
</ol>
<hr />
<h2>Exception Handling Questions</h2>
<ol>
<li><p>Take two numbers and divide them. Handle <code>ZeroDivisionError</code>.</p>
</li>
<li><p>Take age from user. Handle <code>ValueError</code>.</p>
</li>
<li><p>Try to access an invalid list index. Handle <code>IndexError</code>.</p>
</li>
<li><p>Try to access an invalid dictionary key. Handle <code>KeyError</code>.</p>
</li>
<li><p>Try to read a file that does not exist. Handle <code>FileNotFoundError</code>.</p>
</li>
</ol>
<hr />
<h2>File Handling Questions</h2>
<ol>
<li><p>Create a file named <code>message.txt</code> and write <code>"Hello Python"</code> into it.</p>
</li>
<li><p>Read and print the content of <code>message.txt</code>.</p>
</li>
<li><p>Append three student names into <code>students.txt</code>.</p>
</li>
<li><p>Read a file and handle <code>FileNotFoundError</code>.</p>
</li>
</ol>
<hr />
<h2>Final Project Question</h2>
<p>Create a login system using file handling.</p>
<p>Requirements:</p>
<pre><code class="language-text">1. Register user.
2. Login user.
3. If user already exists, show message.
4. If user does not exist, show user not found.
5. If password is correct, show welcome.
6. If password is wrong, show incorrect password.
7. Use try and except.
8. Store each user password in username.txt file.
</code></pre>
<hr />
<h1>14. Day 3 Final Summary</h1>
<p>Today we learned:</p>
<pre><code class="language-text">List slicing:
Used to get part of a list.

Tuple:
Used to store multiple values that should not change.

Dictionary:
Used to store data in key-value pairs.

Set:
Used to store unique values.

Exception handling:
Used to handle errors without crashing the program.

File handling:
Used to create, read, write, and append files.

Login system:
Used file handling and exception handling together.
</code></pre>
<p>Final simple memory:</p>
<pre><code class="language-text">List      -&gt; changeable collection
Tuple     -&gt; unchangeable collection
Dictionary -&gt; key-value collection
Set       -&gt; unique value collection
try-except -&gt; error handling
File      -&gt; permanent data storage
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Introduction to Programming and Python Day-1
]]></title><description><![CDATA[Programming is the process of giving instructions to a computer so that it can perform a task. A computer is a powerful machine, but it cannot think or…]]></description><link>https://piankit.hashnode.dev/introduction-to-programming-and-python-day-1</link><guid isPermaLink="true">https://piankit.hashnode.dev/introduction-to-programming-and-python-day-1</guid><dc:creator><![CDATA[Ankit Chapagain]]></dc:creator><pubDate>Tue, 19 May 2026 12:21:56 GMT</pubDate><content:encoded><![CDATA[<h2>1. What is Programming?</h2>
<p>Programming is the process of giving instructions to a computer so that it can perform a task.</p>
<p>A computer is a powerful machine, but it cannot think or work by itself. It needs clear instructions from humans.</p>
<p>Programming is mainly about solving problems and getting the expected output from the computer.</p>
<p>Example tasks done by programming:</p>
<ol>
<li><p>Calculating marks</p>
</li>
<li><p>Creating a bill</p>
</li>
<li><p>Storing student records</p>
</li>
<li><p>Making websites</p>
</li>
<li><p>Automating repeated work</p>
</li>
</ol>
<hr />
<h2>2. What is a Program?</h2>
<p>A program is a set of instructions written to perform a specific task.</p>
<p>For example, if we want a computer to calculate the total price of products, we write instructions for it. Those instructions together are called a program.</p>
<p>In simple words:</p>
<p>Program = instructions given to the computer</p>
<hr />
<h2>3. What is a Programming Language?</h2>
<p>A programming language is a language used to write programs.</p>
<p>Computers understand machine language, which is based on 0 and 1. But writing in 0 and 1 is very difficult for humans.</p>
<p>So, programming languages are used to write instructions in a human-friendly way.</p>
<p>Examples of programming languages:</p>
<ol>
<li><p>Python</p>
</li>
<li><p>C</p>
</li>
<li><p>C++</p>
</li>
<li><p>Java</p>
</li>
<li><p>JavaScript</p>
</li>
</ol>
<hr />
<h2>4. Program, Programming, and Programming Language</h2>
<table>
<thead>
<tr>
<th>Term</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td>Program</td>
<td>Set of instructions</td>
</tr>
<tr>
<td>Programming</td>
<td>Process of writing instructions</td>
</tr>
<tr>
<td>Programming Language</td>
<td>Language used to write instructions</td>
</tr>
</tbody></table>
<p>Example:</p>
<p>A calculator app is a program.</p>
<p>Creating that calculator app is programming.</p>
<p>Using Python to create it means Python is the programming language.</p>
<hr />
<h2>5. Why Do We Need Programming?</h2>
<p>We need programming to make computers perform tasks automatically, quickly, and accurately.</p>
<p>Without programming, computers cannot do useful work by themselves.</p>
<p>Programming is used to:</p>
<ol>
<li><p>Solve problems</p>
</li>
<li><p>Save time</p>
</li>
<li><p>Reduce human errors</p>
</li>
<li><p>Automate repeated tasks</p>
</li>
<li><p>Build software, apps, and websites</p>
</li>
</ol>
<hr />
<h2>6. What is Programming Paradigm?</h2>
<p>A programming paradigm is a style or method of writing programs.</p>
<p>It means how we organize and write our code to solve a problem.</p>
<p>Main programming paradigms are:</p>
<ol>
<li><p>Procedural Programming</p>
</li>
<li><p>Object-Oriented Programming</p>
</li>
<li><p>Functional Programming</p>
</li>
</ol>
<hr />
<h2>7. Procedural Programming</h2>
<p>Procedural programming is a style of programming where instructions are written step by step.</p>
<p>It focuses on procedures or functions.</p>
<p>In simple words:</p>
<p>Do this first, then do that, then show the result.</p>
<p>It is useful for simple and step-by-step programs.</p>
<p>Example tasks:</p>
<ol>
<li><p>Calculating total marks</p>
</li>
<li><p>Finding simple interest</p>
</li>
<li><p>Printing a bill</p>
</li>
</ol>
<hr />
<h2>8. Object-Oriented Programming</h2>
<p>Object-Oriented Programming, or OOP, is a style of programming based on objects.</p>
<p>An object represents a real-world thing.</p>
<p>Examples of objects:</p>
<ol>
<li><p>Student</p>
</li>
<li><p>Car</p>
</li>
<li><p>Bank account</p>
</li>
<li><p>Product</p>
</li>
<li><p>Customer</p>
</li>
</ol>
<p>Each object has properties and actions.</p>
<p>For example, a student can have:</p>
<p>Properties:</p>
<ul>
<li><p>Name</p>
</li>
<li><p>Age</p>
</li>
<li><p>Roll number</p>
</li>
</ul>
<p>Actions:</p>
<ul>
<li><p>Study</p>
</li>
<li><p>Attend class</p>
</li>
<li><p>Give exam</p>
</li>
</ul>
<p>OOP is useful for organizing large programs.</p>
<hr />
<h2>9. Functional Programming</h2>
<p>Functional programming is a style of programming where problems are solved mainly using functions.</p>
<p>A function takes input, processes it, and gives output.</p>
<p>In simple words:</p>
<p>Input → Function → Output</p>
<p>Functional programming is useful when we want clean and predictable results.</p>
<hr />
<h2>10. What is Python?</h2>
<p>Python is a high-level, general-purpose programming language.</p>
<p>It is used to create different types of programs and applications.</p>
<p>Python is popular because it is simple, readable, and beginner-friendly.</p>
<p>Python was created by Guido van Rossum and first released in 1991.</p>
<hr />
<h2>11. Why Python?</h2>
<p>Python is used because:</p>
<ol>
<li><p>Easy to learn<br />Python is simple and readable, so beginners can understand it easily.</p>
</li>
<li><p>Beginner-friendly<br />Students can focus more on logic instead of complex syntax.</p>
</li>
<li><p>Used in many fields<br />Python is used in web development, automation, data analysis, AI, and software development.</p>
</li>
<li><p>Large library support<br />Python has many ready-made libraries that help developers work faster.</p>
</li>
<li><p>Strong community support<br />Python has a large community, so learning materials and solutions are easily available.</p>
</li>
</ol>
<hr />
<h2>12. Introduction to Python</h2>
<p>Python is a programming language used to give instructions to a computer.</p>
<p>It is called a high-level language because it is easier for humans to read and write.</p>
<p>Python is also an interpreted language, which means Python runs code line by line.</p>
<p>Python files usually have the extension:</p>
<pre><code class="language-plaintext">.py
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">main.py
</code></pre>
<hr />
<h2>13. Features of Python</h2>
<p>Main features of Python are:</p>
<ol>
<li><p>Simple and easy to read</p>
</li>
<li><p>Free and open-source</p>
</li>
<li><p>Works on Windows, Linux, and macOS</p>
</li>
<li><p>Has many libraries</p>
</li>
<li><p>Supports different programming styles</p>
</li>
</ol>
<hr />
<h2>14. Where is Python Used?</h2>
<p>Python is used in many areas, such as:</p>
<ol>
<li><p>Web development</p>
</li>
<li><p>Data analysis</p>
</li>
<li><p>Artificial intelligence</p>
</li>
<li><p>Automation</p>
</li>
<li><p>Software development</p>
</li>
</ol>
<hr />
<h2>Memory Management</h2>
<h3>1. What is Memory Management?</h3>
<p>Memory management means how a programming language stores, uses, and removes data from computer memory while a program is running.</p>
<p>When we create variables, objects, lists, strings, or functions, they need space in memory.</p>
<p>Python manages most of this memory automatically, so the programmer does not need to manually allocate and delete memory like in some other languages.</p>
<h3>2. Why Memory Management is Needed?</h3>
<p>Memory management is needed because:</p>
<ol>
<li><p>Programs need memory to store data.</p>
</li>
<li><p>Unused data should be removed from memory.</p>
</li>
<li><p>Memory should be used efficiently.</p>
</li>
<li><p>Programs should not become slow because of unnecessary memory usage.</p>
</li>
<li><p>It helps avoid memory-related errors.</p>
</li>
</ol>
<img src="https://cdn.hashnode.com/uploads/covers/6a09686f5b726333fde83fa5/d3377c0b-28f2-495b-bbae-4aad7d2bcefa.png" alt="" style="display:block;margin:0 auto" />

<h1>3. Stack Memory</h1>
<p>Stack memory is used to store temporary information during program execution.</p>
<p>It mainly stores:</p>
<ol>
<li><p>Function calls</p>
</li>
<li><p>Local variables</p>
</li>
<li><p>References to objects</p>
</li>
</ol>
<p>Stack works in a last in, first out order.</p>
<p>That means the function that is called last will finish first.</p>
<p>Example idea:</p>
<pre><code class="language-plaintext">Function starts → memory is added to stack
Function ends → memory is removed from stack
</code></pre>
<p>Stack memory is fast and temporary.</p>
<h3>4. Heap Memory</h3>
<p>Heap memory is used to store objects and data created during program execution.</p>
<p>In Python, actual objects are stored in heap memory.</p>
<p>Examples of objects stored in heap:</p>
<ol>
<li><p>Numbers</p>
</li>
<li><p>Strings</p>
</li>
<li><p>Lists</p>
</li>
<li><p>Dictionaries</p>
</li>
<li><p>Custom objects</p>
</li>
</ol>
<p>Heap memory is larger than stack memory and is used for data that may be needed for a longer time.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a09686f5b726333fde83fa5/34034314-e41a-4e8c-ac5e-85009f1ce0b9.png" alt="" style="display:block;margin:0 auto" />

<h2>5. Garbage Collection</h2>
<img src="https://cdn.hashnode.com/uploads/covers/6a09686f5b726333fde83fa5/49098a45-f7b3-49c4-8033-854357a9327f.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/uploads/covers/6a09686f5b726333fde83fa5/3fffabb8-d174-45cb-8076-3267b54c93e1.png" alt="" style="display:block;margin:0 auto" />

<p>Garbage collection is the process of removing unused objects from memory.</p>
<p>When an object is no longer needed and no variable refers to it, Python automatically removes it from memory.</p>
<p>Example:</p>
<pre><code class="language-plaintext">a = [1, 2, 3]
a = "Hello"
</code></pre>
<p>At first, <code>a</code> refers to the list <code>[1, 2, 3]</code>.</p>
<p>Later, <code>a</code> refers to <code>"Hello"</code>.</p>
<p>Now, if no other variable refers to <code>[1, 2, 3]</code>, Python can remove that list from memory.</p>
<p>This automatic cleaning process is called garbage collection.</p>
<h1>Python Installation and Virtual Environment Setup</h1>
<h2>1. Installing Python</h2>
<p>Python must be installed before we can write and run Python programs.</p>
<p>To check whether Python is already installed, open terminal or command prompt and type:</p>
<pre><code class="language-plaintext">python --version
</code></pre>
<p>or</p>
<pre><code class="language-plaintext">python3 --version
</code></pre>
<p>If Python is installed, it will show the version.</p>
<p>Example:</p>
<pre><code class="language-plaintext">Python 3.x.x
</code></pre>
<hr />
<h1>2. Installing Python on Windows</h1>
<h2>Step 1: Download Python</h2>
<p>Go to the official Python website and download Python for Windows.</p>
<h2>Step 2: Run the installer</h2>
<p>Open the downloaded installer.</p>
<p>Very important:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a0c4d51883727741141ff35/14277c8c-688f-446a-a7e9-d18fe5c5801d.png" alt="" style="display:block;margin:0 auto" />

<pre><code class="language-plaintext">Tick/Add: Add Python to PATH
</code></pre>
<p>Then click:</p>
<pre><code class="language-plaintext">Install Now
</code></pre>
<h2>Step 3: Check installation</h2>
<p>Open Command Prompt and type:</p>
<pre><code class="language-plaintext">python --version
</code></pre>
<p>Also check pip:</p>
<pre><code class="language-plaintext">pip --version
</code></pre>
<p><code>pip</code> is used to install Python packages.</p>
<hr />
<h1>3. Installing Python on macOS</h1>
<p>macOS may already have Python installed, but it is better to install the latest Python 3 version.</p>
<h2>Option 1: Install from official website</h2>
<p>Download Python for macOS from the official Python website and install it.</p>
<p>Then check:</p>
<pre><code class="language-plaintext">python3 --version
</code></pre>
<p>Check pip:</p>
<pre><code class="language-plaintext">pip3 --version
</code></pre>
<h2>Option 2: Install using Homebrew</h2>
<p>If Homebrew is installed, use:</p>
<pre><code class="language-plaintext">brew install python
</code></pre>
<p>Then check:</p>
<pre><code class="language-plaintext">python3 --version
</code></pre>
<hr />
<h1>4. Installing Python on Linux</h1>
<p>Most Linux systems already have Python installed.</p>
<p>Check using:</p>
<pre><code class="language-plaintext">python3 --version
</code></pre>
<p>If Python is not installed, install it using the package manager.</p>
<h2>Ubuntu/Debian</h2>
<pre><code class="language-plaintext">sudo apt update
sudo apt install python3 python3-pip python3-venv
</code></pre>
<p>Check installation:</p>
<pre><code class="language-plaintext">python3 --version
pip3 --version
</code></pre>
<hr />
<h1>5. What is pip?</h1>
<p><code>pip</code> is the package manager for Python.</p>
<p>It is used to install external Python packages.</p>
<p>Example:</p>
<pre><code class="language-plaintext">pip install django
</code></pre>
<p>or on macOS/Linux:</p>
<pre><code class="language-plaintext">pip3 install django
</code></pre>
<p>Packages are ready-made tools or libraries that help us build projects faster.</p>
<hr />
<h1>6. What is a Virtual Environment?</h1>
<p>A virtual environment is a separate workspace for a Python project.</p>
<p>It allows each project to have its own packages and dependencies.</p>
<p>In simple words:</p>
<pre><code class="language-plaintext">Virtual environment = separate Python setup for one project
</code></pre>
<hr />
<h1>7. Why Do We Need a Virtual Environment?</h1>
<p>We need a virtual environment because different projects may need different package versions.</p>
<p>Example:</p>
<pre><code class="language-plaintext">Project A needs Django 4
Project B needs Django 5
</code></pre>
<p>If we install everything globally, there may be conflicts.</p>
<p>A virtual environment solves this problem by keeping packages separate for each project.</p>
<hr />
<h1>8. Benefits of Virtual Environment</h1>
<ol>
<li><p>Keeps each project separate</p>
</li>
<li><p>Avoids package version conflicts</p>
</li>
<li><p>Keeps the main system clean</p>
</li>
<li><p>Makes projects easier to share</p>
</li>
<li><p>It is a professional Python practice</p>
</li>
</ol>
<hr />
<h1>9. Creating a Project Folder</h1>
<p>First, create a folder for your project.</p>
<h2>Windows</h2>
<pre><code class="language-plaintext">mkdir my_project
cd my_project
</code></pre>
<h2>macOS/Linux</h2>
<pre><code class="language-plaintext">mkdir my_project
cd my_project
</code></pre>
<hr />
<h1>10. Creating Virtual Environment</h1>
<h2>Windows</h2>
<pre><code class="language-plaintext">python -m venv venv
</code></pre>
<h2>macOS/Linux</h2>
<pre><code class="language-plaintext">python3 -m venv venv
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>python -m venv</code> means create a virtual environment.</p>
</li>
<li><p><code>venv</code> is the name of the virtual environment folder.</p>
</li>
</ul>
<p>You can use another name, but <code>venv</code> is commonly used.</p>
<hr />
<h1>11. Activating Virtual Environment</h1>
<p>After creating the virtual environment, we need to activate it.</p>
<h2>Windows</h2>
<pre><code class="language-plaintext">venv\Scripts\activate
</code></pre>
<h2>macOS/Linux</h2>
<pre><code class="language-plaintext">source venv/bin/activate
</code></pre>
<p>After activation, you will see:</p>
<pre><code class="language-plaintext">(venv)
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">(venv) my_project&gt;
</code></pre>
<p>This means the virtual environment is active.</p>
<hr />
<h1>12. Installing Packages Inside Virtual Environment</h1>
<p>After activating the virtual environment, install packages normally.</p>
<p>Example:</p>
<pre><code class="language-plaintext">pip install requests
</code></pre>
<p>or:</p>
<pre><code class="language-plaintext">pip install django
</code></pre>
<p>These packages will be installed only inside that project's virtual environment.</p>
<p>They will not affect other projects.</p>
<hr />
<h1>13. Checking Installed Packages</h1>
<p>To see installed packages:</p>
<pre><code class="language-plaintext">pip list
</code></pre>
<p>This shows the packages installed inside the active virtual environment.</p>
<hr />
<h1>14. Saving Packages</h1>
<p>To save installed packages in a file:</p>
<pre><code class="language-plaintext">pip freeze &gt; requirements.txt
</code></pre>
<p>This creates a file named:</p>
<pre><code class="language-plaintext">requirements.txt
</code></pre>
<p>It contains the list of packages used in the project.</p>
<hr />
<h1>15. Installing Packages from requirements.txt</h1>
<p>When someone shares a Python project, they usually share a <code>requirements.txt</code> file.</p>
<p>To install all required packages:</p>
<pre><code class="language-plaintext">pip install -r requirements.txt
</code></pre>
<hr />
<h1>16. Deactivating Virtual Environment</h1>
<p>To close the virtual environment:</p>
<pre><code class="language-plaintext">deactivate
</code></pre>
<p>After this, <code>(venv)</code> disappears from the terminal.</p>
<hr />
<h1>17. Common Python Project Setup Flow</h1>
<h2>Windows</h2>
<pre><code class="language-plaintext">mkdir my_project
cd my_project
python -m venv venv
venv\Scripts\activate
pip install package_name
pip freeze &gt; requirements.txt
deactivate
</code></pre>
<h2>macOS/Linux</h2>
<pre><code class="language-plaintext">mkdir my_project
cd my_project
python3 -m venv venv
source venv/bin/activate
pip install package_name
pip freeze &gt; requirements.txt
deactivate
</code></pre>
<hr />
<h1>First Code in Python</h1>
<p>After installing Python and setting up the virtual environment, the first program we usually write is:</p>
<pre><code class="language-plaintext">print("Hello, World!")
</code></pre>
]]></content:encoded></item></channel></rss>