0% found this document useful (0 votes)
6 views

Python 504

Uploaded by

asmitadavrung
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Python 504

Uploaded by

asmitadavrung
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

1. Explain Loop Control Statements used in Python?

Loop control statements in Python are used to change the execution from its normal
sequence. They help in controlling the flow of loops like for and while loops. The primary
loop control statements in Python are:

• break: This statement terminates the loop containing it. Control of the program flows
to the statement immediately after the body of the loop.

python
Copy code
for i in range(10):
if i == 5:
break
print(i)
# Output: 0 1 2 3 4

• continue: This statement skips the rest of the code inside the loop for the current
iteration and jumps to the next iteration of the loop.

python
Copy code
for i in range(10):
if i % 2 == 0:
continue
print(i)
# Output: 1 3 5 7 9

• pass:This statement does nothing and is used as a placeholder. It is useful in places


where a statement is syntactically required but no action is needed.

python
Copy code
for i in range(10):
if i < 5:
pass
else:
print(i)
# Output: 5 6 7 8 9

2. Explain Functools module with an example.

The Python functools module is determined for higher-order functions, this


function accepts other functions as parameters and returns the given value.
These higher-order functions, often referred to as decorators.

This module specifies different utilities for working with higher-order


functions and callable objects. This function includes cumulative operations,
selecting partial functions, and including functions for caching.

Hence, functools is one of the most useful libraries in Python. This library
offers a collection of higher-order functions.
List of functools

The table below showcases values in this module, explains and elaborates on
the functions within the functools module.

S.No Function & Description

partial()
1 This function transforms multi-arguments functions into single-
argument and creates a partial object with predefined arguments.

2 partialmethod()
This function creates a class method with predefined values.

reduce()
3 This function gives accumulated output values with an optional
initializer.

wraps()
4 This function updates the wrapper function attributes to those of the
original function.

lru_cache()
5 This decorator caches recent function for efficiency, with a default
maxsize of 128.

6 cache()
This function caches unlimited values.

7 cached_property()
This function determines the class attribute in cached properties.

total_ordering()
8 This decorator automatically defines missing comparison methods if
__eq__(), __gt__ and __ge__ methods.

singledispatch()
9 This decorator allows functions to behave differently based on
argument types.

3. What is a class? Write the syntax of a class.

A class in Python is a blueprint for creating objects. Classes encapsulate data for the object
and methods to manipulate that data.

Syntax of a class:

python
Copy code
class ClassName:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2

def method1(self):
# method body
pass

def method2(self):
# method body
pass

Example:

python
Copy code
class Car:
def __init__(self, make, model):
self.make = make
self.model = model

def display_info(self):
print(f"Car make: {self.make}, Model: {self.model}")

# Create an object of the Car class


car1 = Car("Toyota", "Corolla")
car1.display_info() # Output: Car make: Toyota, Model: Corolla

4. What is Exception? How to handle exception in Python.

An exception is an event that disrupts the normal flow of the program's instructions. In
Python, exceptions are errors detected during execution. Examples include
ZeroDivisionError, TypeError, FileNotFoundError, etc.

Handling exceptions: Exceptions in Python can be handled using try, except, else, and
finally blocks.

python
Copy code
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code that runs if the exception occurs
print("Cannot divide by zero")
else:
# Code that runs if no exception occurs
print("Division successful")
finally:
# Code that runs no matter what
print("Execution completed")

In this example, if the division by zero occurs, the except block is executed. If no exception
occurs, the else block is executed. The finally block is executed in all cases.
5. Explain any three widgets available in tkinter in brief.

tkinter is a standard GUI (Graphical User Interface) library in Python. It provides various
widgets to create interactive applications.

• Button: A button widget is used to perform an action when clicked.

python
Copy code
import tkinter as tk

root = tk.Tk()
button = tk.Button(root, text="Click Me", command=root.destroy)
button.pack()
root.mainloop()

• Label: A label widget is used to display text or images.

python
Copy code
import tkinter as tk

root = tk.Tk()
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()
root.mainloop()

• Entry: An entry widget is used to accept single-line text input from the user.

python
Copy code
import tkinter as tk

root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
root.mainloop()

6. Write the difference between NLTK and SpaCy.

NLTK (Natural Language Toolkit) and SpaCy are both libraries used for Natural
Language Processing (NLP) in Python, but they have different strengths and use cases.

Feature NLTK SpaCy


Extensive but can be complex for User-friendly with a streamlined
Ease of Use
beginners API
Slower, suitable for research and Fast and optimized for production
Performance
teaching use
Features Wide range of tools and algorithms Focused on practical applications
Models Requires manual installation of models Pre-trained models included
Feature NLTK SpaCy
Customization High degree of customization Less customizable but efficient

Example of tokenization with NLTK:

python
Copy code
import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize

text = "Hello, world!"


tokens = word_tokenize(text)
print(tokens) # Output: ['Hello', ',', 'world', '!']

Example of tokenization with SpaCy:

python
Copy code
import spacy

nlp = spacy.load("en_core_web_sm")
doc = nlp("Hello, world!")
tokens = [token.text for token in doc]
print(tokens) # Output: ['Hello', ',', 'world', '!']

In summary, NLTK is great for educational purposes and offers a wide array of tools for
different NLP tasks. SpaCy is designed for practical, real-world applications and is optimized
for performance.

You might also like