Friday, January 16, 2026

Python 36

 Python 36

Introduction to Jinja2

Jinja2 is  a template engine for python, mainly used with Flask(and also Django-like systems)

 It allows us to 

write HTML + Python logic

Display dynamic data 

Use loops, conditions variables 

Jinja2 gives (Clear,Reusable,Professional)

Browser understand only HTML, Python generate data,Jinja2 combines both.

Without Jinj2(Bad practice)

@app.route("/")

def home():

return "<h1>Welcome Naga</h1>

With Jinja2(Best practice)

@app.route("/")

def home():

return render_template("Index.html",name="naga")

<h1>welcome {{name}}</h1>

Create template with Jinja2

Connecting Flask to database and displaying records 


Examples :

Task1:

app.py

from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def home():
    return render_template('index.html', name=
                           "Subbu" , age=15)
if __name__=='__main__':
    app.run(debug=True)

templates>index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title> </head>
<body>
 
        {% if age >= 18 %}
           <h1>You are eligible to vote:{{name}} {{age}}</h1>
        {% else %}
            <h1>You are not eligible to vote:{{name}} {{age}}</h1>
        {% endif %}
       
</body>
</html>

You are not eligible to vote:Subbu 15

Task2:
List
app.py

from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def home():
    std = ["Raja", "Subbu", "Pavan","Kumar","Ajay"]
    return render_template('index.html', students=std)
if __name__=='__main__':
    app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title> </head>
<body>
       <ul>
        {% for stdind in students %}
                 <li>{{stdind}}</li>
        {% endfor %}
    </ul>
       
</body>
</html>
  • Raja
  • Subbu
  • Pavan
  • Kumar
  • Ajay
Task3: Display Table format

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <table border="1">
        <tr>
            <th>Student Name</th>
            <th>Age</th>
            <th>Marks</th>
        </tr>
        {% for name, age,mark in student_data %}
        <tr>
            <td>{{ name }}</td>
            <td>{{ age }}</td>
            <td>{{ mark }}</td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>
app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    std = ["Raja", "Subbu", "Pavan", "Kumar", "Ajay"]
    ag = [23, 24, 22, 25, 23]
    marks = [85, 90, 78, 88, 92]
    # Combine lists into list of tuples
    student_data = list(zip(std, ag, marks))
    return render_template('index.html', student_data=student_data)

if __name__ == '__main__':
    app.run(debug=True)


used zip function combine multiple iterables (like lists, tuples, etc.) element-wise. It creates an iterator that aggregates
elements from each of the iterables.
Output:
Student Name Age Marks
Raja 23 85
Subbu 24 90
Pavan 22 78
Kumar 25 88
Ajay 23 92


Task4: Template inheritance

base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cloud Computing In Telugu</title>

    <link rel="stylesheet" href="{{url_for('static',filename='css/style.css') }}">
</head>

<body>

<nav >
    <ul class="menu">
        <li><a href = "/">Home</a></li>
        <li><a href="/registration">Student Registration</a></li>
        <li><a href="/courses"> Courses</a></li>
    </ul>
</nav>

    <!-- Header Section -->
    <header>
        <h1>Cloud Computing In Telugu</h1>
                  <section>
            <p>Learn how websites are built from scratch</p>
    </header>

    <!-- Main Content -->
    <main>

     {% block content %}

     {% endblock %}
    </main>

    <!-- Footer -->
    <footer>
        <p>Regards,</p>
        <p>
            <a href="https://www.cloudcomputingintelugu.com" target="_blank">
                Cloud Computing In Telugu
            </a>
        </p>
    </footer>

</body>
</html>

index.html
{% extends "base.html" %}

