Interview

10 Scripting Language Interview Questions and Answers

Prepare for your next interview with our comprehensive guide on scripting languages, featuring common questions and expert insights.

Scripting languages play a crucial role in automating tasks, managing system operations, and enhancing productivity across various domains. These languages, known for their ease of use and flexibility, enable developers to write concise code that can perform complex operations. Popular scripting languages like Python, JavaScript, and Bash are integral to modern software development and IT operations, making proficiency in them a valuable asset.

This article offers a curated selection of interview questions designed to test your knowledge and problem-solving abilities with scripting languages. By working through these questions, you will gain a deeper understanding of key concepts and be better prepared to demonstrate your expertise in a professional setting.

Scripting Language Interview Questions and Answers

1. Write a script that reads a text file and counts the number of lines, words, and characters.

To read a text file and count lines, words, and characters, use this Python script:

def count_file_stats(filename):
    with open(filename, 'r') as file:
        lines = file.readlines()
        num_lines = len(lines)
        num_words = sum(len(line.split()) for line in lines)
        num_chars = sum(len(line) for line in lines)
    
    return num_lines, num_words, num_chars

filename = 'example.txt'
lines, words, chars = count_file_stats(filename)
print(f"Lines: {lines}, Words: {words}, Characters: {chars}")

2. Write a script that takes a list of numbers and returns the largest and smallest numbers.

To find the largest and smallest numbers in a list, use Python’s min() and max() functions:

def find_min_max(numbers):
    if not numbers:
        return None, None
    smallest = min(numbers)
    largest = max(numbers)
    return smallest, largest

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
smallest, largest = find_min_max(numbers)
print(f"Smallest: {smallest}, Largest: {largest}")

3. Write a script that connects to a database, retrieves data from a table, and prints it out.

To connect to a database and retrieve data, use Python’s sqlite3 library:

import sqlite3

def fetch_data():
    conn = sqlite3.connect('example.db')
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM my_table")
    rows = cursor.fetchall()
    for row in rows:
        print(row)
    conn.close()

fetch_data()

4. Write a script that uses recursion to solve a problem of your choice. Explain why recursion is appropriate for this problem.

Recursion is useful for problems that can be broken down into smaller, repetitive tasks. For example, calculating the Fibonacci sequence:

def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))  # Output: 55

5. Write a script that implements a simple web scraper.

A web scraper extracts data from websites. Use requests and BeautifulSoup in Python:

import requests
from bs4 import BeautifulSoup

def fetch_webpage_title(url):
    response = requests.get(url)
    if response.status_code == 200:
        soup = BeautifulSoup(response.content, 'html.parser')
        return soup.title.string
    else:
        return None

url = 'https://www.example.com'
title = fetch_webpage_title(url)
print(f'Title of the webpage: {title}')

6. Write a script that uses multithreading or multiprocessing to perform a task more efficiently.

Multithreading and multiprocessing improve efficiency by parallelizing tasks. Here’s an example using multithreading:

import threading

def print_numbers():
    for i in range(1, 6):
        print(i)

def print_letters():
    for letter in 'abcde':
        print(letter)

thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)

thread1.start()
thread2.start()

thread1.join()
thread2.join()

7. Write a script that reads from and writes to a file, demonstrating basic file manipulation.

For basic file manipulation, read from one file and write to another:

with open('input.txt', 'r') as infile:
    content = infile.read()

with open('output.txt', 'w') as outfile:
    outfile.write('This is the new content.\n')
    outfile.write(content)

8. Write a script that parses JSON data and extracts specific information.

To parse JSON data and extract information, use Python’s json module:

import json

json_data = '''
{
    "name": "John Doe",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA"
    },
    "phone_numbers": [
        {"type": "home", "number": "555-555-5555"},
        {"type": "work", "number": "555-555-5556"}
    ]
}
'''

data = json.loads(json_data)

name = data['name']
city = data['address']['city']
home_phone = next(item['number'] for item in data['phone_numbers'] if item['type'] == 'home')

print(f"Name: {name}")
print(f"City: {city}")
print(f"Home Phone: {home_phone}")

9. Write a script that interacts with a RESTful API to fetch and display data.

To interact with a RESTful API, use the requests library:

import requests

def fetch_data(api_url):
    response = requests.get(api_url)
    if response.status_code == 200:
        data = response.json()
        return data
    else:
        return None

api_url = 'https://jsonplaceholder.typicode.com/posts'
data = fetch_data(api_url)

if data:
    for item in data:
        print(f"Title: {item['title']}\nBody: {item['body']}\n")
else:
    print("Failed to fetch data.")

10. Write a script that automates a repetitive task, such as renaming files in a directory based on a pattern.

Automate repetitive tasks like renaming files in a directory:

import os

def rename_files(directory, prefix):
    for filename in os.listdir(directory):
        if not filename.startswith(prefix):
            new_name = prefix + filename
            os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))

rename_files('/path/to/directory', 'prefix_')
Previous

10 RFID Interview Questions and Answers

Back to Interview
Next

10 Anomaly Detection Interview Questions and Answers