Binary Search
Binary Search
Binary Search
Slicing:
Tuples support slicing to extract sub-tuples:
sub_tuple = my_tuple[1:4]
print(sub_tuple) # Output: (2, 3, 'a')
Concatenation:
Tuples can be concatenated using the + operator:
combined_tuple = my_tuple + another_tuple
print(combined_tuple) # Output: (1, 2, 3, 'a', 'b', 4, 5, 6)
Repetition:
Tuples can be repeated using the * operator:
repeated_tuple = my_tuple * 2
print(repeated_tuple) # Output: (1, 2, 3, 'a', 'b', 1, 2, 3, 'a', 'b')
Length:
The len() function returns the length of a tuple:
print(len(my_tuple)) # Output: 5
----------------------------------------------------------------------------------------------------------------
list:
Lists in Python are mutable sequences, allowing various operations to be performed
on them. Here are some common operations on lists:
1. Creation:
Lists can be created using square brackets []:
my_list = [1, 2, 3, 'a', 'b']
2. Accessing Elements:
Elements of a list can be accessed using indexing:
print(my_list[0]) # Output: 1 print(my_list[3]) # Output: 'a'
3. Slicing:
Lists support slicing to extract sub-lists:
sub_list = my_list[1:4] print(sub_list) # Output: [2, 3, 'a']
4. Modification:
Lists can be modified by changing elements, adding, or removing elements:
my_list[0] = 'updated' my_list.append('c') my_list.extend([4, 5, 6]) my_list.insert(2,
'new_element')
5. Deletion:
Elements can be removed by using the del statement or the remove() method:
del my_list[1] my_list.remove('a')
6. Concatenation:
Lists can be concatenated using the + operator:
another_list = [7, 8, 9] combined_list = my_list + another_list print(combined_list) #
Output: ['updated', 3, 'new_element', 'b', 'c', 4, 5, 6, 7, 8, 9]
7. Repetition:
Lists can be repeated using the * operator:
repeated_list = my_list * 2 print(repeated_list) # Output: ['updated', 3,
'new_element', 'b', 'c', 4, 5, 6, 'updated', 3, 'new_element', 'b', 'c', 4, 5, 6]
8. Length:
The len() function returns the length of a list:
print(len(my_list)) # Output: 9
-------------------------------------------------------------------------------------------------------------
exception handling:
Handling exceptions in Python involves using try, except, else, and finally blocks.
def divide_numbers(x, y):
try:
result = x / y
print(f"The result of {x} divided by {y} is: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input. Please provide valid numeric values.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("The division operation completed successfully.")
finally:
print("This block will always be executed, regardless of whether an exception
occurred.")
# Example usage:
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
divide_numbers(numerator, denominator)
except ValueError:
print("Invalid input. Please enter numeric values for the numerator and
denominator.")
In this program, we define a function divide_numbers that attempts to perform
division and handle specific exceptions.
----------------------------------------------------------------------------------------------------------------
Multilevel inheritance:
Multi-level inheritance in Python involves creating a chain of classes where each class
extends the previous one.
class Animal:
def __init__(self, species):
self.species = species
def speak(self):
print(f"I am an {self.species}")
class Mammal(Animal):
def __init__(self, species, sound):
super().__init__(species)
self.sound = sound
def make_sound(self):
print(f"{self.species} says {self.sound}")
class Dog(Mammal):
def __init__(self, breed, sound):
super().__init__('Dog', sound)
self.breed = breed
def display_info(self):
print(f"I am a {self.breed} dog")
# Example usage:
dog_instance = Dog('Labrador', 'Woof')
dog_instance.display_info() # Output: I am a Labrador dog
dog_instance.make_sound() # Output: Dog says Woof
dog_instance.speak() # Output: I am an Dog
OPENING MODES:
Python requires file handling for various reasons, such as reading data from files,
writing data to files, and manipulating file content. File handling is essential for tasks
like data storage, data analysis, and communication with external resources. Python
provides built-in functions and methods to open, read, write, and manipulate files
easily.
Opening Files in Python with Modes:
The open() function is used to open files in Python. It takes two arguments: the file
name and the mode in which the file should be opened. The mode specifies the
purpose of opening the file, such as reading, writing, or appending.
1. Read Mode ('r'):
• Open the file for reading.
• If the file doesn't exist, it raises a FileNotFoundError.
• Example: open('filename.txt', 'r')
2. Write Mode ('w'):
• Open the file for writing.
• If the file already exists, it truncates its content.
• If the file doesn't exist, it creates a new file.
• Example: open('filename.txt', 'w')
3. Append Mode ('a'):
• Open the file for appending (writing at the end of the file).
• If the file doesn't exist, it creates a new file.
• Example: open('filename.txt', 'a')
4. Binary Read Mode ('rb'):
• Open the file in binary mode for reading.
• Example: open('filename.bin', 'rb')
5. Binary Write Mode ('wb'):
• Open the file in binary mode for writing.
• Example: open('filename.bin', 'wb')
6. Text Read Mode ('rt' or 'r'):
• Open the file in text mode for reading. (Default)
• Example: open('filename.txt', 'rt') or open('filename.txt', 'r')
7. Text Write Mode ('wt' or 'w'):
• Open the file in text mode for writing. (Default)
• Example: open('filename.txt', 'wt') or open('filename.txt', 'w')
8. Text Append Mode ('at' or 'a'):
• Open the file in text mode for appending. (Default)
• Example: open('filename.txt', 'at') or open('filename.txt', 'a')
OS.PATH.JOIN() is a function in Python's os.path module that is used for
joining one or more path components intelligently. It takes care of handling the
differences in path separators ('/' or '') between operating systems, making it
especially useful for creating platform-independent file paths during directory
traversal.
Significance of os.path.join() in Directory Traversal:
1.Platform Independence:
Different operating systems use different path separators (e.g., '/' on Unix-like
systems and '\' on Windows).
os.path.join() abstracts these differences and generates a path using the correct
separator based on the underlying operating system.
2. Accessing Values:
Use square brackets [] and the key to access the value associated with that key.
print(my_dict['name']) # Output: John
3. Adding/Modifying Entries:
To add a new key-value pair or modify an existing one:
my_dict['gender'] = 'Male' # Adding a new entry
my_dict['age'] = 31 # Modifying an existing entry
4. Removing Entries:
To remove a key-value pair, you can use the del statement or the pop() method.
del my_dict['city'] # Removing a specific entry
value = my_dict.pop('age') # Removing and getting the value
5. Dictionary Methods:
Various built-in methods are available for dictionaries:
keys(): Returns a list of all keys.
values(): Returns a list of all values.
items(): Returns a list of key-value pairs as tuples.
keys_list = my_dict.keys()
values_list = my_dict.values()
items_list = my_dict.items()
6. Checking Key Existence:
You can check if a key exists in a dictionary using the in keyword.
if 'name' in my_dict:
print("Key 'name' exists.")
7. Length:
The len() function returns the number of key-value pairs in a dictionary.
length = len(my_dict)
1. Threading:
Using the threading module to create separate threads for handling individual
connections. Each thread can manage its own connection, allowing concurrent
execution.
import threading
import socket
def handle_client(connection, address):
pass
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8080))
server_socket.listen(5)
while True:
client_socket, client_address = server_socket.accept()
client_thread = threading.Thread(target=handle_client, args=(client_socket,
client_address))
client_thread.start()
. Forking
#A Forking Server
from socketserver import TCPServer, ForkingMixIn, StreamRequestHandler
class Server(ForkingMixIn, TCPServer): pass
class Handler(StreamRequestHandler):
def handle(self):
addr = self.request.getpeername()
print('Got connection from', addr)
self.wfile.write('Thank you for connecting')
server = Server(('', 1234), Handler)
server.serve_forever()
Define URLib:
urllib is a Python module that provides a set of modules for working with URLs. It
includes modules such as urllib.request for opening and reading URLs, urllib.parse for
parsing URLs, urllib.error for exception classes raised by urllib, and urllib.robotparser
for parsing robots.txt files. urllib is part of the Python standard library and is
commonly used for web-related tasks
• Common Gateway Interface (also known as CGI) is a specification(set of
rules) that helps to establish a dynamic interaction between a web
application and the browser (or the client application).
• The CGI programs make possible communication between client and web
servers.
• Whenever the client browser sends a request to the webserver the CGI
programs send the output back to the web server based on the input
provided by the client-server.
▪ CGI is the standard for programs to interface with HTTP servers.
▪ CGI programming is written dynamically generating webpages that respond
to user input or webpages that interact with software on the sector.
Here's an example of a CGI script written in Python. This script will handle a simple
HTML form, receive user input, and display a personalized greeting on a web page.
In Tkinter, a Listbox is a widget that displays a list of items from which the user can
make selections. It provides a user-friendly way to present a list of options, allowing
users to choose one or more items. List boxes are commonly used in GUI
applications to offer selection choices in a clear and organized manner.
Purpose of List Boxes:
Selection: List boxes allow users to select one or more items from a predefined list.
Display: They provide a visible list of options, making it easy for users to see
available choices.
Organization: List boxes help organize and present choices in a structured way,
improving the user experience.
Here's a simple example of creating a Tkinter window with a Listbox, adding items
to it, and retrieving the selected item:
import tkinter as tk
def on_select(event):
selected_index = listbox.curselection()
if selected_index:
selected_item = listbox.get(selected_index[0])
result_label.config(text=f"Selected Item: {selected_item}")
window = tk.Tk()
window.title("List Box Example")
listbox = tk.Listbox(window, selectmode=tk.SINGLE)
listbox.pack(pady=10)
items = ["Item 1", "Item 2", "Item 3", "Item 4"]
for item in items:
listbox.insert(tk.END, item)
listbox.bind("<<ListboxSelect>>", on_select)
result_label = tk.Label(window, text="Selected Item: None")
result_label.pack(pady=10)
window.mainloop()
squares_of_evens = [x ** 2 for x in range(1, 21) if x % 2 == 0]
print(squares_of_evens)
• Threading Module
• Asyncio Module
2] Define URLError:
• URLError is an exception class in Python's urllib.error module.
• It is raised when a URL-related error occurs during the execution of a
program using urllib. This can include errors such as a failed connection to
the server, inability to resolve the host, or other network-related issues.
• Handling URLError allows a program to respond appropriately to problems
encountered when working with URLs.
• Update Operation:
• Modifies existing records or rows in a database table.
records.
• Used to update existing data in a table.