{% block content %}
        <!-- Introduction -->
        <section id="sec1">
            <p>
                In this training, you will learn how websites are created from scratch.
                This course is designed for beginners with no prior technical background.
            </p>

            <p>
                Web development is the process of building and maintaining websites.
                It involves designing the structure, styling the appearance, and adding interactivity.
            </p>
        </section>

        <!-- Topics Covered -->
        <section id="sec2">
            <h2>Topics Covered in This Training</h2>
            <ul>
                <li>HTML fundamentals</li>
                <li>Page structure and elements</li>
                <li>Text formatting and links</li>
                <li>Images, lists, and tables</li>
                <li>Forms and user input</li>
                <li>Introduction to CSS</li>
                <li>Basics of JavaScript</li>
                <li>Pythin full-stack development</li>
            </ul>
        </section>

        <!-- Technologies Overview -->
        <section>
            <p>
                HTML is responsible for creating the structure of a web page.
                CSS is used to make the web page look attractive.
                JavaScript adds interactivity and dynamic behavior.
            </p>
        </section>

        <!-- Outcomes -->
        <section id="sec3">
            <h2>After Completing This Training, You Will Be Able To</h2>
            <ul>
                <li>Create simple and well-structured web pages</li>
                <li>Understand and read existing website code</li>
                <li>Apply basic styling using CSS</li>
                <li>Add simple interactions using JavaScript</li>
                <li>Build a strong foundation for frontend development</li>
            </ul>
        </section>

        <!-- Audience -->
        <section id="sec4">
            <p>
                This training is suitable for students, beginners, and working professionals.
                Anyone interested in building websites or starting a career in web development can join.
            </p>
        </section>
{% endblock %}

student.html
{% extends "base.html" %}

{% block content %}
<form method="post">
        <table>
            <tr><td><label>Student Name: </label></td><td><input type ="text" name="name"></td></tr>
            <tr><td><label>Course: </label></td><td><input type ="text"  name="course"></td></tr>
           
            <tr><td><label>Email Id: </label></td><td><input type ="email"   name="email"></td></tr>
            <tr style="text-align: center;"><td colspan="2"><button type="submit">Submit</button></td></tr>
        </table>
        <h1>{{msg}}</h1>

<table>
    <tr>
        <th>Student Id</th>
        <th>Student Name</th>
        <th>Course Selected</th>
        <th>Email Id</th>
    </tr>


        {% for student in std %}
        <tr>
            <td>{{student.id}}</td>
            <td>{{student.name}}</td>
            <td>{{student.course}}</td>
            <td>{{student.email}}</td>
        </tr>
        {% endfor %}
</table>

 </form>    
{% endblock %}

index.html
{% extends "base.html" %}

{% block content %}
        <!-- Introduction -->
        <section id="sec1">
            <p>
                In this training, you will learn how websites are created from scratch.
                This course is designed for beginners with no prior technical background.
            </p>

            <p>
                Web development is the process of building and maintaining websites.
                It involves designing the structure, styling the appearance, and adding interactivity.
            </p>
        </section>

        <!-- Topics Covered -->
        <section id="sec2">
            <h2>Topics Covered in This Training</h2>
            <ul>
                <li>HTML fundamentals</li>
                <li>Page structure and elements</li>
                <li>Text formatting and links</li>
                <li>Images, lists, and tables</li>
                <li>Forms and user input</li>
                <li>Introduction to CSS</li>
                <li>Basics of JavaScript</li>
                <li>Pythin full-stack development</li>
            </ul>
        </section>

        <!-- Technologies Overview -->
        <section>
            <p>
                HTML is responsible for creating the structure of a web page.
                CSS is used to make the web page look attractive.
                JavaScript adds interactivity and dynamic behavior.
            </p>
        </section>

        <!-- Outcomes -->
        <section id="sec3">
            <h2>After Completing This Training, You Will Be Able To</h2>
            <ul>
                <li>Create simple and well-structured web pages</li>
                <li>Understand and read existing website code</li>
                <li>Apply basic styling using CSS</li>
                <li>Add simple interactions using JavaScript</li>
                <li>Build a strong foundation for frontend development</li>
            </ul>
        </section>

        <!-- Audience -->
        <section id="sec4">
            <p>
                This training is suitable for students, beginners, and working professionals.
                Anyone interested in building websites or starting a career in web development can join.
            </p>
        </section>
{% endblock %}

static>css>style.css
   body{
        font-family: Arial, sans-serif;
        line-height: 1.6;
        background-color: #f4f6f8;
        margin:0;
        padding: 20px;
    }

    main{
        width:80%;
        margin:30px;
        padding: 25px;
        background-color: white;
        border-radius: 6px;

    }
    header{
        background-color: #2c3e50;
        color: white;
        padding:20px;
        text-align:center;
    }

    section{

        margin-bottom:25px

    }

    h2{
        color:#2c3e50;
        border-bottom: 2px solid #ddd ;
        padding-bottom: 5px;
    }

    ul{
        margin-left: 20px;

    }

    footer{
        text-align: center;
        padding: 15px;
        background-color: #2c3e50;
        color:white

    }
    footer a{
        color: #ffd700;
        text-decoration: none;
    }



 /* Menu bar */

 nav{
    background-color: #2c3e50;
 }

