Bird
Raised Fist0
Pythonprogramming~10 mins

Writing multiple lines in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Writing multiple lines
Start Program
Open file in write mode
Write first line
Write second line
Write more lines if needed
Close file
End Program
The program opens a file, writes multiple lines one by one, then closes the file to save changes.
Execution Sample
Python
with open('file.txt', 'w') as f:
    f.write('Hello\n')
    f.write('World\n')
This code opens a file and writes two lines: 'Hello' and 'World', each on its own line.
Execution Table
StepActionFile Content After Action
1Open 'file.txt' in write mode
2Write 'Hello\n'Hello
3Write 'World\n'Hello World
4Close fileHello World
💡 File closed, all lines written and saved.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
f (file object)NoneOpen file objectOpen file objectClosed file object
Key Moments - 2 Insights
Why do we use '\n' inside the string when writing lines?
Because '\n' adds a new line, so each write call adds a separate line in the file as shown in steps 2 and 3 of the execution_table.
What happens if we forget to close the file?
The file might not save properly. Closing the file (step 4) ensures all data is written and saved.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the file content after step 2?
A"Hello\nWorld\n"
B"Hello\n"
C"World\n"
D""
💡 Hint
Check the 'File Content After Action' column for step 2 in execution_table.
At which step does the file contain both lines 'Hello' and 'World'?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the file content after each step in execution_table.
If we remove '\n' from the write calls, what changes in the file content?
ALines will be written on separate lines as before.
BFile will be empty.
CAll text will be on the same line without breaks.
DFile will contain '\n' characters as text.
💡 Hint
Remember '\n' creates a new line; without it, text stays on the same line.
Concept Snapshot
Writing multiple lines to a file in Python:
- Open file with open('filename', 'w') as f:
- Use f.write('text\n') to add lines with new line
- Repeat write() for multiple lines
- File closes automatically with 'with' block
- '\n' is needed to separate lines
Full Transcript
This example shows how to write multiple lines to a file in Python. The program opens a file in write mode, writes 'Hello' followed by a new line, then writes 'World' with a new line. Each write adds text to the file. Closing the file saves the changes. Using '\n' ensures each line appears separately. The execution table traces each step and the file content after each write. The variable tracker shows the file object state. Key moments clarify why '\n' is needed and why closing the file matters. The quiz tests understanding of file content at each step and the role of '\n'.

Practice

(1/5)
1. Which of the following is the correct way to write a string that spans multiple lines in Python?
easy
A. Use double quotes but write all text in one line only
B. Use single quotes and separate lines with commas
C. Use triple quotes like '''This is a\nmulti-line string'''
D. Use backslashes at the end of each line without quotes

Solution

  1. Step 1: Understand multi-line string syntax

    Python allows strings to span multiple lines using triple quotes (either ''' or """).
  2. Step 2: Check each option

    Use triple quotes like '''This is a\nmulti-line string''' correctly uses triple quotes to write a multi-line string. Other options misuse quotes or syntax.
  3. Final Answer:

    Use triple quotes like '''This is a\nmulti-line string''' -> Option C
  4. Quick Check:

    Triple quotes = multi-line string [OK]
Hint: Remember: triple quotes let strings span multiple lines easily [OK]
Common Mistakes:
  • Using single or double quotes without triple quotes
  • Trying to separate lines with commas inside quotes
  • Forgetting to close triple quotes
2. Which of these code snippets correctly prints multiple lines using a multi-line string?
easy
A. print('''Line 1\nLine 2\nLine 3''')
B. print('Line 1\n' + 'Line 2\n' + 'Line 3')
C. print('Line 1\nLine 2\nLine 3')
D. print('''Line 1 Line 2 Line 3''')

Solution

  1. Step 1: Understand how multi-line strings handle newlines

    Triple-quoted strings keep line breaks as typed, so actual newlines appear without \n escape sequences.
  2. Step 2: Analyze each option

    print('''Line 1 Line 2 Line 3''') uses triple quotes with actual newlines inside, so it prints three lines. print('''Line 1\nLine 2\nLine 3''') uses \n inside triple quotes, which prints literal \n, not new lines. Options B and D use single quotes with \n, which print new lines correctly, but are not multi-line strings.
  3. Final Answer:

    print('''Line 1 Line 2 Line 3''') -> Option D
  4. Quick Check:

    Triple quotes with real newlines print multiple lines [OK]
Hint: Triple quotes keep line breaks as typed, no need for \n [OK]
Common Mistakes:
  • Using \n inside triple quotes expecting line breaks
  • Confusing escape sequences with actual newlines
  • Using single quotes for multi-line strings
3. What will be the output of this code?
text = '''Hello
World
Python'''
print(text)
medium
A. Hello World Python
B. Hello\nWorld\nPython
C. Hello World Python
D. SyntaxError

Solution

  1. Step 1: Understand triple-quoted string behavior

    The triple quotes preserve the line breaks inside the string as actual newlines.
  2. Step 2: Predict print output

    Printing the string will show three lines: Hello, World, and Python each on its own line.
  3. Final Answer:

    Hello World Python -> Option A
  4. Quick Check:

    Triple quotes print multi-line text as typed [OK]
Hint: Triple quotes print text with real line breaks, not \n literals [OK]
Common Mistakes:
  • Expecting \n to print literally
  • Confusing string representation with print output
  • Syntax errors from missing quotes
4. Find the error in this code that tries to print multiple lines:
text = '''Line 1
Line 2
Line 3'
print(text)
medium
A. Missing closing triple quotes causes SyntaxError
B. Using single quotes inside triple quotes is not allowed
C. print() function is missing parentheses
D. No error, code runs fine

Solution

  1. Step 1: Check string delimiters

    The string starts with triple single quotes ''' but ends with a single quote ', causing a syntax error.
  2. Step 2: Identify error type

    Python expects matching triple quotes to close the string. Mismatched quotes cause SyntaxError.
  3. Final Answer:

    Missing closing triple quotes causes SyntaxError -> Option A
  4. Quick Check:

    Triple quotes must open and close properly [OK]
Hint: Triple quotes must match exactly at start and end [OK]
Common Mistakes:
  • Ending triple-quoted string with single quote
  • Forgetting to close triple quotes
  • Assuming print syntax error instead
5. You want to store a long message with multiple paragraphs in a variable and print it exactly as typed, including blank lines. Which is the best way to do this?
hard
A. Concatenate many single-line strings with + and \n
B. Use triple quotes to write the message with blank lines inside
C. Use single quotes and write all text in one line with \n
D. Use multiple print statements for each line

Solution

  1. Step 1: Understand requirement for preserving formatting

    To keep multiple paragraphs and blank lines exactly as typed, the string must preserve line breaks and spaces.
  2. Step 2: Choose best method

    Triple quotes allow writing multi-line strings naturally, including blank lines, without needing \n or concatenation.
  3. Final Answer:

    Use triple quotes to write the message with blank lines inside -> Option B
  4. Quick Check:

    Triple quotes preserve formatting best for long multi-line text [OK]
Hint: Triple quotes keep all line breaks and spaces as typed [OK]
Common Mistakes:
  • Using concatenation makes code messy and error-prone
  • Forgetting to add \n for new lines in single quotes
  • Using multiple print statements loses single string storage