CBSE Class 11 Computer Science
Question 14 of 19
Strings in Python — Question 11
Back to all questionsmINDwORKA
Below is the detailed step by step explanation of the program:
Initialization
Text = "Mind@Work!"
ln = len(Text)
nText = ""Textis initialized with the string"Mind@Work!".lnholds the length ofText, which is10in this case.nTextis initialized as an empty string, which will hold the transformed characters.
Loop through each character
for i in range(0, ln):
if Text[i].isupper():
nText = nText + Text[i].lower()
elif Text[i].isalpha():
nText = nText + Text[i].upper()
else:
nText = nText + 'A'- A
forloop iterates over each indexifrom0toln-1(i.e.,0to9).
Conditions within the loop:
Text[i].isupper(): Checks if the character at indexiin the stringTextis an uppercase letter.- If true, it converts the character to lowercase using
Text[i].lower()and appends it tonText.
- If true, it converts the character to lowercase using
elif Text[i].isalpha(): Checks if the character at indexiin the stringTextis an alphabetic letter (either uppercase or lowercase).- If the character is alphabetic but not uppercase, it converts the character to uppercase using
Text[i].upper()and appends it tonText.
- If the character is alphabetic but not uppercase, it converts the character to uppercase using
else statement of loop:
- The
elsestatement in this context is associated with theforloop, meaning it executes after the loop has completed iterating over all the indices. nText = nText + 'A'appends the character'A'to the end ofnText.
Printing the result
print(nText)- This line prints the final value of
nText.
Step-by-Step Execution
1. Initial States:
Text = "Mind@Work!"ln = 10nText = ""
2. Loop Iterations:
| Index | Character | Condition | Transformation | nText |
|---|---|---|---|---|
| 0 | 'M' | isupper() is True | 'm' | "m" |
| 1 | 'i' | isalpha() is True | 'I' | "mI" |
| 2 | 'n' | isalpha() is True | 'N' | "mIN" |
| 3 | 'd' | isalpha() is True | 'D' | "mIND" |
| 4 | '@' | neither condition is True | - | "mIND" |
| 5 | 'W' | isupper() is True | 'w' | "mINDw" |
| 6 | 'o' | isalpha() is True | 'O' | "mINDwO" |
| 7 | 'r' | isalpha() is True | 'R' | "mINDwOR" |
| 8 | 'k' | isalpha() is True | 'K' | "mINDwORK" |
| 9 | '!' | neither condition is True | - | "mINDwORK" |
3. Post Loop Execution:
- The loop is complete, so the
elsestatement appends'A'tonText. nText = "mINDwORK" + "A" = "mINDwORKA"
4. Print Output:
print(nText)outputs"mINDwORKA".