.menu{
    list-style: none;
    margin: 0;
    padding: 0;
    display: flex;
 }

.menu li{
    margin: 0;
 }

.menu li a{

    display: block;
    padding: 14px 20px;
    color: white;
    text-decoration: none;
    font-weight: bold;

 }

.menu li a{

    display: block;
    padding: 14px 20px;
    color: white;
    text-decoration: none;
    font-weight: bold;

 }

.menu li a:hover{
    background-color: #1a252f;
 }

button {
    height: 50px;
    width: 250px;
    padding: 10px 20px;
    margin: 8px;

    background-color: #2563eb;   /* Blue */
    color: white;

    border: none;
    border-radius: 8px;

    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    font-weight: 500;

    cursor: pointer;
    transition: all 0.3s ease;
}
        table {
            border-collapse: collapse;
            width: 70%;
        }
        th, td {
            border: 1px solid black;
            padding: 8px;
            text-align: center;
        }
        th {
            background-color: #f2f2f2;
        }

app.py
# pip install pymysql

from flask import Flask,render_template, request

app=Flask(__name__)
@app.route("/")
def home():
    return render_template("index.html")

@app.route("/registration",methods=["GET", "POST"])
def student():
    return render_template("student.html")

@app.route("/courses")
def courses():
    return render_template("courses.html")


if __name__=="__main__":
    app.run(debug=True)

courses.html

{% extends "base.html" %}

{% block content %}
<form>
<ul>
    <li>AWS</li>
    <li>Azure</li>
    <li>GCP</li>
    <li>DevOps</li>
</ul>
 </form>    
</body>
</html>
{% endblock %}



Output



Task 5:
Get and Post student details using database
Install: pip install pymysql for db connection

app.py
# pip install pymysql

from flask import Flask,render_template, request
import pymysql

def dbconnection():
    conn=pymysql.connect(host="Localhost",user="ccitsource",password="SourcePassword123!",database="ccitdbsource")
    return conn

app=Flask(__name__)
@app.route("/")

def home():
    return render_template("index.html")

@app.route("/registration",methods=["GET", "POST"])
def student():
    message="Get method called"
    if  request.method=="POST":
        name=request.form.get("name")
        course=request.form.get("course")
        email=request.form.get("email")
        message="Post method called"

        conn=dbconnection()
        cursor=conn.cursor()
        sql="insert into student(std_name,course,email_id) values(%s,%s,%s)"
        cursor.execute(sql,(name,course,email))
        conn.commit()
        cursor.close()
        conn.close()
        message="Student Registered Successfully"
    # GET the student details
    conn=dbconnection()
    cursor=conn.cursor(pymysql.cursors.DictCursor)
    sql="select std_name,course,email_id from student"
    cursor.execute(sql)
    student=cursor.fetchall()
    cursor.close()
    conn.close()

    return render_template("student.html", msg=message, std=student)

@app.route("/courses")
def courses():
    return render_template("courses.html")

if __name__=="__main__":
    app.run(debug=True)

index.html
--Same as above task4
base.html
--Same as above task4
style.css
--Same as above task4
student.html
{% extends "base.html" %}

{% block content %}
<form method="post">
        <table>
            <tr><td><label>Student Name: </label></td><td><input type ="text" name="name"></td></tr>
            <tr><td><label>Course: </label></td><td><input type ="text"  name="course"></td></tr>
            <tr><td><label>Email Id: </label></td><td><input type ="email"   name="email"></td></tr>
            <tr style="text-align: center;"><td colspan="2"><button type="submit">Submit</button></td></tr>
        </table>
        <h1>{{msg}}</h1>

        <table>
            <tr>
                <th>Student Name</th>
                <th>Course Selected</th>
                <th>Email Id</th>
            </tr>
                {% for student in std %}
                <tr>
                    <td>{{student.std_name}}</td>
                    <td>{{student.course}}</td>
                    <td>{{student.email_id}}</td>
                </tr>
                {% endfor %}
