Author: saqibkhan

  • File Handling

    File Handling in Python

    File handling in Python involves interacting with files on your computer to read data from them or write data to them. Python provides several built-in functions and methods for creating, opening, reading, writing, and closing files. This tutorial covers the basics of file handling in Python with examples.

    Opening a File in Python

    To perform any file operation, the first step is to open the file. Python’s built-in open() function is used to open files in various modes, such as reading, writing, and appending. The syntax for opening a file in Python is −

    file=open("filename","mode")

    Where, filename is the name of the file to open and mode is the mode in which the file is opened (e.g., ‘r’ for reading, ‘w’ for writing, ‘a’ for appending).

    File Opening Modes

    Following are the file opening modes −

    Sr.No.Modes & Description
    1rOpens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
    2rbOpens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
    3r+Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
    4rb+Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
    5wOpens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
    6bOpens the file in binary mode
    7tOpens the file in text mode (default)
    8+open file for updating (reading and writing)
    9wbOpens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
    10w+Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
    11wb+Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
    12aOpens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
    13abOpens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
    14a+Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
    15ab+Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
    16xopen for exclusive creation, failing if the file already exists

    Once a file is opened and you have one file object, you can get various information related to that file.

    Example 1

    In the following example, we are opening a file in different modes −

    # Opening a file in read modefile=open("example.txt","r")# Opening a file in write modefile=open("example.txt","w")# Opening a file in append modefile=open("example.txt","a")# Opening a file in binary read modefile=open("example.txt","rb")

    Example 2

    In here, we are opening a file named “foo.txt” in binary write mode (“wb”), printing its name, whether it’s closed, and its opening mode, and then closing the file −

    Open Compiler

    # Open a file
    fo =open("foo.txt","wb")print("Name of the file: ", fo.name)print("Closed or not: ", fo.closed)print("Opening mode: ", fo.mode)
    fo.close()

    It will produce the following output −

    Name of the file: foo.txt
    Closed or not: False
    Opening mode: wb
    

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

    Reading a File in Python

    Reading a file in Python involves opening the file in a mode that allows for reading, and then using various methods to extract the data from the file. Python provides several methods to read data from a file −

    • read() − Reads the entire file.
    • readline() − Reads one line at a time.
    • readlines − Reads all lines into a list.

    To read a file, you need to open it in read mode. The default mode for the open() function is read mode (‘r’), but it’s good practice to specify it explicitly.

    Example: Using read() method

    In the following example, we are using the read() method to read the whole file into a single string −

    withopen("example.txt","r")asfile:
       content =file.read()print(content)

    Following is the output obtained −

    Hello!!!
    Welcome to TutorialsPoint!!!
    

    Example: Using readline() method

    In here, we are using the readline() method to read one line at a time, making it memory efficient for reading large files line by line −

    withopen("example.txt","r")asfile:
       line =file.readline()while line:print(line, end='')
    
      line =file.readline()</code></pre>

    Output of the above code is as shown below −

    Hello!!!
    Welcome to TutorialsPoint!!!
    

    Example: Using readlines() method

    Now, we are using the readlines() method to read the entire file and splits it into a list where each element is a line −

    withopen("example.txt","r")asfile:
       lines =file.readlines()for line in lines:print(line, end='')

    We get the output as follows −

    Hello!!!
    Welcome to TutorialsPoint!!!
    

    Writing to a File in Python

    Writing to a file in Python involves opening the file in a mode that allows writing, and then using various methods to add content to the file.

    To write data to a file, use the write() or writelines() methods. When opening a file in write mode ('w'), the file's existing content is erased.

    Example: Using the write() method

    In this example, we are using the write() method to write the string passed to it to the file. If the file is opened in 'w' mode, it will overwrite any existing content. If the file is opened in 'a' mode, it will append the string to the end of the file −

    Open Compiler

    withopen("foo.txt","w")asfile:file.write("Hello, World!")print("Content added Successfully!!")

    Output of the above code is as follows −

    Content added Successfully!!
    

    Example: Using the writelines() method

    In here, we are using the writelines() method to take a list of strings and writes each string to the file. It is useful for writing multiple lines at once −

    Open Compiler

    lines =["First line\n","Second line\n","Third line\n"]withopen("example.txt","w")asfile:file.writelines(lines)print("Content added Successfully!!")

    The result obtained is as follows −

    Content added Successfully!!
    

    Closing a File in Python

    We can close a file in Python using the close() method. Closing a file is an essential step in file handling to ensure that all resources used by the file are properly released. It is important to close files after operations are completed to prevent data loss and free up system resources.

    Example

    In this example, we open the file for writing, write data to the file, and then close the file using the close() method −

    Open Compiler

    file=open("example.txt","w")file.write("This is an example.")file.close()print("File closed successfully!!")

    The output produced is as shown below −

    File closed successfully!!
    

    Using "with" Statement for Automatic File Closing

    The with statement is a best practice in Python for file operations because it ensures that the file is automatically closed when the block of code is exited, even if an exception occurs.

    Example

    In this example, the file is automatically closed at the end of the with block, so there is no need to call close() method explicitly −

    Open Compiler

    withopen("example.txt","w")asfile:file.write("This is an example using the with statement.")print("File closed successfully!!")

    Following is the output of the above code −

    File closed successfully!!
    

    Handling Exceptions When Closing a File

    When performing file operations, it is important to handle potential exceptions to ensure your program can manage errors gracefully.

    In Python, we use a try-finally block to handle exceptions when closing a file. The "finally" block ensures that the file is closed regardless of whether an error occurs in the try block −

    Open Compiler

    try:file=open("example.txt","w")file.write("This is an example with exception handling.")finally:file.close()print("File closed successfully!!")

    After executing the above code, we get the following output −

  • Array Exercises

    Example 1

    Python program to find the largest number in an array −

    Open Compiler

    import array as arr
    a = arr.array('i',[10,5,15,4,6,20,9])print(a)
    largest = a[0]for i inrange(1,len(a)):if a[i]>largest:
    
      largest=a&#91;i]print("Largest number:", largest)</code></pre>

    It will produce the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9])
    Largest number: 20
    

    Example 2

    Python program to store all even numbers from an array in another array −

    Open Compiler

    import array as arr
    a = arr.array('i',[10,5,15,4,6,20,9])print(a)
    b = arr.array('i')for i inrange(len(a)):if a[i]%2==0:
    
      b.append(a&#91;i])print("Even numbers:", b)</code></pre>

    It will produce the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9])
    Even numbers: array('i', [10, 4, 6, 20])
    

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

    Example 3

    Python program to find the average of all numbers in a Python array −

    Open Compiler

    import array as arr
    a = arr.array('i',[10,5,15,4,6,20,9])print(a)
    s =0for i inrange(len(a)):
       s+=a[i]
    avg = s/len(a)print("Average:", avg)# Using sum() function
    avg =sum(a)/len(a)print("Average:", avg)

    It will produce the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9])
    Average: 9.857142857142858
    Average: 9.857142857142858
    

    Exercise Programs

    • Python program find difference between each number in the array and the average of all numbers
    • Python program to convert a string in an array
    • Python program to split an array in two and store even numbers in one array and odd numbers in the other.
    • Python program to perform insertion sort on an array.
    • Python program to store the Unicode value of each character in the given array.
  • Recipe Meal Planner

    Python Code for Meal Planner

    # Meal Planner Program
    
    def display_meal_plan(meal_plan):
    
    print("\nYour Meal Plan for the Week:")
    for day, meals in meal_plan.items():
        print(f"{day}: Breakfast: {meals&#91;'Breakfast']}, Lunch: {meals&#91;'Lunch']}, Dinner: {meals&#91;'Dinner']}")
    def get_meal_input(day):
    breakfast = input(f"Enter Breakfast for {day}: ")
    lunch = input(f"Enter Lunch for {day}: ")
    dinner = input(f"Enter Dinner for {day}: ")
    return {'Breakfast': breakfast, 'Lunch': lunch, 'Dinner': dinner}
    def meal_planner():
    days_of_week = &#91;'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    meal_plan = {}
    print("Welcome to the Meal Planner!")
    for day in days_of_week:
        meal_plan&#91;day] = get_meal_input(day)
    display_meal_plan(meal_plan)
    if __name__ == "__main__":
    meal_planner()

    How It Works

    1. Function Definitions:
      • display_meal_plan(meal_plan): This function prints the meal plan for the week.
      • get_meal_input(day): This function prompts the user to input meals for breakfast, lunch, and dinner for a given day.
      • meal_planner(): The main function that orchestrates the meal planning process.
    2. User Interaction:
      • The program prompts the user to enter meals for each day of the week.
      • It then stores the meals in a dictionary and displays the entire meal plan at the end.

    Running the Code

    To run this code:

    1. Ensure you have Python installed on your machine.
    2. Copy the code into a Python file (e.g., meal_planner.py).
    3. Run the file using the command: python meal_planner.py.

    Customization Ideas

    • Save and Load Meal Plans: You can extend the program to save meal plans to a file and load them later.
    • Dietary Preferences: Add options for dietary restrictions (e.g., vegetarian, gluten-free).
    • Random Meal Suggestions: Implement a feature that suggests meals from a predefined list.
    • Nutrition Information: Include a database of meals with nutritional information.
  • Volunteer Management System

    Prerequisites

    Make sure you have Python and Flask installed. You can install Flask using pip:

    pip install Flask
    

    Project Structure

    volunteer_management/
    │
    ├── app.py
    ├── templates/
    │   ├── index.html
    │   ├── add_volunteer.html
    │   ├── edit_volunteer.html
    └── database.db
    

    Step 1: Setting Up the Database

    Create a SQLite database and a table for volunteers.

    # db_setup.py
    import sqlite3
    
    def setup_database():
    
    conn = sqlite3.connect('database.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS volunteers (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            email TEXT NOT NULL UNIQUE,
            phone TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()
    if __name__ == '__main__':
    setup_database()

    Run this script once to create the database:

    python db_setup.py
    

    Step 2: Create the Flask Application

    Create the main application file app.py:

    from flask import Flask, render_template, request, redirect, url_for
    import sqlite3
    
    app = Flask(__name__)
    
    # Function to get database connection
    def get_db_connection():
    
    conn = sqlite3.connect('database.db')
    conn.row_factory = sqlite3.Row
    return conn
    # Route to display all volunteers @app.route('/') def index():
    conn = get_db_connection()
    volunteers = conn.execute('SELECT * FROM volunteers').fetchall()
    conn.close()
    return render_template('index.html', volunteers=volunteers)
    # Route to add a new volunteer @app.route('/add', methods=('GET', 'POST')) def add_volunteer():
    if request.method == 'POST':
        name = request.form&#91;'name']
        email = request.form&#91;'email']
        phone = request.form&#91;'phone']
        conn = get_db_connection()
        conn.execute('INSERT INTO volunteers (name, email, phone) VALUES (?, ?, ?)',
                     (name, email, phone))
        conn.commit()
        conn.close()
        return redirect(url_for('index'))
    return render_template('add_volunteer.html')
    # Route to edit a volunteer @app.route('/edit/<int:id>', methods=('GET', 'POST')) def edit_volunteer(id):
    conn = get_db_connection()
    volunteer = conn.execute('SELECT * FROM volunteers WHERE id = ?', (id,)).fetchone()
    if request.method == 'POST':
        name = request.form&#91;'name']
        email = request.form&#91;'email']
        phone = request.form&#91;'phone']
        conn.execute('UPDATE volunteers SET name = ?, email = ?, phone = ? WHERE id = ?',
                     (name, email, phone, id))
        conn.commit()
        conn.close()
        return redirect(url_for('index'))
    conn.close()
    return render_template('edit_volunteer.html', volunteer=volunteer)
    # Route to delete a volunteer @app.route('/delete/<int:id>', methods=('POST',)) def delete_volunteer(id):
    conn = get_db_connection()
    conn.execute('DELETE FROM volunteers WHERE id = ?', (id,))
    conn.commit()
    conn.close()
    return redirect(url_for('index'))
    if __name__ == '__main__':
    app.run(debug=True)

    Step 3: Create HTML Templates

    Create the HTML templates in the templates/ directory.

    index.html

    <!DOCTYPE html>
    <html>
    <head>
    
    &lt;title>Volunteer Management&lt;/title>
    </head> <body>
    &lt;h1>Volunteers&lt;/h1>
    &lt;a href="/add">Add Volunteer&lt;/a>
    &lt;ul>
        {% for volunteer in volunteers %}
            &lt;li>
                {{ volunteer.name }} - {{ volunteer.email }} - {{ volunteer.phone }}
                &lt;a href="/edit/{{ volunteer.id }}">Edit&lt;/a>
                &lt;form action="/delete/{{ volunteer.id }}" method="post" style="display:inline;">
                    &lt;button type="submit">Delete&lt;/button>
                &lt;/form>
            &lt;/li>
        {% endfor %}
    &lt;/ul>
    </body> </html>

    add_volunteer.html

    <!DOCTYPE html>
    <html>
    <head>
    
    &lt;title>Add Volunteer&lt;/title>
    </head> <body>
    &lt;h1>Add Volunteer&lt;/h1>
    &lt;form method="post">
        &lt;label>Name:&lt;/label>
        &lt;input type="text" name="name" required>
        &lt;br>
        &lt;label>Email:&lt;/label>
        &lt;input type="email" name="email" required>
        &lt;br>
        &lt;label>Phone:&lt;/label>
        &lt;input type="text" name="phone" required>
        &lt;br>
        &lt;button type="submit">Add Volunteer&lt;/button>
    &lt;/form>
    </body> </html>

    edit_volunteer.html

    <!DOCTYPE html>
    <html>
    <head>
    
    &lt;title>Edit Volunteer&lt;/title>
    </head> <body>
    &lt;h1>Edit Volunteer&lt;/h1>
    &lt;form method="post">
        &lt;label>Name:&lt;/label>
        &lt;input type="text" name="name" value="{{ volunteer.name }}" required>
        &lt;br>
        &lt;label>Email:&lt;/label>
        &lt;input type="email" name="email" value="{{ volunteer.email }}" required>
        &lt;br>
        &lt;label>Phone:&lt;/label>
        &lt;input type="text" name="phone" value="{{ volunteer.phone }}" required>
        &lt;br>
        &lt;button type="submit">Update Volunteer&lt;/button>
    &lt;/form>
    </body> </html>

    Step 4: Run the Application

    You can run the application using:

    python app.py
    

    Access the application in your web browser at http://127.0.0.1:5000/.

  • Subscription-Based Content Platform

    Project Structure

    subscription_platform/
    │
    ├── app.py
    ├── models.py
    ├── templates/
    │   ├── index.html
    │   ├── login.html
    │   ├── signup.html
    │   ├── dashboard.html
    │   └── content.html
    └── static/
    
    └── style.css

    1. Set Up Flask and Dependencies

    Make sure you have Flask and its dependencies installed. You can install them using pip:

    pip install Flask Flask-SQLAlchemy Flask-Login Flask-WTF
    

    2. Create the Models

    In models.py, define the user and content models.

    from flask_sqlalchemy import SQLAlchemy
    from flask_login import UserMixin
    
    db = SQLAlchemy()
    
    class User(db.Model, UserMixin):
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), unique=True, nullable=False)
    password = db.Column(db.String(150), nullable=False)
    subscription_active = db.Column(db.Boolean, default=False)
    class Content(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(150), nullable=False)
    body = db.Column(db.Text, nullable=False)

    3. Set Up Flask Application

    In app.py, set up your Flask application and routes.

    from flask import Flask, render_template, redirect, url_for, request, flash
    from flask_sqlalchemy import SQLAlchemy
    from flask_login import LoginManager, login_user, login_required, logout_user, current_user
    from models import db, User, Content
    from werkzeug.security import generate_password_hash, check_password_hash
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'your_secret_key'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
    db.init_app(app)
    login_manager = LoginManager()
    login_manager.init_app(app)
    
    @login_manager.user_loader
    def load_user(user_id):
    
    return User.query.get(int(user_id))
    @app.route('/') def index():
    return render_template('index.html')
    @app.route('/signup', methods=['GET', 'POST']) def signup():
    if request.method == 'POST':
        username = request.form&#91;'username']
        password = request.form&#91;'password']
        hashed_password = generate_password_hash(password, method='sha256')
        new_user = User(username=username, password=hashed_password)
        db.session.add(new_user)
        db.session.commit()
        flash('Signup successful! You can now log in.')
        return redirect(url_for('login'))
    return render_template('signup.html')
    @app.route('/login', methods=['GET', 'POST']) def login():
    if request.method == 'POST':
        username = request.form&#91;'username']
        password = request.form&#91;'password']
        user = User.query.filter_by(username=username).first()
        if user and check_password_hash(user.password, password):
            login_user(user)
            return redirect(url_for('dashboard'))
        flash('Login failed. Check your credentials.')
    return render_template('login.html')
    @app.route('/dashboard') @login_required def dashboard():
    return render_template('dashboard.html', user=current_user)
    @app.route('/content/<int:content_id>') @login_required def content(content_id):
    content = Content.query.get_or_404(content_id)
    return render_template('content.html', content=content)
    @app.route('/logout') @login_required def logout():
    logout_user()
    return redirect(url_for('index'))
    if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)

    4. Create the HTML Templates

    Create basic templates in the templates folder.

    • index.html:
    <h1>Welcome to the Subscription Platform</h1> <a href="{{ url_for('signup') }}">Sign Up</a> <a href="{{ url_for('login') }}">Login</a>
    • login.html:
    <form method="POST"> <input type="text" name="username" placeholder="Username" required> <input type="password" name="password" placeholder="Password" required> <button type="submit">Login</button> </form>
    • signup.html:
    <form method="POST"> <input type="text" name="username" placeholder="Username" required> <input type="password" name="password" placeholder="Password" required> <button type="submit">Sign Up</button> </form>
    • dashboard.html:
    <h1>Hello, {{ user.username }}</h1> <a href="{{ url_for('logout') }}">Logout</a>
    • content.html:
    <h1>{{ content.title }}</h1> <p>{{ content.body }}</p> <a href="{{ url_for('dashboard') }}">Back to Dashboard</a>

    5. CSS for Basic Styling

    You can add a basic CSS file in the static folder to style your application (style.css).

    6. Running the Application

    Make sure you’re in the project directory, then run the Flask application:

    python app.py
    

    Visit http://127.0.0.1:5000/ in your web browser.

    Notes

    • Payment Processing: To implement subscriptions, integrate a payment processor like Stripe or PayPal.
    • Content Management: Expand the app to allow content creation and management by users.
    • Security: Consider enhancing security features (e.g., email verification, password recovery).
    • Deployment: Deploy the application using a platform like Heroku, AWS, or DigitalOcean.

  • Array Methods

    The array module in Python offers an efficient object type for representing arrays of basic values like characters, integers, and floating point numbers. Arrays are similar to lists but it stores a collection of homogeneous data elements in order. At the time of creating array’s type is specified using a single character type code.

    Array methods provides various operations on array objects, including appending, extending, and manipulating elements. These methods are used for efficient handling of homogeneous collections of basic data types, making them suitable for tasks requiring compact data storage, such as numerical computations.

    Python Array Class

    The array class defines several methods, including adding and removing elements, obtaining information about the array, manipulating array elements, and converting arrays to and from other data types. Below are categorized methods based on their functionality. Let’s explore and understand the functionality of each method.

    Arrays are created using the array.array(typecode[, initializer]) class, where typecode is a single character that defines the type of elements in the array, and initializer is an optional value used to initialize the array.

    Adding and Removing Elements

    Below methods are used for appending, extending, inserting, and removing elements from arrays −

    Sr.No.Methods with Description
    1append(x)Appends a new item with value x to the end of the array.
    2extend(iterable)Appends items from iterable to the end of the array.
    3insert(i, x)Inserts a new item with value x before position i.
    4pop([i])Removes and returns the item with index i. If i is not specified, removes and returns the last item.
    5remove(x)Removes the first occurrence of x from the array.

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

    Information and Utility Methods

    These methods are used for obtaining information about arrays and to perform utility operations −

    Sr.No.Methods with Description
    1buffer_info()Returns a tuple (address, length) giving the current memory address and the length in elements of the buffer used to hold the array’s contents.
    2count(x)Returns the number of occurrences of x in the array.
    3index(x[, start[, stop]])Returns the smallest index where x is found in the array. Optional start and stop arguments can specify a sub-range to search.

    Manipulating Array Elements

    Following methods are used for manipulating array elements, such as reversing the array or byteswapping values.

    Sr.No.Methods with Description
    1reverse()Reverses the order of the items in the array.
    2byteswap()“Byteswaps” all items of the array, useful for reading data from a file written on a machine with a different byte order.

    Conversion Methods

    These methods are used to convert arrays to and from bytes, files, lists, and Unicode strings.

    Sr.No.Methods with Description
    1frombytes(buffer)Appends items from the bytes-like object, interpreting its content as an array of machine values.
    2tobytes()Converts the array to a bytes representation.
    3fromfile(f, n)Reads n items from the file object f and appends them to the array.
    4tofile(f)Writes all items to the file object f.
    5fromlist(list)Appends items from the list to the array.
    6tolist()Converts the array to a list with the same items.
    7fromunicode(s)Extends the array with data from the given Unicode string. The array must have type code ‘u’.
    8tounicode()Converts the array to a Unicode string. The array must have type code ‘u’.
  • Join Arrays

    The process of joining two arrays is termed as Merging or concatenating. Python provides multiple ways to merge two arrays such as append() and extend() methods. But, before merging two arrays always ensure that both arrays are of the same data type otherwise program will throw error.

    In Pythonarray is a homogenous collection of Python’s built in data types such as strings, integer or float objects. However, array itself is not a built-in type, instead we need to use the Python’s built-in array module.

    Merge Python Array

    Join two Arrays in Python

    To join arrays in Python, use the following approaches −

    • Using append() method
    • Using + operator
    • Using extend() method

    Using append() Method

    To join two arrays, we can append each item from one array to other using append() method. To perform this operation, run a for loop on the original array, fetch each element and append it to a new array.

    Example: Join Two Arrays by Appending Elements

    Here, we use the append() method to join two arrays.

    Open Compiler

    import array as arr
    
    # creating two arrays
    a = arr.array('i',[10,5,15,4,6,20,9])
    b = arr.array('i',[2,7,8,11,3,10])# merging both arraysfor i inrange(len(b)):
       a.append(b[i])print(a)

    It will produce the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9, 2, 7, 8, 11, 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 + operator

    We can also use + operator to concatenate or merge two arrays. In this approach, we first convert arrays to list objects, then concatenate the lists using the + operator and convert back to get merged array.

    Example: Join Two Arrays by Converting to List Objects

    In this example, we will see how to join two arrays using + operator.

    Open Compiler

    import array as arr
    a = arr.array('i',[10,5,15,4,6,20,9])
    b = arr.array('i',[2,7,8,11,3,10])
    x = a.tolist()
    y = b.tolist()
    z = x+y
    a = arr.array('i', z)print(a)

    The above code will display the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9, 2, 7, 8, 11, 3, 10])
    

    Using extend() Method

    Another approach to concatenate arrays is the use of extend() method from the List class. Similar to above approach, we first convert the array to a list and then call the extend() method to merge the two lists.

    Example: Join Two Arrays using extend() Method

    In the following example, we will use the extend() method to concatenate two arrays in Python.

    Open Compiler

    import array as arr
    a = arr.array('i',[88,99,77,66,44,22])
    b = arr.array('i',[12,17,18,11,13,10])
    a.extend(b)print(a)

    It will produce the following output −

    array('i', [88, 99, 77, 66, 44, 22, 12, 17, 18, 11, 13, 10])
  • Sort Arrays

    Python’s array module defines the array class. An object of array class is similar to the array as present in Java or C/C++. Unlike the built-in Python sequences, array is a homogenous collection of either strings, or integers, or float objects.

    The array class doesn’t have any function/method to give a sorted arrangement of its elements. However, we can achieve it with one of the following approaches −

    • Using a sorting algorithm
    • Using the sort() method from List
    • Using the built-in sorted() function

    Let’s discuss each of these methods in detail.

    Python Array Sorting

    Sort Arrays Using a Sorting Algorithm

    We implement the classical bubble sort algorithm to obtain the sorted array. To do it, we use two nested loops and swap the elements for rearranging in sorted order.

    Example

    Run the following code using a Python code editor −

    Open Compiler

    import array as arr
    a = arr.array('i',[10,5,15,4,6,20,9])for i inrange(0,len(a)):for j inrange(i+1,len(a)):if(a[i]> a[j]):
    
         temp = a&#91;i];
         a&#91;i]= a&#91;j];
         a&#91;j]= temp;print(a)</code></pre>

    It will produce the following output −

    array('i', [4, 5, 6, 9, 10, 15, 20])
    

    Sort Arrays Using sort() Method of List

    Even though array module doesn't have a sort() method, Python's built-in List class does have a sort method. We shall use it in the next example.

    First, declare an array and obtain a list object from it, using tolist() method. Then, use the sort() method to get a sorted list. Lastly, create another array using the sorted list which will display a sorted array.

    Example

    The following code shows how to get sorted array using the sort() method.

    Open Compiler

    import array as arr
    
    # creating array
    orgnlArray = arr.array('i',[10,5,15,4,6,20,9])print("Original array:", orgnlArray)# converting to list 
    sortedList = orgnlArray.tolist()# sorting the list
    sortedList.sort()# creating array from sorted list
    sortedArray = arr.array('i', sortedList)print("Array after sorting:",sortedArray)

    The above code will display the following output −

    Original array: array('i', [10, 5, 15, 4, 6, 20, 9])
    Array after sorting: array('i', [4, 5, 6, 9, 10, 15, 20])
    

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

    Sort Arrays Using sorted() Method

    The third technique to sort an array is with the sorted() function, which is a built-in function.

    The syntax of sorted() function is as follows −

    sorted(iterable, reverse=False)

    The function returns a new list containing all items from the iterable in ascending order. Set reverse parameter to True to get a descending order of items.

    The sorted() function can be used along with any iterable. Python array is an iterable as it is an indexed collection. Hence, an array can be used as a parameter to sorted() function.

    Example

    In this example, we will see the use of sorted() method in sorting an array.

    Open Compiler

    import array as arr
    a = arr.array('i',[4,5,6,9,10,15,20])sorted(a)print(a)

    It will produce the following output −

    array('i', [4, 5, 6, 9, 10, 15, 20])
  • Reverse Arrays

    Reversing an array is the operation of rearranging the array elements in the opposite order. There are various methods and approaches to reverse an array in Python including reverse() and reversed() methods.

    In Python, array is not one of the built-in data types. However, Python’s standard library has array module which helps us to create a homogenous collection of string, integer or float types.

    Reverse Array Operation Python

    Ways to Reverse an Array in Python

    To reverse an array, use the following approaches −

    • Using slicing operation
    • Using reverse() method
    • Using reversed() method
    • Using for loop

    Using slicing operation

    Slicing operation is the process of extracting a part of array within the specified indices. In Python, if we use the slice operation in the form [::-1] then, it will display a new array by reversing the original one.

    In this process, the interpreter starts from the end and stepping backwards by 1 until it reaches the beginning of the array. As a result, we get a reverse copy of original array.

    Example

    The below example demonstrates how to use the slicing operation to reverse an array in Python.

    Open Compiler

    import array as arr
    
    # creating array
    numericArray = arr.array('i',[88,99,77,55,66])print("Original array:", numericArray)
    revArray = numericArray[::-1]print("Reversed array:",revArray)

    When you run the code, it will produce the following output −

    Original array: array('i', [88, 99, 77, 55, 66])
    Reversed array: array('i', [66, 55, 77, 99, 88])
    

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

    Reverse an Array Using reverse() Method

    We can also reverse the sequence of numbers in an array using the reverse() method of list class. Here, list is a built-in type in Python.

    Since reverse() is a method of list class, we cannot directly use it to reverse an array created through the Python array module. We have to first transfer the contents of an array to a list with tolist() method of array class, then we call the reverse() method and at the end, when we convert the list back to an array, we get the array with reversed order.

    Example

    Here, we will see the use of reverse() method in reversing an array in Python.

    Open Compiler

    import array as arr
    
    # creating an array
    numericArray = arr.array('i',[10,5,15,4,6,20,9])print("Array before reversing:", numericArray)# converting the array into list
    newArray = numericArray.tolist()# reversing the list
    newArray.reverse()# creating a new array from reversed list
    revArray = arr.array('i', newArray)print("Array after reversing:",revArray)

    It will produce the following output −

    Array before reversing: array('i', [10, 5, 15, 4, 6, 20, 9])
    Array after reversing: array('i', [9, 20, 6, 4, 15, 5, 10])
    

    Reverse an Array Using reversed() Method

    The reversed() method is another way to reverse elements of an array. It accepts an array as a parameter value and returns an iterator object that dispalys array elements in reverse order.

    Example

    In this example, we are using the reversed() method to reverse an array in Python.

    Open Compiler

    import array as arr
    
    # creating an array
    numericArray = arr.array('i',[12,10,14,16,20,18])print("Array before reversing:", numericArray)# reversing the array
    newArray =list(reversed(numericArray))# creating a new array from reversed list
    revArray = arr.array('i', newArray)print("Array after reversing:",revArray)

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

    Array before reversing: array('i', [12, 10, 14, 16, 20, 18])
    Array after reversing: array('i', [18, 20, 16, 14, 10, 12])
    

    Using for Loop

    To reverse an array using a for loop, we first traverse the elements of the original array in reverse order and then append each element to a new array.

    Example

    The following example shows how to reverse an array in Python using for loop.

    Open Compiler

    import array as arr
    a = arr.array('i',[10,5,15,4,6,20,9])
    b = arr.array('i')for i inrange(len(a)-1,-1,-1):
       b.append(a[i])print(a)print(b)

    It will produce the following output −

    array('i', [10, 5, 15, 4, 6, 20, 9])
    array('i', [9, 20, 6, 4, 15, 5, 10])
  • Personal Finance Tracker

    Simple Personal Finance Tracker in Python

    First, make sure you have Python installed on your system. You can use any text editor or IDE to write your code.

    Code

    import json
    
    class FinanceTracker:
    
    def __init__(self, filename='finance_data.json'):
        self.filename = filename
        self.load_data()
    def load_data(self):
        try:
            with open(self.filename, 'r') as f:
                self.data = json.load(f)
        except FileNotFoundError:
            self.data = {'income': 0, 'expenses': &#91;], 'balance': 0}
    def save_data(self):
        with open(self.filename, 'w') as f:
            json.dump(self.data, f)
    def add_income(self, amount):
        self.data&#91;'income'] += amount
        self.update_balance()
        self.save_data()
    def add_expense(self, amount, description):
        self.data&#91;'expenses'].append({'amount': amount, 'description': description})
        self.update_balance()
        self.save_data()
    def update_balance(self):
        total_expenses = sum(expense&#91;'amount'] for expense in self.data&#91;'expenses'])
        self.data&#91;'balance'] = self.data&#91;'income'] - total_expenses
    def view_summary(self):
        print(f"Total Income: ${self.data&#91;'income']}")
        print("Expenses:")
        for expense in self.data&#91;'expenses']:
            print(f" - ${expense&#91;'amount']} for {expense&#91;'description']}")
        print(f"Balance: ${self.data&#91;'balance']}")
    def main():
    tracker = FinanceTracker()
    while True:
        print("\nPersonal Finance Tracker")
        print("1. Add Income")
        print("2. Add Expense")
        print("3. View Summary")
        print("4. Exit")
        
        choice = input("Select an option: ")
        if choice == '1':
            amount = float(input("Enter income amount: "))
            tracker.add_income(amount)
        elif choice == '2':
            amount = float(input("Enter expense amount: "))
            description = input("Enter expense description: ")
            tracker.add_expense(amount, description)
        elif choice == '3':
            tracker.view_summary()
        elif choice == '4':
            break
        else:
            print("Invalid choice. Please try again.")
    if __name__ == "__main__":
    main()

    How to Run the Code

    The data will be saved in a file named finance_data.json in the same directory, allowing you to track your finances over time.

    Copy the Code: Copy the code above into a new file called finance_tracker.py.

    Run the Script: Open a terminal (or command prompt), navigate to the directory where you saved the file, and run:

    python finance_tracker.py

    Interact with the Tracker:

    Choose options to add income, add expenses, or view your financial summary.