Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Python Assignment 1

Python is a high-level, interpreted programming language known for its readability and versatility, supporting various programming paradigms. It is executed line by line by an interpreter, compiling source code into bytecode before running it on the Python Virtual Machine. The document also covers conditional statements, file opening modes, regular expressions, doubly linked lists, and stack operations in Python.

Uploaded by

aryanrasam01
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 Assignment 1

Python is a high-level, interpreted programming language known for its readability and versatility, supporting various programming paradigms. It is executed line by line by an interpreter, compiling source code into bytecode before running it on the Python Virtual Machine. The document also covers conditional statements, file opening modes, regular expressions, doubly linked lists, and stack operations in Python.

Uploaded by

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

1.​ What is python? How python is interpreted.

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.

How Python is Interpreted

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.

2. How the conditional statements works in python?


Ans:
Conditional statements in Python allow you to execute different blocks of code based
on certain conditions. They are fundamental for controlling the flow of your program.
Python provides several types of conditional statements, including if, elif (else if), and
else. Here's how they work:
1. if Statement

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

5. Ternary Operator (Conditional Expression)

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

3. Explain different file opening modes in python.


Ans:
In Python, files are opened using the built-in open() function. The open() function
allows you to specify the mode in which the file should be opened. The mode
determines how the file will be used—whether for reading, writing, appending, or a
combination of these. Here are the different file opening modes in Python:

1. 'r' (Read Mode)

●​ Opens a file for reading.


●​ This is the default mode if no mode is specified.
●​ The file must exist; otherwise, it raises a FileNotFoundError.

Example:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

2. 'w' (Write Mode)

●​ Opens a file for writing.


●​ If the file already exists, it truncates the file (deletes all its content).
●​ If the file does not exist, it creates a new file.

Example:
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()

3. 'a' (Append Mode)

●​ Opens a file for appending.


●​ If the file exists, it appends new content to the end of the file.
●​ If the file does not exist, it creates a new file.

Example:
file = open("example.txt", "a")
file.write("\nThis is a new line.")
file.close()

4. 'x' (Exclusive Creation Mode)

●​ Opens a file for exclusive creation.


●​ If the file already exists, it raises a FileExistsError.
●​ If the file does not exist, it creates a new file.

Example:
try:
file = open("example.txt", "x")
file.write("This is a new file.")
file.close()
except FileExistsError:
print("File already exists.")

5. 'b' (Binary Mode)

●​ Opens a file in binary mode.


●​ This mode is used for non-text files (e.g., images, videos, or executable files).
●​ It can be combined with other modes like 'rb', 'wb', 'ab', etc.

Example:
# Reading a binary file
file = open("image.png", "rb")
data = file.read()
file.close()

# Writing to a binary file


file = open("new_image.png", "wb")
file.write(data)
file.close()

6. 't' (Text Mode)

●​ Opens a file in text mode.


●​ This is the default mode if no mode is specified.
●​ It can be combined with other modes like 'rt', 'wt', 'at', etc.

Example:

file = open("example.txt", "rt") # Same as 'r'


content = file.read()
print(content)
file.close()

7. '+' (Read and Write Mode)

●​ Opens a file for both reading and writing.


●​ It can be combined with other modes like 'r+', 'w+', 'a+', etc.

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()

4. What is regular expression? Write a python program to create a regular


expression using the match () method to search for strings starting with ‘m’
and having total 3 characters.
Ans:
A regular expression (regex) is a sequence of characters that defines a search pattern.
It is used for matching, searching, and manipulating text.

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:

1.​ Pattern: ^m..


○​ ^ asserts the start of the string.
○​ m matches the first character as 'm'.
○​ . matches any character (except a newline).
○​ The second . ensures the third character exists.
2.​ re.match(): Checks if the pattern matches at the beginning of the string.

5. Write definition of doubly linked-list? Give some specific


examples.
Ans:
Definition of a Doubly Linked List

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.

Structure of a Node in a Doubly Linked List


Draw yourself

Specific Examples

1. Creating a Doubly Linked List


class DoublyLinkedList:
def __init__(self):
self.head = None # Head of the list
self.tail = None # Tail of the list

def append(self, data):


new_node = Node(data)
if not self.head: # If the list is empty
self.head = new_node
self.tail = new_node
else:
new_node.prev = self.tail
self.tail.next = new_node
self.tail = new_node

# Create a doubly linked list


dll = DoublyLinkedList()
dll.append(1)
dll.append(2)
dll.append(3)
dll.append(4)

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 <->

4. Inserting a Node at the Beginning


def insert_at_beginning(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
self.tail = new_node
else:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node

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

6. What operations can you do with stack data structure in


python using build in functions?
Ans:

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)

Adds an element to the top of 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])

2. Pop (Remove an Element from the Stack)

Removes and returns the top element of the stack.

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])

3. Peek (Get the Top Element Without Removing It)

Returns the top element of the stack without removing it.

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])

4. Check if the Stack is Empty

Checks whether the stack has no elements.

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

5. Get the Size of the Stack

Returns the number of elements in the stack.

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

Removes all elements from 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

You might also like