</table>

 </form>    
{% endblock %}

Mysql:
create table ccitdbsource.student( std_name varchar(100), mobile decimal(20), course varchar(100), email_id varchar(100));

Ouput:


Task6: Delete


Student.html

{% extends "base.html" %}

{% block content %}
<form method="post" action="/registration">
        <table>
            <tr><td><label>Student Name: </label></td><td><input type ="text" name="name"></td></tr>
            <tr><td><label>Course: </label></td><td><input type ="text"  name="course"></td></tr>
            <tr><td><label>Email Id: </label></td><td><input type ="email"   name="email"></td></tr>
            <tr style="text-align: center;"><td colspan="2"><button type="submit">Submit</button></td></tr>
        </table>
        {% if msg %}
             <h3 style="color: green;">{{ msg }}</h3>
        {% endif %}
</form>
        <table>
            <tr>
                <th>Student Name</th>
                <th>Course Selected</th>
                <th>Email Id</th>
                <th>Action</th>
            </tr>
                {% for student1 in std %}
                <tr>
                    <td>{{student1.std_name}}</td>
                    <td>{{student1.course}}</td>
                    <td>{{student1.email_id}}</td>
                    <td style="text-align:center;">
                        <form method="post" action="{{ url_for('delete_student', std_name=student1.std_name) }}">
                        <button type="delete"
                        onclick="return confirm('Are you sure you want to delete this student?')">
                        Delete
                </button>

            </form>
        </td>
                </tr>

                {% endfor %}
</table>

 </form>    
{% endblock %}

--Thanks
app.py
# pip install pymysql
from flask import Flask,render_template, request,url_for,redirect
import pymysql

app=Flask(__name__)
def dbconnection():
    conn=pymysql.connect(host="Localhost",user="ccitsource",password="SourcePassword123!",database="ccitdbsource")
    return conn

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/registration",methods=["GET", "POST"])
def student():
    message="All Students records"
    if  request.method=="POST":
        name=request.form.get("name")
        course=request.form.get("course")
        email=request.form.get("email")
        message="post method called"
       
        if name and course and email:
            conn = dbconnection()
            cursor = conn.cursor()
            sql = "INSERT INTO student (std_name, course, email_id) VALUES (%s, %s, %s)"
            cursor.execute(sql, (name, course, email))
            conn.commit()
            cursor.close()
            conn.close()
        else:
            message = "All Students records"

    # GET the student details
    conn=dbconnection()
    cursor=conn.cursor(pymysql.cursors.DictCursor)
    sql="select std_name,course,email_id from student"
    cursor.execute(sql)
    student=cursor.fetchall()
    cursor.close()
    conn.close()

    return render_template("student.html", msg=message, std=student)

@app.route("/delete_student/<string:std_name>", methods=["POST"])

def delete_student(std_name):
    conn=dbconnection()
    cursor=conn.cursor()
    sql="delete from student where std_name=%s"
    cursor.execute(sql,(std_name,))

    conn.commit()
    cursor.close()
    conn.close()
    return redirect(url_for("student"))

@app.route("/courses")
def courses():
    return render_template("courses.html")

if __name__=="__main__":
    app.run(debug=True)

remaining Same as above
base.html
style.css
index.html

Output:

-thanks..



Monday, January 12, 2026

Python 35

 Python 35

Web Development with Flask 

What is web-browser? (Chrome/edge/Firefox)

How a Web browser works 

User --> browser-->Web server--> Browser-->User 

A Web Browser can : 

Send HTTP requests(GET,POST)

Receive responses from servers 

Render HTML and apply CSS Styles

Java Script

Display Images ,videos ,text

What is web-server? (Apache/NGNX/IIS/Gunicorn/Tomcat)

A Web server is a software(and sometime hardware) that requests from a browser and send responses back(HTML,JSON,Images,etc.)

It has completed setup, which page to go all software code will be exists

Browser -->request -->webserver (routing)-->response-->Browser)

Web servers (selected List)  

   Web server                       Plant/Language     Used For 

1. Apach HTTP server -->   Cross-plantform  static & dynamic websites

2. Nginx                                 Cross-platform       High-traffic websites

3. Microsoft IIS                     Windows                 .Net web applications

4. Gunicorn                            Python                    Flask/Django production apps

