1. Reading a Text File and Counting Words
with open('text_file.txt', 'r') as f:
Explanation
-
open()is used to open a file. -
'text_file.txt'is the file name. -
'r'means read mode. -
withautomatically closes the file after use. -
as fstores the file object in variablef.
content = f.read()
Explanation
-
read()reads all text from the file. -
The text is stored in variable
content.
Example:
If the file contains:
Hello world Python is easy
Then:
content = "Hello world Python is easy"
words = content.split()
Explanation
-
split()breaks text into separate words. - By default, it splits where spaces occur.
Example:
"Hello world Python".split()
becomes:
['Hello', 'world', 'Python']
So words becomes a list of words.
print(f"Number of words: {len(words)}")
Explanation
-
len(words)counts total words in the list. -
f""is an f-string used to insert values into text.
Example Output:
Number of words: 5
2. Handling Division by Zero Using try-except
try:
Explanation
-
tryis used to test code that may cause an error.
num1 = 10
num2 = 0
Explanation
Two variables are created:
-
num1= 10 -
num2= 0
result = num1 / num2
Explanation
This tries to divide:
10÷0
Division by zero is not allowed in Python.
So Python raises an error called:
ZeroDivisionError
print(result)
Explanation
- This would print the result.
- But it never runs because the error happens before it.
except ZeroDivisionError:
Explanation
-
exceptcatches the error. -
If a
ZeroDivisionErroroccurs, Python runs this block instead of stopping the program.
print("Error: Division by zero")
Explanation
This prints a custom error message.
Output:
Error: Division by zero
3. Simple Note-Taker Program
with open('notes.txt', 'a') as f:
Explanation
-
Opens the file
notes.txt. -
'a'means append mode. - Append mode adds new data without deleting old data.
note = input("Enter a note: ")
Explanation
-
input()asks the user to type something. -
The typed text is stored in variable
note.
Example:
Enter a note: Study Python today
Then:
note = "Study Python today"
f.write(note + '\n')
Explanation
-
write()saves text into the file. -
'\n'adds a new line after the note.
So every new note goes on a separate line.
Example file content:
Study Python today
Buy groceries
Complete homework
Final Concepts Used
| Concept | Purpose |
|---|---|
open() | Open a file |
'r' mode | Read file |
'a' mode | Append to file |
read() | Read file content |
split() | Separate text into words |
len() | Count items |
try | Test risky code |
except | Handle errors |
input() | Take user input |
write() | Save data into file |
Discussion (0)