Practice Question 2
In this post, we will learn how to write a function that finds and displays all the special symbols (like @, #, $, etc.) present in a text file. This is an excellent way to practice using “Conditional Logic” to filter out data you don’t need.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To solve this, we need to look at every character and decide if it counts as a “Special Symbol.” Here is the step-by-step logic:
- Open & Read: We open
data.txtand read the content. - The Alphanumeric Check: We check every character using
.isalnum(). If it is a letter or a number, we don’t want it. - The
continueStatement: If the character is a letter or number, we usecontinueto skip the rest of the loop and move to the next character. - Print the Rest: Anything that doesn’t get skipped by the
continuestatement is a special symbol, so we print it!
Let’s Code as per the above logic :
def displaySpecialSymbols():
f = open("data.txt", "r")
data = f.read()
for alpha in data:
if alpha.isalnum():
continue
else:
print(alpha, end=" ")
f.close()
# To call the function:
displaySpecialSymbols()
Important Notes for Students
As a teacher, I want you to focus on these three key points so you don’t lose marks:
-
Using
continue: Thecontinuekeyword is very powerful. It tells Python, “Stop right here for this character and jump back to the start of the loop for the next one.” It’s a clean way to skip data you don’t need. -
What is
isalnum()? This method returnsTrueif the character is a letter (A-Z) or a digit (0-9). By skipping these, we are naturally left with symbols and spaces. -
The Space Factor: In this logic, spaces will also be printed because a space is not “alphanumeric.” If your teacher wants you to ignore spaces too, you can change the condition to
if alpha.isalnum() or char == ' ':.
Teacher’s Secret Tip for Exams:
This program is not just for special symbols. By changing only the condition inside the if, the same logic can be used to print digits, letters, uppercase, lowercase, or any specific character type in the exam.
Want to practice more? If you found this helpful, I have compiled a full list of 30 practice problems just like this one. Each question focuses on a different logic to help you become a pro at File Handling.
Click here to view the full 30-Question Practice Set