5.Apache tomcat                   Java                         Java Web applications

Introduction to Flask 

 It is web framework it will take request from webserver and send response to browser. light weight frame work ,high weight django

-->Flask is a lightweight web framework written in python

-->It helps developer build web applications and APIS easily

It simple words:

 Flask helps Python programs talk to the browser.

 pip install flask

Why do we need flask?

 If you want to print a message using python, there are multiple ways.

1.Print in the terminal.

  def index():

 print("Welcome to ccit")

2.Print in the web-page 

  def index():

    return "Welcome to ccit"

Setting Up a Flask Project  

Task1:

app.py:

from flask import Flask
"""
Create a Flask application instance.
__name__ is a special Python variable that gets the name of the current module.
When the script is run directly, __name__ equals "__main__".
"""
app = Flask(__name__)
"""
Define a route for the root URL ('/').
The @app.route decorator tells Flask what URL should trigger this function.
'GET' method is the default, so methods=['GET'] is optional.
"""
@app.route('/')
def home():
    """Handle requests to the root URL and return a welcome message."""
    return "Welcome to the Flask Web Application!"
"""
Check if this script is executed directly (not imported as a module).
If so, run the Flask development server with debug mode enabled.
"""
if __name__ == '__main__':
    # Debug mode provides auto-reload and detailed error pages
    app.run(debug=True, port=5000)

 * Running on http://127.0.0.1:5000

Display test in web page :

Welcome to the Flask Web Application!

Task2: Render template

  • render_template → used to display an HTML file This allows Flask to show web pages, not just plain text.

app.py

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
    return render_template("index.html")
if __name__ == '__main__':
    app.run(debug=True, port=5000)

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cloud Computing In Telugu</title>
    <link rel="stylesheet" href="static/style.css">
</head>
<body>
<nav >
    <ul class="menu">
        <li><a href = "/">Home</a></li>
        <li><a href="/send">Send</a></li>
        <li><a href="/Student">Student</a></li>
    </ul>
</nav>
    <!-- Header Section -->
    <header>
    <h1>AWS Cloud Computing</h1>
    <section>
              <p>Learn how websites are built from scratch</p>
    </header>

    <main>
        <section id="sec4">
            <p>
                This training is suitable for students, beginners, and working professionals.
                Anyone interested in building websites or starting a career in web development can join.
            </p>
        </section>

    </main>

    <!-- Footer -->
    <footer>
        <p>Regards,</p>
        <p>
            <a href="https://www.Google.com" target="_blank">
                Google Page
            </a>
        </p>
    </footer>

</body>
</html>

Web page Output:

Above one example default method Get 

Task3: 

We have different type of method in routing get/put/post/delete

While click any button and expecting response is called post method 

app.py

from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def home():
    return render_template('index.html', title="Home Page")
@app.route('/', methods=['POST'])  
def send():
    topics = """
    <h2>Topics Covered in This Training</h2>
    <ul>
        <li>Introduction to Cloud Computing</li>
        <li>AWS Services Overview</li>
        <li>Deploying Applications on AWS</li>
        <li>Managing AWS Resources</li>
        <li>Security Best Practices</li>
    </ul>
    """
    return render_template('index.html', title="Home Page", msg=topics)

if __name__ == '__main__':
    app.run(debug=True)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cloud Computing In Telugu</title>
    <link rel="stylesheet" href="static/style.css">
</head>
<body>
<nav >
    <ul class="menu">
        <li><a href = "/">Home</a></li>
        <li><a href="/send">Send</a></li>
        <li><a href="/Student">Student</a></li>
    </ul>
</nav>
    <!-- Header Section -->
    <header>
    <h1>AWS Cloud Computing</h1>
    <section>
              <p>Learn how websites are built from scratch</p>
    </header>
    <main>
 
        <section id="sec4">
            <form method="post" >
            <button type="submit">Enroll Now</button>
            {% if msg %}
                {{ msg|safe }}
            {% endif %}
        </form>

            <h2>Join Our Cloud Computing Course Today!</h2>
         </section>
    </main>
    <!-- Footer -->
    <footer>
        <p>Regards,</p>
        <p>
            <a href="https://www.Google.com" target="_blank">
                Google Page
            </a>
        </p>
    </footer>
</body>
</html>

When click button request send to Post metod ,display below text


Web development basics:

