Friday, 20 September 2024

Python

  Python paper answer only 1 or 2 marks


(a) Attempt the following:                  

 1. Who is the developer of Python?

Guido van Rossum

2. Which special character is used for a new line?

The special character for a new line is \n.

3. Python commands are evaluated/executed in ________.

Python commands are executed in the interpreter.

4. The ______ symbol is used to set a single line comment in Python.

The # symbol is used to set a single line comment.


(b) Attempt the following: (any one)

1. Explain tuple with an example.

A tuple is an immutable sequence of items in Python. Example: my_tuple = (1, 2, 3). Once created, elements in a tuple cannot be changed.


2. What is a global variable?

A global variable is one that is defined outside of any function and is accessible in any scope within the program.


(a) Attempt the following:

1. The Python raise statement forces a specified exception to occur.

2. ELSE keyword is used in exception handling in Python.

True. The else block is used to define a code segment that runs if no exception occurs in the try block.

3. The Exception class catches all exceptions in Python.

4. Partition and exchange sort is QuickSort.


(b) Attempt the following: (any one)


1. Explain assertions in Python.

An assertion is a debugging aid that tests a condition. If the condition evaluates to True, nothing happens, but if it evaluates to False, the program raises an AssertionError.

 Example:

assert x > 0, "x must be positive"

2. Explain class in Python.

A class is a user-defined blueprint or prototype from which objects are created. Classes encapsulate data for the object and methods to manipulate that data. 

Example:

class MyClass:

    def _init_(self, name):

        self.name = name

obj = MyClass("John")

print(obj.name)


(a) Attempt the following:

1. Knapsack problem is also known as ________ problem.

The Knapsack problem is also known as the Optimization problem.

2. ________ method displays the graphical window on the computer screen.

The show() method displays the graphical window on the computer screen.

3. When storing PyLab Figure, Default extension is ________.

The default extension when storing a PyLab figure is .png.

4. Which function is used to save plot graph to file?

The savefig() function is used to save a plot graph to a file.


(b) Attempt the following: (any one)

1. Explain show() function in Python.

The show() function in Python is used to display figures created using libraries like Matplotlib. It renders the plot in a window or inline in notebooks. Without calling show(), the plot may not be visible.

 Example:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [4, 5, 6])

plt.show()  # Displays the plot


2. Explain legend() function in Python.

The legend() function in Python is used to place a legend on the plot, which describes the elements of the plot. It helps differentiate between multiple plots on the same graph. 

Example:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3], label='Line 1')

plt.plot([3, 2, 1], label='Line 2')

plt.legend()  # Adds a legend

plt.show()


(a) Attempt the following:

1. URL stands for:

Uniform Resource Locator

2. UDP stands for:

User Datagram Protocol

3. TCL stands for:

Tool Command Language

4. TCP/IP stands for:

Transmission Control Protocol/Internet Protocol


(b) Attempt the following: (any one)

1. Write a code to download an image from the internet:

You can use Python’s requests library to download an image from the internet. Here’s an example:

import requests

url = 'https://example.com/image.jpg' 

 # Replace with the image URL

response = requests.get(url)

with open('image.jpg', 'wb') as file:

    file.write(response.content)

print('Image downloaded successfully')

This code downloads the image from the given URL and saves it as image.jpg.


2. Explain Button with an example:

In Python, buttons can be created using the tkinter library for graphical user interfaces. Here's a simple example:

import tkinter as tk

def on_button_click():

    print("Button clicked!")

root = tk.Tk()

root.title("Button Example")

button = tk.Button(root, text="Click Me", command=on_button_click)

button.pack(pady=20)

root.mainloop()

Explanation:

This script creates a window with a button labeled "Click Me".

When the button is clicked, it triggers the on_button_click function, which prints "Button clicked!" to the console.



(a) Attempt the following:

1. SQL stands for:

Structured Query Language

2. Which package is used to connect MySQL database in Python code?

The package used to connect MySQL databases in Python is mysql-connector-python or PyMySQL.

3. List out connection() function parameters:

The parameters of the connect() function commonly used to connect to a MySQL database are:

host: The hostname or IP address of the MySQL server (e.g., 'localhost').

user: The username for the database (e.g., 'root').

password: The password for the database user.

database: The name of the database to connect to.

port: The port number on which the MySQL server is running (default is 3306).

4. Which method of the cursor class is used to fetch only one row from the table?

The method used to fetch only one row is fetchone().


(b) Attempt the following: (any one)

1. Write a Python code to insert a record into the table:

import mysql.connector

# Establish the connection

mydb = mysql.connector.connect

(host="localhost",

user="yourusername",

 password="yourpassword",

    database="yourdatabase")


