Author: saqibkhan

  • Remove Array Items

    Removing array items in Python

    Python arrays are a mutable sequence which means operation like adding new elements and removing existing elements can be performed with ease. We can remove an element from an array by specifying its value or position within the given array.

    The array module defines two methods namely remove() and pop(). The remove() method removes the element by value whereas the pop() method removes array item by its position.

    Python does not provide built-in support for arrays, however, we can use the array module to achieve the functionality like an array.

    Remove First Occurrence

    To remove the first occurrence of a given value from the array, use remove() method. This method accepts an element and removes it if the element is available in the array.

    Syntax

    array.remove(v)

    Where, v is the value to be removed from the array.

    Example

    The below example shows the usage of remove() method. Here, we are removing an element from the specified array.

    Open Compiler

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# before removing arrayprint("Before removing:", numericArray)# removing array
    numericArray.remove(311)# after removing arrayprint("After removing:", numericArray)

    It will produce the following output −

    Before removing: array('i', [111, 211, 311, 411, 511])
    After removing: array('i', [111, 211, 411, 511])
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Remove Items from Specific Indices

    To remove an array element from specific index, use the pop() method. This method removes an element at the specified index from the array and returns the element at ith position after removal.

    Syntax

    array.pop(i)

    Where, i is the index for the element to be removed.

    Example

    In this example, we will see how to use pop() method to remove elements from an array.

    Open Compiler

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# before removing arrayprint("Before removing:", numericArray)# removing array
    numericArray.pop(3)# after removing arrayprint("After removing:", numericArray)

    It will produce the following output −

    Before removing: array('i', [111, 211, 311, 411, 511])
    After removing: array('i', [111, 211, 311, 511])
  • Copy Arrays

    In Python, copying an array refers to the process of creating a new array that contains all the elements of the original array. This operation can be done using assignment operator (=) and deepcopy() method. In this chapter, we discuss how to copy an array object to another. But, before getting into the details let’s breifly discuss arrays.

    Python’s built-in sequence types i.e. listtuple, and string are indexed collection of items. However, unlike arrays in C/C++, Java etc. they are not homogenous, in the sense the elements in these types of collection may be of different types. Python’s array module helps you to create object similar to Java like arrays.

    Python arrays can be of string, integer or float type. The array class constructor is used as follows −

    import array
    obj = array.array(typecode[, initializer])

    Where, the typecode may be a character constant representing the data type.

    Copy Arrays Using Assignment Operator

    We can assign an array to another by using the assignment operator (=). However, such assignment doesn’t create a new array in the memory. Instead, it creates a new reference to the same array.

    Example

    In the following example, we are using assignment operator to copy array in Python.

    Open Compiler

    import array as arr
    a = arr.array('i',[110,220,330,440,550])
    b = a
    print("Copied array:",b)print(id(a),id(b))

    It will produce the following output −

    Copied array: array('i', [110, 220, 330, 440, 550])
    134485392383792 134485392383792
    

    Check the id() of both a and b. Same value of id confirms that simple assignment doesn’t create a copy. Since “a” and “b” refer to the same array object, any change in the array “a” will reflect in “b” too −

    a[2]=10print(a,b)

    It will produce the following output −

    array('i', [110, 220, 10, 440, 550]) array('i', [110, 220, 10, 440, 550])
    

    Copy Arrays Using Deep Copy

    To create another physical copy of an array, we use another module in Python library, named copy and use deepcopy() function in the module. A deep copy constructs a new compound object and then, recursively inserts copies into it of the objects found in the original.

    Example

    The following example demonstrates how to copy array in Python −

    Open Compiler

    import array as arr
    import copy
    a = arr.array('i',[110,220,330,440,550])
    b = copy.deepcopy(a)print("Copied array:",b)

    On executing, it will produce the following output −

    Copied array: array('i', [110, 220, 330, 440, 550])
    

    Now check the id() of both “a” and “b”. You will find the ids are different.

    print(id(a),id(b))

    It will produce the following output −

    2771967069936 2771967068976
    

    This proves that a new object “b” is created which is an actual copy of “a”. If we change an element in “a”, it is not reflected in “b”.

    a[2]=10print(a,b)

    It will produce the following output −

    array('i', [110, 220, 10, 440, 550]) array('i', [110, 220, 330, 440, 550])
  • Customer Relationship Management (CRM)

    Step 1: Set Up Your Environment

    1. Install Required Packages: Make sure you have Python installed, then set up a virtual environment and install Flask and SQLAlchemy.
    mkdir crm_app cd crm_app python -m venv venv source venv/bin/activate # On Windows use venv\Scripts\activate pip install Flask Flask-SQLAlchemy

    Step 2: Create the Database Model

    Create a file named app.py:

    from flask import Flask, request, jsonify
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///crm.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = SQLAlchemy(app)
    
    class Customer(db.Model):
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)
    phone = db.Column(db.String(20), nullable=True)
    def to_dict(self):
        return {"id": self.id, "name": self.name, "email": self.email, "phone": self.phone}
    with app.app_context():
    db.create_all()

    Step 3: Create API Endpoints

    Add the following code to app.py to create API endpoints for managing customers:

    @app.route('/customers', methods=['POST'])
    def add_customer():
    
    data = request.get_json()
    new_customer = Customer(name=data['name'], email=data['email'], phone=data.get('phone'))
    db.session.add(new_customer)
    db.session.commit()
    return jsonify(new_customer.to_dict()), 201
    @app.route('/customers', methods=['GET']) def get_customers():
    customers = Customer.query.all()
    return jsonify([customer.to_dict() for customer in customers])
    @app.route('/customers/<int:id>', methods=['GET']) def get_customer(id):
    customer = Customer.query.get_or_404(id)
    return jsonify(customer.to_dict())
    @app.route('/customers/<int:id>', methods=['PUT']) def update_customer(id):
    data = request.get_json()
    customer = Customer.query.get_or_404(id)
    customer.name = data&#91;'name']
    customer.email = data&#91;'email']
    customer.phone = data.get('phone')
    db.session.commit()
    return jsonify(customer.to_dict())
    @app.route('/customers/<int:id>', methods=['DELETE']) def delete_customer(id):
    customer = Customer.query.get_or_404(id)
    db.session.delete(customer)
    db.session.commit()
    return '', 204
    if __name__ == '__main__':
    app.run(debug=True)

    Step 4: Run the Application

    Run your Flask app:

    python app.py
    

    Step 5: Test the API

    You can test your API using tools like Postman or cURL. Here are some example requests:

    1. Add a Customer:
    curl -X POST http://127.0.0.1:5000/customers -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "[email protected]", "phone": "123-456-7890"}'
    1. Get All Customers:
    curl http://127.0.0.1:5000/customers
    1. Get a Specific Customer:
    curl http://127.0.0.1:5000/customers/1
    1. Update a Customer:
    curl -X PUT http://127.0.0.1:5000/customers/1 -H "Content-Type: application/json" -d '{"name": "Jane Doe", "email": "[email protected]", "phone": "098-765-4321"}'
    1. Delete a Customer:
    curl -X DELETE http://127.0.0.1:5000/customers/1
  • Loop Arrays

    Loops are used to repeatedly execute a block of code. In Python, there are two types of loops named for loop and while loop. Since the array object behaves like a sequence, you can iterate through its elements with the help of loops.

    The reason for looping through arrays is to perform operations such as accessing, modifying, searching, or aggregating elements of the array.

    Python for Loop with Array

    The for loop is used when the number of iterations is known. If we use it with an iterable like array, the iteration continues until it has iterated over every element in the array.

    Example

    The below example demonstrates how to iterate over an array using the “for” loop −

    Open Compiler

    import array as arr
    newArray = arr.array('i',[56,42,23,85,45])for iterate in newArray:print(iterate)

    The above code will produce the following result −

    56
    42
    23
    85
    45
    

    Python while Loop with Array

    In while loop, the iteration continues as long as the specified condition is true. When you are using this loop with arrays, initialize a loop variable before entering the loop. This variable often represents an index for accessing elements in the array. Inside the while loop, iterate over the array elements and manually update the loop variable.

    Example

    The following example shows how you can loop through an array using a while loop −

    Open Compiler

    import array as arr
    
    # creating array
    a = arr.array('i',[96,26,56,76,46])# checking the length
    l =len(a)# loop variable
    idx =0# while loopwhile idx < l:print(a[idx])# incrementing the while loop
       idx+=1

    On executing the above code, it will display the following output −

    96
    26
    56
    76
    46
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Python for Loop with Array Index

    We can find the length of array with built-in len() function. Use it to create a range object to get the series of indices and then access the array elements in a for loop.

    Example

    The code below illustrates how to use for loop with array index.

    Open Compiler

    import array as arr
    a = arr.array('d',[56,42,23,85,45])
    l =len(a)for x inrange(l):print(a[x])

    On running the above code, it will show the below output −

    56.0
    42.0
    23.0
    85.0
    45.0
  • Inventory Management System

    Inventory Management System (IMS)

    Requirements

    • Python 3.x
    • Basic knowledge of Python

    Code

    class Item:
    
    def __init__(self, name, quantity, price):
        self.name = name
        self.quantity = quantity
        self.price = price
    def __str__(self):
        return f"Item(name={self.name}, quantity={self.quantity}, price={self.price})"
    class Inventory:
    def __init__(self):
        self.items = {}
    def add_item(self, name, quantity, price):
        if name in self.items:
            self.items&#91;name].quantity += quantity
        else:
            self.items&#91;name] = Item(name, quantity, price)
        print(f"Added {quantity} of {name}.")
    def update_item(self, name, quantity=None, price=None):
        if name in self.items:
            if quantity is not None:
                self.items&#91;name].quantity = quantity
            if price is not None:
                self.items&#91;name].price = price
            print(f"Updated {name}.")
        else:
            print(f"Item {name} not found.")
    def delete_item(self, name):
        if name in self.items:
            del self.items&#91;name]
            print(f"Deleted {name}.")
        else:
            print(f"Item {name} not found.")
    def view_inventory(self):
        if not self.items:
            print("Inventory is empty.")
        else:
            for item in self.items.values():
                print(item)
    def main():
    inventory = Inventory()
    while True:
        print("\nInventory Management System")
        print("1. Add Item")
        print("2. Update Item")
        print("3. Delete Item")
        print("4. View Inventory")
        print("5. Exit")
        choice = input("Choose an option: ")
        if choice == '1':
            name = input("Enter item name: ")
            quantity = int(input("Enter quantity: "))
            price = float(input("Enter price: "))
            inventory.add_item(name, quantity, price)
        elif choice == '2':
            name = input("Enter item name: ")
            quantity = input("Enter new quantity (leave blank to skip): ")
            price = input("Enter new price (leave blank to skip): ")
            inventory.update_item(name, quantity=int(quantity) if quantity else None,
                                  price=float(price) if price else None)
        elif choice == '3':
            name = input("Enter item name: ")
            inventory.delete_item(name)
        elif choice == '4':
            inventory.view_inventory()
        elif choice == '5':
            print("Exiting...")
            break
        else:
            print("Invalid choice. Please try again.")
    if __name__ == "__main__":
    main()

    How It Works

    1. Classes:
      • Item: Represents an individual item with attributes for name, quantity, and price.
      • Inventory: Manages a collection of items, allowing you to add, update, delete, and view items.
    2. Functions:
      • add_item(): Adds a new item or updates the quantity if it already exists.
      • update_item(): Updates the quantity and/or price of an existing item.
      • delete_item(): Deletes an item from the inventory.
      • view_inventory(): Displays all items in the inventory.
    3. Main Loop: The main() function provides a simple console menu for user interaction.

    Running the Code

    1. Save the code to a file named inventory_management.py.
    2. Run the script using Python:
    python inventory_management.py
  •  Add Array Items

    Python array is a mutable sequence which means they can be changed or modified whenever required. However, items of same data type can be added to an array. In the similar way, you can only join two arrays of the same data type.

    Python does not have built-in support for arrays, it uses array module to achieve the functionality like an array.

    Adding Elements to Python Array

    There are multiple ways to add elements to an array in Python −

    • Using append() method
    • Using insert() method
    • Using extend() method

    Using append() method

    To add a new element to an array, use the append() method. It accepts a single item as an argument and append it at the end of given array.

    Syntax

    Syntax of the append() method is as follows −

    append(v)

    Where,

    • v − new value is added at the end of the array. The new value must be of the same type as datatype argument used while declaring array object.

    Example

    Here, we are adding element at the end of specified array using append() method.

    Open Compiler

    import array as arr
    a = arr.array('i',[1,2,3])
    a.append(10)print(a)

    It will produce the following output −

    array('i', [1, 2, 3, 10])
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Using insert() method

    It is possible to add a new element at the specified index using the insert() method. The array module in Python defines this method. It accepts two parameters which are index and value and returns a new array after adding the specified value.

    Syntax

    Syntax of this method is shown below −

    insert(i, v)

    Where,

    • i − The index at which new value is to be inserted.
    • v − The value to be inserted. Must be of the arraytype.

    Example

    The following example shows how to add array elements at specific index with the help of insert() method.

    Open Compiler

    import array as arr
    a = arr.array('i',[1,2,3])
    a.insert(1,20)print(a)

    It will produce the following output −

    array('i', [1, 20, 2, 3])
    

    Using extend() method

    The extend() method belongs to Python array module. It is used to add all elements from an iterable or array of same data type.

    Syntax

    This method has the following syntax −

    extend(x)

    Where,

    • x − This parameter specifies an array or iterable.

    Example

    In this example, we are adding items from another array to the specified array.

    Open Compiler

    import array as arr
    a = arr.array('i',[1,2,3,4,5])
    b = arr.array('i',[6,7,8,9,10])
    a.extend(b)print(a)

    On executing the above code, it will produce the following output −

    array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
  • Fitness Tracker Application

    Step 1: Create the Flask Application

    app.py

    from flask import Flask, render_template, request, redirect, url_for
    import sqlite3
    
    app = Flask(__name__)
    
    def init_db():
    
    with sqlite3.connect("fitness_tracker.db") as conn:
        conn.execute('''
            CREATE TABLE IF NOT EXISTS workouts (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                date TEXT NOT NULL,
                type TEXT NOT NULL,
                duration INTEGER NOT NULL,
                calories INTEGER NOT NULL
            )
        ''')
    conn.close()
    @app.route('/') def index():
    return render_template('index.html')
    @app.route('/log', methods=['GET', 'POST']) def log():
    if request.method == 'POST':
        date = request.form&#91;'date']
        type_ = request.form&#91;'type']
        duration = request.form&#91;'duration']
        calories = request.form&#91;'calories']
        
        with sqlite3.connect("fitness_tracker.db") as conn:
            conn.execute('''
                INSERT INTO workouts (date, type, duration, calories)
                VALUES (?, ?, ?, ?)
            ''', (date, type_, duration, calories))
        
        return redirect(url_for('history'))
    return render_template('log.html')
    @app.route('/history') def history():
    with sqlite3.connect("fitness_tracker.db") as conn:
        cursor = conn.execute('SELECT * FROM workouts ORDER BY date DESC')
        workouts = cursor.fetchall()
    return render_template('history.html', workouts=workouts)
    if __name__ == '__main__':
    init_db()
    app.run(debug=True)

    Step 2: Create the HTML Templates

    templates/index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;title>Fitness Tracker&lt;/title>
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
    </head> <body>
    &lt;h1>Welcome to the Fitness Tracker&lt;/h1>
    &lt;a href="/log">Log a Workout&lt;/a>&lt;br>
    &lt;a href="/history">View Workout History&lt;/a>
    </body> </html>

    templates/log.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;title>Log a Workout&lt;/title>
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
    </head> <body>
    &lt;h1>Log a Workout&lt;/h1>
    &lt;form method="post">
        &lt;label>Date:&lt;/label>&lt;br>
        &lt;input type="date" name="date" required>&lt;br>
        &lt;label>Type:&lt;/label>&lt;br>
        &lt;input type="text" name="type" required>&lt;br>
        &lt;label>Duration (in minutes):&lt;/label>&lt;br>
        &lt;input type="number" name="duration" required>&lt;br>
        &lt;label>Calories Burned:&lt;/label>&lt;br>
        &lt;input type="number" name="calories" required>&lt;br>
        &lt;button type="submit">Log Workout&lt;/button>
    &lt;/form>
    &lt;a href="/">Back to Home&lt;/a>
    </body> </html>

    templates/history.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;title>Workout History&lt;/title>
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
    </head> <body>
    &lt;h1>Workout History&lt;/h1>
    &lt;table>
        &lt;tr>
            &lt;th>Date&lt;/th>
            &lt;th>Type&lt;/th>
            &lt;th>Duration (min)&lt;/th>
            &lt;th>Calories&lt;/th>
        &lt;/tr>
        {% for workout in workouts %}
        &lt;tr>
            &lt;td>{{ workout&#91;1] }}&lt;/td>
            &lt;td>{{ workout&#91;2] }}&lt;/td>
            &lt;td>{{ workout&#91;3] }}&lt;/td>
            &lt;td>{{ workout&#91;4] }}&lt;/td>
        &lt;/tr>
        {% endfor %}
    &lt;/table>
    &lt;a href="/">Back to Home&lt;/a>
    </body> </html>

    Step 3: Add Basic Styles

    static/styles.css

    body {
    
    font-family: Arial, sans-serif;
    margin: 20px;
    } h1 {
    color: #333;
    } table {
    width: 100%;
    border-collapse: collapse;
    } table, th, td {
    border: 1px solid #ddd;
    } th, td {
    padding: 8px;
    text-align: left;
    }

    Step 4: Run the Application

    1. Navigate to your project directory in the terminal.
    2. Run the application:
    python app.py
    1. Open your web browser and go to http://127.0.0.1:5000.
  • Access Array Items

    Accessing an array items in Python refers to the process of retrieving the value stored at a specific index in the given array. Here, index is an numerical value that indicates the location of array items. Thus, you can use this index to access elements of an array in Python.

    An array is a container that holds a fix number of items of the same type. Python uses array module to achieve the functionality like an array.

    Accessing array items in Python

    You can use the following ways to access array items in Python −

    • Using indexing
    • Using iteration
    • Using enumerate() function

    Using indexing

    The process of accessing elements of an array through the index is known as Indexing. In this process, we simply need to pass the index number inside the index operator []. The index of an array in Python starts with 0 which means you can find its first element at index 0 and the last at one less than the length of given array.

    Example

    The following example shows how to access elements of an array using indexing.

    Open Compiler

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])#indexingprint(numericArray[0])print(numericArray[1])print(numericArray[2])

    When you run the above code, it will show the following output −

    111
    211
    311
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Using iteration

    In this approach, a block of code is executed repeatedely using loops such as for and while. It is used when you want to access array elements one by one.

    Example

    In the below code, we use the for loop to access all the elements of the specified array.

    Open Compiler

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# iteration through for loopfor item in numericArray:print(item)

    On executing the above code, it will display the following result −

    111
    211
    311
    411
    511
    

    Using enumerate() function

    The enumerate() function can be used to access elements of an array. It accepts an array and an optional starting index as parameter values and returns the array items by iterating.

    Example

    In the below example, we will see how to use the enumerate() function to access array items.

    Open Compiler

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# use of enumerate() functionfor loc, val inenumerate(numericArray):print(f"Index: {loc}, value: {val}")

    It will produce the following output −

    Index: 0, value: 111
    Index: 1, value: 211
    Index: 2, value: 311
    Index: 3, value: 411
    Index: 4, value: 511
    

    Accessing a range of array items in Python

    In Python, to access a range of array items, you can use the slicing operation which is performed using index operator [] and colon (:).

    This operation is implemented using multiple formats, which are listed below −

    • Use the [:index] format to access elements from beginning to desired range.
    • To access array items from end, use [:-index] format.
    • Use the [index:] format to access array items from specific index number till the end.
    • Use the [start index : end index] to slice the array elements within a range. You can also pass an optional argument after end index to determine the increment between each index.

    Example

    The following example demonstrates the slicing operation in Python.

    Open Compiler

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[111,211,311,411,511])# slicing operationprint(numericArray[2:])print(numericArray[0:3])

    On executing the above code, it will display the following result −

    array('i', [311, 411, 511])
    array('i', [111, 211, 311])
  • Recipe Sharing Community

    Step 1: Set Up Your Environment

    1. Install Flask: You can set up a virtual environment and install Flask.
    python -m venv venv source venv/bin/activate # On Windows use venv\Scripts\activate pip install Flask
    1. Project Structure:
    recipe_community/ ├── app.py ├── templates/ │ ├── index.html │ ├── add_recipe.html └── static/ └── style.css

    Step 2: Create the Backend (app.py)

    Here’s a simple Flask application to handle recipe submissions:

    from flask import Flask, render_template, request, redirect, url_for
    
    app = Flask(__name__)
    
    # In-memory storage for recipes (you can replace this with a database later)
    recipes = []
    
    @app.route('/')
    def index():
    
    return render_template('index.html', recipes=recipes)
    @app.route('/add', methods=['GET', 'POST']) def add_recipe():
    if request.method == 'POST':
        title = request.form&#91;'title']
        ingredients = request.form&#91;'ingredients']
        instructions = request.form&#91;'instructions']
        recipes.append({
            'title': title,
            'ingredients': ingredients.split(','),
            'instructions': instructions
        })
        return redirect(url_for('index'))
    return render_template('add_recipe.html')
    if __name__ == '__main__':
    app.run(debug=True)

    Step 3: Create the Frontend (HTML Templates)

    1. index.html (to display recipes):
    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <title>Recipe Sharing Community</title> </head> <body> <h1>Recipe Sharing Community</h1> <a href="/add">Add a Recipe</a> <ul> {% for recipe in recipes %} <li> <h2>{{ recipe.title }}</h2> <h3>Ingredients:</h3> <ul> {% for ingredient in recipe.ingredients %} <li>{{ ingredient }}</li> {% endfor %} </ul> <h3>Instructions:</h3> <p>{{ recipe.instructions }}</p> </li> {% endfor %} </ul> </body> </html>
    1. add_recipe.html (to add new recipes):
    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <title>Add Recipe</title> </head> <body> <h1>Add a New Recipe</h1> <form method="POST"> <label for="title">Recipe Title:</label><br> <input type="text" id="title" name="title" required><br> <label for="ingredients">Ingredients (comma-separated):</label><br> <input type="text" id="ingredients" name="ingredients" required><br> <label for="instructions">Instructions:</label><br> <textarea id="instructions" name="instructions" required></textarea><br> <button type="submit">Submit Recipe</button> </form> <a href="/">Back to Home</a> </body> </html>

    Step 4: Add Some Basic CSS (style.css)

    You can create a simple CSS file to style your application:

    body {
    
    font-family: Arial, sans-serif;
    margin: 20px;
    } h1, h2, h3 {
    color: #333;
    } ul {
    list-style-type: none;
    padding: 0;
    } form {
    margin-bottom: 20px;
    }

    Step 5: Run Your Application

    Now you can run your Flask app:

    python app.py
    
  • Arrays

    Arrays in Python

    Unlike other programming languages like C++ or Java, Python does not have built-in support for arrays. However, Python has several data types like lists and tuples (especially lists) that are often used as arrays but, items stored in these types of sequences need not be of the same type.

    In addition, we can create and manipulate arrays the using the array module. Before proceeding further, let’s understand arrays in general.

    What are arrays?

    An array is a container which can hold a fix number of items and these items should be of the same type. Each item stored in an array is called an element and they can be of any type including integers, floats, strings, etc.

    These elements are stored at contiguous memory location. Each location of an element in an array has a numerical index starting from 0. These indices are used to identify and access the elements.

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Array Representation

    Arrays are represented as a collection of multiple containers where each container stores one element. These containers are indexed from ‘0’ to ‘n-1’, where n is the size of that particular array.

    Arrays can be declared in various ways in different languages. Below is an illustration −

    Python Array Representation

    As per the above illustration, following are the important points to be considered −

    • Index starts with 0.
    • Array length is 10 which means it can store 10 elements.
    • Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9.

    Creating Array in Python

    To create an array in Python, import the array module and use its array() function. We can create an array of three basic types namely integer, float and Unicode characters using this function.

    The array() function accepts typecode and initializer as a parameter value and returns an object of array class.

    Syntax

    The syntax for creating an array in Python is −

    # importing import array as array_name
    
    # creating array
    obj = array_name.array(typecode[, initializer])

    Where,

    • typecode − The typecode character used to speccify the type of elements in the array.
    • initializer − It is an optional value from which array is initialized. It must be a list, a bytes-like object, or iterable elements of the appropriate type.

    Example

    The following example shows how to create an array in Python using the array module.

    Open Compiler

    import array as arr
    
    # creating an array with integer type
    a = arr.array('i',[1,2,3])print(type(a), a)# creating an array with char type
    a = arr.array('u','BAT')print(type(a), a)# creating an array with float type
    a = arr.array('d',[1.1,2.2,3.3])print(type(a), a)

    It will produce the following output −

    <class 'array.array'> array('i', [1, 2, 3])
    <class 'array.array'> array('u', 'BAT')
    <class 'array.array'> array('d', [1.1, 2.2, 3.3])
    

    Python array type is decided by a single character Typecode argument. The type codes and the intended data type of array is listed below −

    typecodePython data typeByte size
    ‘b’signed integer1
    ‘B’unsigned integer1
    ‘u’Unicode character2
    ‘h’signed integer2
    ‘H’unsigned integer2
    ‘i’signed integer2
    ‘I’unsigned integer2
    ‘l’signed integer4
    ‘L’unsigned integer4
    ‘q’signed integer8
    ‘Q’unsigned integer8
    ‘f’floating point4
    ‘d’floating point8

    Basic Operations on Python Arrays

    Following are the basic operations supported by an array −

    • Traverse − Print all the array elements one by one.
    • Insertion − Adds an element at the given index.
    • Deletion − Deletes an element at the given index.
    • Search − Searches an element using the given index or by the value.
    • Update − Updates an element at the given index.

    Accessing Array Element

    We can access each element of an array using the index of the element.

    Example

    The below code shows how to access elements of an array.

    Open Compiler

    from array import*
    array1 = array('i',[10,20,30,40,50])print(array1[0])print(array1[2])

    When we compile and execute the above program, it produces the following result −

    10
    30
    

    Insertion Operation

    In insertion operation, we insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array.

    Example

    Here, we add a data element at the middle of the array using the python in-built insert() method.

    Open Compiler

    from array import*
    array1 = array('i',[10,20,30,40,50])
    array1.insert(1,60)for x in array1:print(x)

    When we compile and execute the above program, it produces the following result which shows the element is inserted at index position 1.

    10
    60
    20
    30
    40
    50
    

    Deletion Operation

    Deletion refers to removing an existing element from the array and re-organizing all elements of an array.

    Here, we remove a data element at the middle of the array using the python in-built remove() method.

    Open Compiler

    from array import*
    array1 = array('i',[10,20,30,40,50])
    array1.remove(40)for x in array1:print(x)

    When we compile and execute the above program, it produces the following result which shows the element is removed form the array.

    10
    20
    30
    50
    

    Search Operation

    You can perform a search operation on an array to find an array element based on its value or its index.

    Example

    Here, we search a data element using the python in-built index() method −

    Open Compiler

    from array import*
    array1 = array('i',[10,20,30,40,50])print(array1.index(40))

    When we compile and execute the above program, it will display the index of the searched element. If the value is not present in the array, it will return an error.

    3
    

    Update Operation

    Update operation refers to updating an existing element from the array at a given index. Here, we simply reassign a new value to the desired index we want to update.

    Example

    In this example, we are updating the value of array element at index 2.

    Open Compiler

    from array import*
    array1 = array('i',[10,20,30,40,50])
    array1[2]=80for x in array1:print(x)

    On executing the above program, it produces the following result which shows the new value at the index position 2.

    10
    20
    80
    40
    50