We need  to create an object of the flask class(app=Flask(_name_)

 A route(@app.route("/")) guides the Flash framework to execute a particular python function when a specific URL is accessed 

(If _name_ =="_main_":)This block ensures that the Flask application runs only when the file is executed directly, not when it is imported 

(app.run(debug=true))starts the Flask development server 


Handling Routes:

Routing navigation the one page to another 

Routing maps URLs to specific functions (views) in your application. When a user visits a URL, Flask calls the corresponding function to handle that request.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cloud Computing In Telugu</title>
    <link rel="stylesheet" href="static/style.css">
</head>
<body>
<nav >
    <ul class="menu">
        <li><a href = "/">Home</a></li>
        <li><a href="/send1">Send</a></li>
        <li><a href="/student">Student</a></li>
    </ul>
</nav>
    <!-- Header Section -->
    <header>
    <h1>AWS Cloud Computing</h1>
    <section>
              <p>Learn how websites are built from scratch</p>
    </header>
    <main>
 
        <section id="sec4">
            <form method="post" >
            <button type="submit">Enroll Now</button>
            {% if msg %}
                {{ msg|safe }}
            {% endif %}
        </form>

            <h2>Join Our Cloud Computing Course Today!</h2>
         </section>
    </main>
    <!-- Footer -->
    <footer>
        <p>Regards,</p>
        <p>
            <a href="https://www.Google.com" target="_blank">
                Google Page
            </a>
        </p>
    </footer>
</body>
</html>

app.py 

from flask import Flask,render_template

app = Flask(__name__)
@app.route('/')
def home():
    return render_template('index.html', title="Home Page")
@app.route('/send1')
def send1():
    return "Thank you for enrolling!"

@app.route('/student')
def student():
    return "Thank you for student enrolling!"

@app.route('/', methods=['POST'])  
def send():
    topics = """
    <h2>Topics Covered in This Training</h2>
    <ul>
        <li>Introduction to Cloud Computing</li>
        <li>AWS Services Overview</li>
        <li>Deploying Applications on AWS</li>
        <li>Managing AWS Resources</li>
        <li>Security Best Practices</li>
    </ul>
    """
    return render_template('index.html', title="Home Page", msg=topics)

if __name__ == '__main__':
    app.run(debug=True)

When click Send 


It will call send tab it called send1 function 

Same way when click student tab it will call student function 



--Thanks 





Saturday, December 6, 2025

Python Day17

Python Day17

Remove Duplicate using Inheritance :

Duplicate removal in OOP means moving the common(repeated) code into a centralized place(usually a parent class).So that multiple classes can reuse it without rewriting.

Problem with duplicate code                 Solution using inheritance 

Code repeated again and again             Write one -->reuse every where

Hard to update later                               Update only in parent class 

More bugs                                                Less complexity


How inheritance help ?

Common code(name ,age show method) --> in parent class.

unique code in child classes only.

it increase the readability and reusability 

See below repeated twice:

class Student:
    def __init__(self, username: str, age: int, sfee: str):
        self.username = username
        self.age = age
        self.sfee = sfee
        print(self.username, "Student created.", self.age, self.sfee)

std = Student("john_doe", 20, "Paid")

class Faculty:
    def __init__(self, username: str, age: int, sfee: str):
        self.username = username
        self.age = age
        self.sfee = sfee
        print(self.username, "Faculty created.", self.age, self.sfee)
fac = Faculty("dr_smith", 45, "Unpaid")    


See Below code Parent class Comm

class AdminClass:
    def __init__(self, username: str, age: int, sfee: str):
        self.username = username
        self.age = age
        self.sfee = sfee
        print(self.username, "Admin created.", self.age, self.sfee)

class Student(AdminClass):
    def __init__(self, susername: str, sage: int, sfee: str):
        AdminClass.__init__(self, susername, sage, sfee)
        print(self.username, "Student created.", self.age, self.sfee)

class Faculty(AdminClass):
    def __init__(self, fusername: str, fage: int, sfee: str):
        AdminClass.__init__(self, fusername, fage, sfee)
        print(self.username, "Faculty created.", self.age, self.sfee)

std = Student("john_doe", 20, "Paid")
fac = Faculty("dr_smith", 45, "Unpaid")




See Below code Parent class Comm


See Below code Parent class Comm