# Create a cursor object

mycursor = mydb.cursor()

# SQL query to insert a record

sql = "INSERT INTO students (name, age) VALUES (%s, %s)"

val = ("John Doe", 21)

# Execute the query

mycursor.execute(sql, val)

# Commit the transaction

mydb.commit()

print(mycursor.rowcount, "record inserted.")

This code connects to a MySQL database, inserts a record into the students table, and commits the transaction.


2. Write a Python code to delete a record from the table:

import mysql.connector

# Establish the connection

mydb = mysql.connector.connect

( host="localhost",

    user="yourusername",

    password="yourpassword",

    database="yourdatabase")

# Create a cursor object

mycursor = mydb.cursor()

# SQL query to delete a record

sql = "DELETE FROM students WHERE name = %s"

val = ("John Doe", )

# Execute the query

mycursor.execute(sql, val)

# Commit the transaction

mydb.commit()

print(mycursor.rowcount, "record deleted.")

This code connects to a MySQL database, deletes a record where the name is 'John Doe', and commits the transaction.



(a) Give appropriate answers for the following questions:

1. Who is the developer of Python?

Guido van Rossum is the developer of Python. He created the first version of Python in 1991.

2. What is the output of 30//20 and 30/20?

30//20 (integer division or floor division): 1

30/20 (floating-point division): 1.5

3. What is the output of type(3)?

The output of type(3) will be:

<class 'int'>

This shows that the value 3 is of type int (integer).

4. How to write x raised to the power y in Python?

You can write x raised to the power y using the ** operator.

Example:

result = x ** y


(b) Answer in brief (any one):

1. Explain tuple with an example.

A tuple is an immutable sequence in Python. Once a tuple is created, its elements cannot be modified, added, or removed. Tuples are used to group multiple items into a single compound object.

Example:

my_tuple = (1, 2, 3, "apple")

print(my_tuple)

This creates a tuple with integers and a string, and its contents can be accessed using indexing.


2. What is function specification? Explain with an example.

A function specification in Python refers to defining what a function does, including its parameters and the expected return value. It provides a clear understanding of how to use the function.

Example:

def add_numbers(a, b):

    """

    This function takes two numbers as input and returns their sum.

    :param a: First number

    :param b: Second number

    :return: Sum of a and b

    """

    return a + b


In this example, the function add_numbers() has a specification in the form of a docstring, which explains the parameters (a, b) and the return value (sum of a and b).



(a) Give appropriate answers for the following questions:

1. The Python raise statement forces a specified exception to occur.


2.  yield keyword tells Python that a function is a generator.



3. What is the time complexity of merge sort?

The time complexity of merge sort is O(n log n), where n is the number of elements in the array. This complexity occurs in both the best-case and worst-case scenarios.


4. What is the complexity of binary search when the value of high - low is equal to len(L) - 1?

The complexity of binary search remains O(log n), where n is the number of elements in the list. This complexity holds true regardless of the specific range of high - low, as long as the search space is halved in each step.


(b) Answer in brief (any one):

1. Explain exception handling in brief.

Exception handling in Python allows you to handle runtime errors or exceptions, ensuring that the program doesn't crash unexpectedly. The primary keywords used for exception handling are try, except, else, and finally.

try: The code that might raise an exception is placed inside a try block.

except: If an exception occurs, it is caught in the except block.

else: Executes if no exception occurs in the try block.

finally: Executes code regardless of whether an exception occurred or not.

Example:

try:

    x = 1 / 0

except ZeroDivisionError:

    print("Division by zero is not allowed.")

else:

    print("No exceptions occurred.")

finally:

    print("This will always run.")


2. What is an assertion?

An assertion is a debugging tool that tests a condition. If the condition is True, nothing happens, but if it’s False, an AssertionError is raised. It is used to check for expected conditions in the code and is mostly used during development.

Example:

x = 10

assert x > 0,


(a) Give appropriate answers for the following questions:

1. Which function is used to save a plot graph to a file?

The savefig() function is used to save a plot graph to a file in Python using libraries like Matplotlib.

Example:

plt.savefig('plot.png')

2. What is the full form of PNG?

The full form of PNG is Portable Network Graphics.

3. Dynamic programming was invented by ______ in ______.

Dynamic programming was invented by Richard Bellman in 1953.

4. In a rooted binary tree, each non-root node has a ______ parent.

In a rooted binary tree, each non-root node has one parent.


(b) Answer in brief: (any one)

1. Explain pylab.show() with an example.

The pylab.show() function is used to display all open figures or plots in a graphical window. It ensures that plots are rendered and visible to the user.

Example:

