Project Overview 💡
In this project, you'll write a Python script that asks the user to enter three sentences and saves them into a text file. Between each sentence (except the last), a dashed line will be written to visually separate them.
Challenge Yourself! 🚀
Before checking the solution, try building a script that collects input from a user and writes it to a file in a structured format.
Task:
Write a Python program that:
Prompts the user to enter three different sentences
Writes each sentence to a file, separated by a dashed line (
-----------
) except after the last oneSaves the content to a file named
user_sentences.txt
Expected Output:
The program prompts the user three times to enter three sentences.
Once the user has entered the three sentences, the program produces a text file with the three sentences inside and dashes between them.
Give it a shot! Scroll down when you're ready for the step-by-step guide.
Spoiler Alert!
Step-by-Step Guide
Step 1️⃣: Define the Output File
Choose a name for your text file.
filename = "user_sentences.txt"
Step 2️⃣: Open the File in Write Mode
Use a with
statement to open the file so it closes automatically after writing.
with open(filename, "w") as file:
Step 3️⃣: Loop to Get User Input
Ask the user for a sentence three times, writing each one to the file.
for i in range(3):
sentence = input(f"Enter sentence {i+1}: ")
file.write(sentence + "\n")
Step 4️⃣: Add Dashed Lines Between Sentences
Insert separator lines between sentences—but not after the last one.
if i < 2:
file.write("-----------\n")
Step 5️⃣: Confirmation Message
Notify the user that their input was saved.
print(f"Sentences have been saved to {filename}.")
Complete Code 🧨
# Define the file name
filename = "user_sentences.txt"
# Open the file in write mode
with open(filename, "w") as file:
# Loop three times to get sentences from the user
for i in range(3):
# Prompt the user to enter a sentence
sentence = input(f"Enter sentence {i+1}: ")
# Write the sentence to the file
file.write(sentence + "\n")
# If it's not the last sentence, add dash lines
if i < 2:
file.write("-----------\n")
print(f"Sentences have been saved to {filename}.")
Alternative Solution
Here’s a version that collects all input first and writes to the file afterward:
filename = "user_sentences.txt"
sentences = [input(f"Enter sentence {i+1}: ") for i in range(3)]
with open(filename, "w") as file:
for i, sentence in enumerate(sentences):
file.write(sentence + "\n")
if i < 2:
file.write("-----------\n")
print(f"Saved 3 sentences to {filename}.")
Comparison
The original version writes to the file as the user types.
The alternative version collects all input first, which can make the logic easier to manage for more complex input tasks.
Want More? 🔥
Enjoyed this project? Unlock real-world projects with full guides & solutions by subscribing to the paid plan. 🎉