0% found this document useful (0 votes)
4 views14 pages

Important Questions Unit II

The document is a question bank with answers focused on Python programming concepts, including strings, loops, and regular expressions. It covers topics such as string immutability, loop control statements, string methods, and the use of the range() function. Each question is answered with explanations and examples to illustrate the concepts.

Uploaded by

25eu06022
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)
4 views14 pages

Important Questions Unit II

The document is a question bank with answers focused on Python programming concepts, including strings, loops, and regular expressions. It covers topics such as string immutability, loop control statements, string methods, and the use of the range() function. Each question is answered with explanations and examples to illustrate the concepts.

Uploaded by

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

UNIT-2 QUESTION BANK ANSWERS

1. What is a string in Python?


2. Write the syntax for concatenating two strings.
3. Explain the continue statement along with examples.
4. Differentiate between break and continue statements.
5. Name the function used to find the length of a string.
6. What is meant by string immutability?
7. What is an indefinite loop?
8. What happens if a semicolon is used at the end of a Python statement?
9. Discuss the types of loops used in Python with suitable examples.
10. Differentiate between definite and indefinite loops.
11. Explain the loop control statements available in Python.
12. Explain string slicing with examples.
13. Justify the statement “Strings are immutable in Python”.
14. Explain the use of the range() function with examples.
15. Write a Python program to interchange the first and last characters of a given string.
16. Define string methods and explain at least five string methods with an example program.
17. Discuss loops in Python and explain how break and continue statements affect loop
execution.
18. Write Python programs to demonstrate:
a) String concatenation
b) String slicing
c) Iterating through a string
19. What is a regular expression?
20. Differentiate between the following regex functions in Python:
a) [Link]() and [Link]()
b) [Link]() and [Link]()
21. Write a Python program to count the number of words in a sentence using regular
expressions.
22. Explain ord() and chr() Functions.

ANSWERS

1. What is a string in Python?

A string in Python is a sequence of characters enclosed within single quotes (' '),
double quotes (" "), or triple quotes (''' ''' / """ """).

Example:

s1 = "Python"
s2 = 'Programming'

2. Write the syntax for concatenating two strings.

String concatenation is done using the + operator.

Syntax: string3 = string1 + string2


UNIT-2 QUESTION BANK ANSWERS

Example:

a = "Hello "
b = "World"
c=a+b
print(c)

Output: HelloWorld

3. Explain the continue statement along with examples.

The continue statement skips the current iteration of a loop and moves to the next
iteration.

Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5

4. Differentiate between break and continue statements.

Feature break continue


Purpose Terminates the loop Skips current iteration
Control Exits loop completely Continues next iteration
Execution Loop stops Loop continues
Ex: Ex:
for i in range(1, 6): for i in range(1, 6):
if i == 3: if i == 3:
continue break
print(i) print(i)
Output: Output:
1 1
2 2
4
5
UNIT-2 QUESTION BANK ANSWERS

5. Name the function used to find the length of a string.

The function used to find the length of a string is len() function.

Example:

s = "Python"
print(len(s))
Output:6

6. What is meant by string immutability?

String immutability means that once a string is created, its contents cannot be changed.
If you try to modify a string, a new string is created instead of changing the original
one.
Ex:
s = "Hello"
s[0] = "h" # ❌ Error

7. What is an indefinite loop?

An indefinite loop is a loop in which the number of iterations is not known in advance.

The loop continues to execute as long as a condition remains true and stops only when
the condition becomes false.

Example: while loop

Example Program:

num = 1

while num <= 5:


print(num)
num += 1
Output:
1
2
3
4
5

8. What happens if a semicolon is used at the end of a Python statement?


UNIT-2 QUESTION BANK ANSWERS

Using a semicolon does not cause an error. It is optional and mostly ignored.

Example:

print("Hello");

9. Discuss the types of loops used in Python with suitable examples.

Python supports two types of loops:

a) for loop

Used when number of iterations is known.

for i in range(5):
print(i)

b) while loop

loops are programming constructs that execute a block of code repeatedly until a
condition is met. Basically two types of looping statements in Python, they are
i) while ii) for
i) while Loop:
While loop is used to execute a block of statements repeatedly until a given condition
is satisfied. When the condition becomes false, the line immediately after the loop in
the program is executed.

Syntax of while loop :


while condition:
statement(s)
UNIT-2 QUESTION BANK ANSWERS