import matplotlib.pyplot as plt

# Create a simple plot

plt.plot([1, 2, 3, 4], [10, 20, 25, 30])

# Show the plot

plt.show()

This code generates a plot and uses show() to render the plot in a window.


(a) Give appropriate answers for the following questions:

1. Give full form of CSV:

Comma-Separated Values

2. Give full form of JSON:

JavaScript Object Notation

3. Write down the regular expression statement to find all five-character-long words from the string strl and print them.

Regular expression for finding all five-character-long words:

import re

# Example string

strl = "This is a sample string with words having five chars like apple"

# Regular expression to find five-character-long words

result = re.findall(r'\b\w{5}\b', strl)

# Print the result

print(result)

In this code, \b\w{5}\b is the regular expression that matches words with exactly five characters.

4. What is the output of the following code?

import re

DOB = "08-10-1980 # This is Date of Birth"

print(re.sub(r'\D', "", re.sub(r'#.*$', "", DOB)))

Explanation:

re.sub(r'#.*$', "", DOB) removes everything after the # symbol.

re.sub(r'\D', "", DOB) removes all non-digit characters from the remaining string.

So the output will be:

08101980


(b) Answer in brief:


(1) What is a regular expression? Explain with a simple example.


A regular expression (regex) is a sequence of characters that define a search pattern, typically used for string matching or substitution. Regex can be used to identify patterns in text such as email addresses, phone numbers, or any other specific sequence of characters.


Example:

To find all occurrences of the word "cat" in a text, the regex pattern would simply be:


import re

text = "I have a cat, and my friend has a cat too."

matches = re.findall(r"cat", text)

print(matches)

This would return ['cat', 'cat'] as it finds both instances of the word "cat."


(2) List out all flags modifiers with a single-line meaning.

1. re.IGNORECASE (or re.I): Makes the pattern matching case-insensitive.

2. re.MULTILINE (or re.M): Allows ^ and $ to match the start and end of each line, not just the whole string.

3. re.DOTALL (or re.S)




(a) Give appropriate answers for the following questions:

1. What is the output of print(dataset.shape)?

The shape attribute of a dataset (usually a DataFrame in libraries like Pandas) returns a tuple representing the dimensions of the dataset. It provides the number of rows and columns in the format (rows, columns).

Example:

import pandas as pd

data = {'col1': [1, 2], 'col2': [3, 4]}

dataset = pd.DataFrame(data)

print(dataset.shape)  # Output: (2, 2)

This means the dataset has 2 rows and 2 columns.


2. What is the output of print(dataset.head(5))?

The head() function returns the first n rows of the dataset. In this case, it returns the first 5 rows. If the dataset contains fewer than 5 rows, it returns all rows.

Example:

print(dataset.head(5))

(3) MSE stands for Mean Squared Error. 


(4) The dependent variable is also called the response variable or outcome variable


(b) Answer in brief:


(1) List out basic libraries required for data analytics in Python:


1. NumPy: 

2. Pandas: 

3. Matplotlib: 

4. Seaborn: 

5. SciPy:

6. Scikit-learn:

7. Statsmodels: 

(2) Discuss statistical summary function and class distribution in Python:


In Python, statistical summary functions provide key insights into data by summarizing important statistics such as mean, median, variance, and standard deviation. These summaries help in understanding the central tendency, spread, and overall structure of data.


Statistical summary: The describe() function in Pandas is commonly used for this purpose. It generates descriptive statistics for numeric data like count, mean, standard deviation, min, max, and percentiles.


Example:


import pandas as pd

df = pd.DataFrame({'age': [25, 30, 35, 40, 45]})

print(df.describe())


Class distribution: Refers to the distribution of different categories or classes in the dataset, which is crucial in classification problems. The value_counts() function in Pandas is often used to check the distribution of each class in a categorical variable.


Example:


df = pd.DataFrame({'class': ['A', 'B', 'A', 'B', 'C']})

print(df['class'].value_counts())


(1 A) Fill in the blanks:


(1) Python commands are evaluated/executed in the interpreter.


(2) The >>> symbol is a shell prompt in Python.


(3) The # symbol is used to set comments in Python.


(4) IDLE stands for Integrated Development and Learning Environment.


( B) Answer in brief (Any One):


(1) Explain TUPLE data type in Python:


A tuple in Python is an immutable, ordered collection of items. Once created, the items in a tuple cannot be changed, added, or removed. Tuples are written with parentheses (), and elements are separated by commas. They can hold elements of different data types, including numbers, strings, and other collections (such as lists).


Example:


my_tuple = (1, 'apple', 3.5)

print(my_tuple)  # Output: (1, 'apple', 3.5)


