Python 504
Python 504
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
python
Copy code
for i in range(10):
if i < 5:
pass
else:
print(i)
# Output: 5 6 7 8 9
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.
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.
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}")
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.
python
Copy code
import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text="Click Me", command=root.destroy)
button.pack()
root.mainloop()
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()
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.
python
Copy code
import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize
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.