Example:
i=1
while i<=5:
print(i, end=” “)
i+=1
Output: 1 2 3 4 5
ii) for Loop:
In Python, the for loop is used to iterate over a sequence (such as a list, tuple, string,
or dictionary) or any iterable object.

The basic syntax of the for loop is:


For Loop Syntax with sequence:
for var in sequence:
# statements
Example:
for i in range(5):
print(i, end= “ “)
Output: 0 1 2 3 4
10. Differentiate between definite and indefinite loops.
Definite Loop Indefinite Loop
The number of iterations is known in The number of iterations is not known in
advance advance
Loop runs for a fixed number of times Loop runs until a condition becomes false
Uses a counter or range Depends on a condition
Commonly implemented using for loop Commonly implemented using while loop
Ex: Ex:
for i in range(5): i=1
print(i, end= “ “) while i<=5:
Output: 0 1 2 3 4 print(i, end=” “)
i+=1
Output: 1 2 3 4 5
UNIT-2 QUESTION BANK ANSWERS

11. Explain the loop control statements available in Python.

Loop control statements are used to control the flow of execution inside loops.
Python provides three loop control statements:

a. break
b. continue
c. pass

a. break Statement

The break statement is used to terminate the loop immediately, even if the loop
condition is still true.

Example:

for i in range(1, 6):


if i == 4:
break
print(i, end= “ “)

Output:1 2 3

b. continue Statement

The continue statement is used to skip the current iteration and move to the next
iteration of the loop.

Example:

for i in range(1, 6):


if i == 3:
continue
print(i, end= “ “)

Output: 1 2 4 5

c. pass Statement

The pass statement is a null statement.


It does nothing and is used as a placeholder where a statement is required
syntactically.

Example:
UNIT-2 QUESTION BANK ANSWERS

for i in range(1, 4):


print(i)
pass
Output: 1 2 3
12. Explain string slicing with examples.
String slicing is used to extract a part (substring) from a string.
Syntax:
string[start:end:step]
Examples:
Ex 1:
s = "Python"
print(s[0:4])
Output: Pyth
Ex 2:
print(s[:3])
Output: Pyt
Ex 3:
print(s[2:])
Output: thon
Ex 4:
print(s[::2])
Output: Pto
Ex 5:
print(s[-4:-1])
Output: tho
Ex 6 Reverse a String:
print(s[::-1])
Output: nohtyP

13. Justify the statement “Strings are immutable in Python”.

Once a string is created, its characters cannot be modified.

Example:

s = "Hello"
s[0] = 'h' # Error

This proves immutability.

14. Explain the use of the range() function with examples.

The range() function is used to generate a sequence of numbers. It is commonly used


in loops, especially for loops.
UNIT-2 QUESTION BANK ANSWERS

Syntax: range(start, stop, step)

Examples:

1. range(stop)

for i in range(5):

print(i, end= “ “)

Output: 0 1 2 3 4

[Link](start, stop)

for i in range(2, 7):

print(i, end= “ “)

Output: 2 3 4 5 6

3. range(start, stop, step)

for i in range(1, 10, 2):

print(i, end= “ “)

Output: 1 3 5 7 9

15. Write a Python program to interchange the first and last characters of a
given string.

Program:

s = input("Enter string: ")

if len(s) > 1:
new_string = s[-1] + s[1:-1] + s[0]
print(new_string)
else:
print(s)
Input:
Enter string: python
Output:
nythop
UNIT-2 QUESTION BANK ANSWERS

16. Define string methods and explain at least five string methods with an
example program.

String methods are built-in functions used to manipulate strings.


Common methods:
1. upper()
Converts all lowercase letters in a string to uppercase.
Example: "hello".upper() → "HELLO"
2. lower()
Converts all uppercase letters in a string to lowercase.
Example: "HELLO".lower() → "hello"
3. len()
Returns the number of characters in a string (including spaces).
Example: len("Python") → 6
4. replace(old, new)
Replaces all occurrences of a specified substring with another substring.
Example: "I like Java".replace("Java", "Python")
5. split()
Splits a string into a list of words based on a delimiter (space by default).
Example: "Python is easy".split()
6. join()
Joins elements of a list into a single string, using a specified separator.
Example: " ".join(["Python", "is", "easy"])
7. swapcase()
Changes lowercase letters to uppercase and uppercase letters to lowercase.
Example: "PyThOn".swapcase() → "pYtHoN"
8. max()
Returns the character with the highest ASCII value in the string.
Example: max("Python") → 'y'
9. min()
Returns the character with the lowest ASCII value in the string.