Tuples are useful when you want to ensure that the data remains unchanged throughout the program.


(2) Explain LIST data type in Python:


A list in Python is a mutable, ordered collection of items. This means that you can modify a list after it is created—adding, removing, or changing elements. Lists are written with square brackets [], and the elements are separated by commas. Like tuples, lists can hold items of different data types.


Example:


my_list = [1, 'banana', 4.5]

print(my_list)  # Output: [1, 'banana', 4.5]

my_list.append('orange')  # Adding an element

print(my_list)  # Output: [1, 'banana', 4.5, 'orange']


Lists are versatile and are widely used in Python for storing collections of related data.


(2 A) Fill in the blanks:


(1) BaseException catches all exceptions in Python.


(2) The raise statement forces an exception to occur in Python.


(3) ELSE keyword is used in Exception Handling in Python – TRUE.


(4) ADT stands for Abstract Data Type.


(2 B) Answer in brief (Any One):

(1) Explain Assertion in Python:


An assertion in Python is a debugging tool used to test if a certain condition holds true during the execution of a program. It is typically used to catch and report errors early in the development process. If the condition provided in the assert statement evaluates to True, the program continues executing. If the condition is False, it raises an AssertionError with an optional error message.


Example:


x = 5

assert x > 0, "x should be positive"


If the condition x > 0 fails, Python will throw an AssertionError with the message "x should be positive". Assertions are generally used for internal checks during development and can be disabled in production by running Python with the -O (optimize) flag.


(2) Explain Handling Exceptions in Python:


In Python, exception handling is a mechanism to handle runtime errors in a controlled way. It uses the try, except, else, and finally blocks. The code that might raise an error is placed inside the try block. If an exception occurs, the except block is executed, allowing you to handle the error. If no exception occurs, the else block (optional) is executed. The finally block (also optional) is executed regardless of whether an exception occurs, ensuring that resources like file handles or network connections are properly closed.


Example:


try:

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

    result = 10 / number

except ZeroDivisionError:

    print("Cannot divide by zero!")

except ValueError:

    print("Invalid input, please enter a number.")

else:

    print("Result:", result)

finally:

    print("This will always run, even if there is an error.")


In this example, different types of exceptions (like dividing by zero or entering an invalid input) are handled gracefully without crashing the program.

(3 A) Fill in the blanks:


(1) PyLab provides many of the facilities of Matplotlib.


(2) The show() method displays the graphical window on the computer screen.


(3) When PyLab stores a figure, the default extension is .png.


(4) SciPy is a Python module that provides tools for scientific computing.


1. What is Memorization?

Memorization is the process of storing the results of expensive function calls and reusing the stored results when the same inputs occur again. This technique is commonly used in optimization, where repetitive computations can be avoided by saving and reusing the results of previous computations. In programming, it is typically implemented using a cache or lookup table to store the results of function calls.


2. Explain pylab.title, pylab.xlabel, and pylab.ylabel:


=> pylab.title: This function is used to set a title for the plot. It places the specified text at the top of the plot.

pylab.title('My Plot Title')

=> pylab.xlabel: This function is used to set the label for the x-axis of the plot. It describes the data represented on the horizontal axis.

pylab.xlabel('X Axis Label')

=> pylab.ylabel: This function is used to set the label for the y-axis of the plot. It describes the data represented on the vertical axis.

pylab.ylabel('Y Axis Label')



(A) Fill in the blanks:


1. In Python, regular expressions are supported by the re module.

2. A regular expression is a sequence of characters that forms a search pattern.

3. JSON stands for JavaScript Object Notation.

4. If there is no match, None will be returned, instead of the Match Object.

(B) Answer in Brief: (Any One)


1. Explain json.loads(object): 

The function json.loads() is used to parse a JSON string and convert it into a corresponding Python object (like a dictionary, list, etc.). It is the opposite of serialization and is helpful when dealing with JSON data from external sources like web APIs.


import json

json_data = '{"name": "Puja", "age": 19}'

python_obj = json.loads(json_data)

print(python_obj)

# Output: {'name': 'Puja', 'age': 19}



2. Explain json.dumps(object): 

The function json.dumps() converts a Python object into a JSON string. It is useful when serializing data for storage or transmission (such as sending JSON over a network).


import json

python_obj = {"name": "Puja", "age": 19}

json_data = json.dumps(python_obj)

print(json_data)

# Output: '{"name": "Puja", "age": 19}'










No comments:

Post a Comment

Kotlin paper solutions for unit -1

Paper April-2023 --- 1(a) Fill in the blanks: (1 mark each) 1. Who developed Kotlin?  JetBrains 2. Which extension is responsible to save Ko...