0% found this document useful (0 votes)
1 views9 pages

Python - UT-2 Querstion & Answers

The document discusses various programming concepts in Python, including string comparison, the difference between tuples and lists, and the structure of dictionaries. It also covers file handling, basic list operations, string creation and slicing, and exception handling methods with examples. Each section provides code snippets and explanations to illustrate the concepts effectively.

Uploaded by

Ayyanar Manickam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views9 pages

Python - UT-2 Querstion & Answers

The document discusses various programming concepts in Python, including string comparison, the difference between tuples and lists, and the structure of dictionaries. It also covers file handling, basic list operations, string creation and slicing, and exception handling methods with examples. Each section provides code snippets and explanations to illustrate the concepts effectively.

Uploaded by

Ayyanar Manickam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1) Illustrate string comparison with example?

String Comparison in Programming

String comparison means checking if two strings are equal or determining their
lexicographic (dictionary) order. It's a common operation in programming.

Example in Python:
python
CopyEdit
str1 = "Apple"
str2 = "Banana"
str3 = "Apple"

# Equality check
print(str1 == str2) # False
print(str1 == str3) # True

# Lexicographic comparison
print(str1 < str2) # True (because 'Apple' comes before 'Banana')
print(str2 > str3) # True (because 'Banana' comes after 'Apple')

2) Write difference between tuples and list in python?

3) What is the key value pair in dictionary?

A dictionary in Python is a collection of key-value pairs. Each key is unique and maps to a
value.
4) How to open a new file in python?

In Python, you use the open() function to open (or create) a file.

5) List any four common exception errors and explain when they occur?
6) List any four methods that are used in python list?

1.append()

 Adds an element to the end of the list.

2. remove()

 Removes the first occurrence of a specified value.

3. insert(index, value)

 Inserts a value at a specific position.

4. pop()

 Removes and returns the item at the given index (or last item by default).
PART-B

1. Explain the basic list operation that can be performed in python with an example
for each?

1. Creating a List

 Syntax: my_list = [element1, element2, ...]


 Example:

my_list = [1, 2, 3, 4]

📌 2. Accessing Elements

 Use index starting from 0


 Example:

print(my_list[0]) # Output: 1

📌 3. Updating Elements

 Change value at a specific index


 Example:

my_list[1] = 10
# my_list becomes [1, 10, 3, 4]

📌 4. Adding Elements

 append() → Adds to end


 insert(index, value) → Adds at specific position
 Example:

my_list.append(5)
my_list.insert(2, 99)

📌 5. Removing Elements

 remove(value) → Removes first occurrence of value


 pop(index) → Removes element at index
 Example:

my_list.remove(10)
my_list.pop(2)
📌 6. Slicing a List

 Extracts sub-parts using [start:end]


 Example:

sub = my_list[1:3] # Gets items from index 1 to 2

📌 7. Looping Through a List

 Example:

for item in my_list:


print(item)

📌 8. Checking Membership

 Use in or not in
 Example:

3 in my_list # True
99 not in my_list # Depends on content

2) Explain how a string can be created in python and explain the various slicing
operation in string?

Creating Strings in Python

 A string is a sequence of characters enclosed in single, double, or triple quotes.

✅ Examples:
str1 = 'Hello'
str2 = "World"
str3 = '''This is a multi-line string'''

📌 String Indexing

 Characters in a string are accessed using indexing (starts at 0).

text = "Python"
print(text[0]) # Output: 'P'
print(text[-1]) # Output: 'n' (negative indexing)

📌 String Slicing

 Slicing is used to get a substring from a string.


 Syntax: string[start:end]
(includes start, excludes end)
✅ Examples:
text = "Python"

print(text[0:2]) # Output: 'Py' → from index 0 to 1


print(text[2:]) # Output: 'thon' → from index 2 to end
print(text[:4]) # Output: 'Pyth' → from start to index 3
print(text[-3:]) # Output: 'hon' → last 3 characters
print(text[::2]) # Output: 'Pto' → every 2nd character

🔁 Slicing Format
string[start : end : step]
Example:
text = "Programming"
print(text[0:11:2]) # Output: 'Pormig'

3) Write a python programme to create atext file with the content ‘’my first python
programming using files’’ in the name file 1.txt and then copy the contents of the file to
file 2.txt

Here’s a Python program that:

1. Creates a text file named file1.txt with the content


"my first python programming using files", and
2. Copies the content to another file named file2.txt.

✅ Python Program:
# Step 1: Create and write to file1.txt
with open("file1.txt", "w") as file1:
file1.write("my first python programming using files")

# Step 2: Read from file1.txt and write to file2.txt


with open("file1.txt", "r") as file1:
content = file1.read()

with open("file2.txt", "w") as file2:


file2.write(content)

print("Content copied from file1.txt to file2.txt successfully.")

📝 What this does:

 Uses the with statement for automatic file handling.


 Writes the initial message to file1.txt.
 Reads it and writes the same content to file2.txt.
4) Explain the difference exception handling methods with example?

) Difference Between Exception Handling Methods in Python

Python provides several ways to handle exceptions using the try-except block. Here are the
common methods:

1. Basic try-except

 Handles any exception that occurs in the try block.


 If an error occurs, the code in except runs.

try:
x = 10 / 0
except:
print("An error occurred")

Output:
An error occurred

2. Catching Specific Exceptions

 Handles specific types of exceptions.


 Useful to handle known errors differently.

try:
x = int("abc")
except ValueError:
print("ValueError: Cannot convert string to integer")

Output:
ValueError: Cannot convert string to integer

3. Multiple Except Blocks

 Catch different exceptions separately with multiple except blocks.

try:
x = 10 / 0
except ZeroDivisionError:
print("ZeroDivisionError occurred")
except ValueError:
print("ValueError occurred")

Output:
ZeroDivisionError occurred
4. else Block

 Runs if no exception occurs in the try block.

try:
x = 10 / 2
except ZeroDivisionError:
print("Error: division by zero")
else:
print("Success! Result is", x)

Output:
Success! Result is 5.0

5. finally Block

 Always runs, whether or not an exception occurred.


 Often used for cleanup actions like closing files.

try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This will always execute")

Output:

Cannot divide by zero


This will always execute

Summary Table

Method Description Runs When

try-except Catch all exceptions Exception occurs

Specific except Catch specific exception types Specific exception

Multiple except Different handling for exceptions Different exceptions

else Runs if no exceptions No exception

finally Runs always (cleanup) Always

You might also like