Example:

s = "Python Programming"
print("Original String:", s)

print("Uppercase:", [Link]())
print("Lowercase:", [Link]())
print("Length of string:", len(s))
print("After replace:", [Link]("Python", "Java"))
words = [Link]()
print("After split:", words)
UNIT-2 QUESTION BANK ANSWERS

joined_string = "-".join(words)
print("After join:", joined_string)
print("After swapcase:", [Link]())
print("Maximum character:", max(s))
print("Minimum character:", min(s))
Output :
Original String: Python Programming
Uppercase: PYTHON PROGRAMMING
Lowercase: python programming
Length of string: 18
After replace: Java Programming
After split: ['Python', 'Programming']
After join: Python-Programming
After swapcase: pYTHON pROGRAMMING
Maximum character: y
Minimum character: P

17. Discuss loops in Python and explain how break and continue statements
affect loop execution.

Loops are programming constructs that execute a block of code repeatedly until a
condition is met.

Basically two types of looping statements in Python, they are


i) while ii) for
i) while Loop:
While loop is used to execute a block of statements repeatedly until a given condition
is satisfied. When the condition becomes false, the line immediately after the loop in
the program is executed.
Syntax of while loop :
while condition:
statement(s)
ii) for Loop:
In Python, the for loop is used to iterate over a sequence (such as a list, tuple, string,
or dictionary) or any iterable object.
The basic syntax of the for loop is:
for Loop Syntax with sequence:
for var in sequence:
# statements

Loop control statements like break, continue are used to control the flow of
execution inside loops.
a. break Statement
UNIT-2 QUESTION BANK ANSWERS

The break statement is used to terminate the loop immediately, even if the loop
condition is still true.

Example:

for i in range(1, 6):


if i == 4:
break
print(i, end= “ “)

Output:1 2 3

b. continue Statement

The continue statement is used to skip the current iteration and move to the next
iteration of the loop.

Example:

for i in range(1, 6):


if i == 3:
continue
print(i, end= “ “)

Output: 1 2 4 5

18. Write Python programs to demonstrate:

a) String concatenation

String concatenation means joining two or more strings using the + operator.

Ex:
s1 = "Hello"
s2 = "World"
result = s1 + " " + s2
print(result)

Output: Hello World

b) String slicing

String slicing is used to extract a part of a string using indexes.

Syntax: string[start:end:step]
UNIT-2 QUESTION BANK ANSWERS

Ex:
s = "Python"
print(s[0:4]) # characters from index 0 to 3
print(s[2:]) # from index 2 to end
print(s[::-1]) # reverse string

Output:

Pyth
thon
nohtyP

c) Iterating through a string

Iterating through a string means accessing each character one by one.

Ex:
s = "Python"

for ch in s:
print(ch)
Output:
P
y
t
h
o
n

19. What is a regular expression?

A regular expression (regex) is a sequence of characters used to search, match, and


manipulate text patterns.

In Python, regular expressions are handled using the re module.

Examples of use:

 Validate email addresses


 Find phone numbers
 Search words in text
 Replace patterns

20. Differentiate between the following regex functions:


UNIT-2 QUESTION BANK ANSWERS

a) [Link]() vs [Link]()

Feature [Link]() [Link]()


Search position Beginning of string only Anywhere in string
Returns Match object or None Match object or None

Example:

import re

text = "Python programming"

print([Link]("Python", text))
print([Link]("programming", text))

b) [Link]() vs [Link]()

Feature [Link]() [Link]()


Return type List of matches Iterator of match objects
Memory Higher Lower (efficient)
Match details Values only Position + value

Example:

import re

text = "cat bat rat mat"

print([Link]("at", text))

for match in [Link]("at", text):


print([Link](), [Link]())

21. Write a Python program to count the number of words in a sentence using
regular expressions.

import re

sentence = input("Enter a sentence: ")


words = [Link](r'\b\w+\b', sentence)
print("Number of words:", len(words))
UNIT-2 QUESTION BANK ANSWERS

Input:
Python is easy to learn
Output:
Number of words: 5

22. Explain ord() and chr() Functions.

 ord(): Returns ASCII value of a character


 chr(): Returns the character for the corresponding ASCII value

Example:

print(ord('A')) # 65
print(chr(65)) # A

You might also like