Python Assignment 1
Python Assignment 1
Ans:
Python is a high-level, interpreted programming language known for its simplicity and
readability. It was created by Guido van Rossum and first released in 1991. Python
supports multiple programming paradigms, including procedural, object-oriented,
and functional programming. It has a large standard library and a vibrant community,
making it a popular choice for a wide range of applications, from web development
and data analysis to artificial intelligence and scientific computing.
Python is an interpreted language, which means that the source code is executed line by
line by an interpreter rather than being compiled into machine code before
execution. Here’s a more detailed breakdown of how Python code is interpreted:
1. Writing the Code: You write Python code in a .py file using a text editor or an
Integrated Development Environment (IDE).
2. The Python Interpreter: When you run a Python script, the Python interpreter (e.g.,
CPython, which is the default and most widely used implementation) reads the
source code.
3. Compilation to Bytecode: The interpreter first compiles the source code into an
intermediate form called bytecode. This bytecode is a low-level,
platform-independent representation of your source code. The bytecode is stored in
.pyc files (compiled Python files) in a __pycache__ directory, which allows for faster
execution on subsequent runs.
4. Execution by the Python Virtual Machine (PVM): The Python Virtual Machine (PVM)
is the runtime engine of Python. It reads the bytecode and executes it line by line.
The PVM is part of the Python interpreter and is responsible for the actual execution
of the code.
5. Dynamic Typing and Interpretation: Python is dynamically typed, meaning that the
type of a variable is interpreted at runtime. The interpreter checks the types and
performs operations accordingly as it executes the bytecode.
The if statement checks a condition. If the condition is True, the block of code under
the if statement is executed. If the condition is False, the block is skipped.
Syntax:
if condition:
# Code to execute if the condition is True
2. if-else Statement
The if-else statement allows you to execute one block of code if the condition is True
and another block if the condition is False.
Syntax:
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False
3. if-elif-else Statement
The if-elif-else statement is used when you have multiple conditions to check. The
elif (short for "else if") allows you to check additional conditions if the previous ones
are False. The else block is executed if none of the conditions are True.
Syntax:
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if all conditions are False
4. Nested if Statements
You can nest if statements inside other if statements to check for more complex
conditions.
Syntax:
if condition1:
if condition2:
# Code to execute if both condition1 and condition2 are True
Python also supports a shorthand way to write simple if-else statements using the
ternary operator.
Syntax:
value_if_true if condition else value_if_false
Example:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Example:
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
Example:
file = open("example.txt", "a")
file.write("\nThis is a new line.")
file.close()
Example:
try:
file = open("example.txt", "x")
file.write("This is a new file.")
file.close()
except FileExistsError:
print("File already exists.")
Example:
# Reading a binary file
file = open("image.png", "rb")
data = file.read()
file.close()
Example:
Examples:
● 'r+': Opens a file for both reading and writing. The file must exist.
file = open("example.txt", "r+")
content = file.read()
file.write("New content")
file.close()
'w+': Opens a file for both reading and writing. If the file exists, it truncates the file. If
the file does not exist, it creates a new file.
file = open("example.txt", "w+")
file.write("Hello, World!")
file.seek(0) # Move the cursor to the beginning
content = file.read()
print(content)
file.close()
'a+': Opens a file for both reading and appending. If the file does not exist, it creates a
new file.
file = open("example.txt", "a+")
file.write("\nAppended content")
file.seek(0) # Move the cursor to the beginning
content = file.read()
print(content)
file.close()
Python Program to Match Strings Starting with 'm' and Having 3 Characters
import re
# Define the pattern: starts with 'm' and has exactly 3 characters
pattern = r'^m..'
# Test strings
test_strings = ["man", "map", "moon", "mat", "m", "m123"]
# Search for matches
for string in test_strings:
if re.match(pattern, string):
print(f"Match found: {string}")
else:
print(f"No match: {string}")
Explanation:
A doubly linked list is a type of linked list in which each node contains three parts:
1. Data: The value stored in the node.
2. Previous Pointer: A reference to the previous node in the sequence.
3. Next Pointer: A reference to the next node in the sequence.
Unlike a singly linked list, a doubly linked list allows traversal in both directions (forward
and backward) because each node has pointers to both the previous and next nodes.
Specific Examples
2. Traversing Forward
current = dll.head
while current:
print(current.data, end=" <-> ")
current = current.next
# Output: 1 <-> 2 <-> 3 <-> 4 <->
3. Traversing Backward
current = dll.tail
while current:
print(current.data, end=" <-> ")
current = current.prev
# Output: 4 <-> 3 <-> 2 <-> 1 <->
dll.insert_at_beginning(0)
# Updated list: 0 <-> 1 <-> 2 <-> 3 <-> 4
5. Deleting a Node
def delete(self, data):
current = self.head
while current:
if current.data == data:
if current.prev:
current.prev.next = current.next
else:
self.head = current.next
if current.next:
current.next.prev = current.prev
else:
self.tail = current.prev
return
current = current.next
dll.delete(2)
# Updated list: 0 <-> 1 <-> 3 <-> 4
In Python, a stack is a linear data structure that follows the Last In, First Out (LIFO)
principle. You can implement a stack using built-in data structures like lists or the deque
class from the collections module. Here are the primary operations you can perform
on a stack:
1. Push (Add an Element to the Stack)
Using a List:
stack = []
stack.append(1) # Push 1
stack.append(2) # Push 2
print(stack) # Output: [1, 2]
Using dequeue:
from collections import deque
stack = deque()
stack.append(1) # Push 1
stack.append(2) # Push 2
print(stack) # Output: deque([1, 2])
Using a List:
stack = [1, 2, 3]
top_element = stack.pop() # Pop 3
print(top_element) # Output: 3
print(stack) # Output: [1, 2]
Using dequeue:
from collections import deque
stack = deque([1, 2, 3])
top_element = stack.pop() # Pop 3
print(top_element) # Output: 3
print(stack) # Output: deque([1, 2])
Using a List:
stack = [1, 2, 3]
top_element = stack[-1] # Peek 3
print(top_element) # Output: 3
print(stack) # Output: [1, 2, 3]
Using dequeue:
from collections import deque
stack = deque([1, 2, 3])
top_element = stack[-1] # Peek 3
print(top_element) # Output: 3
print(stack) # Output: deque([1, 2, 3])
Using a List:
stack = []
is_empty = len(stack) == 0
print(is_empty) # Output: True
Using dequeue:
from collections import deque
stack = deque()
is_empty = len(stack) == 0
print(is_empty) # Output: True
Using a List:
stack = [1, 2, 3]
size = len(stack)
print(size) # Output: 3
Using dequeue:
from collections import deque
stack = deque([1, 2, 3])
size = len(stack)
print(size) # Output: 3
6. Clear the Stack
Using a List:
stack = [1, 2, 3]
stack.clear()
print(stack) # Output: []
Using dequeue:
from collections import deque
stack = deque([1, 2, 3])
stack.clear()
print(stack) # Output: deque([])
if condition:
# Code to execute if the condition is True