Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
25: Multiline Strings and Docstrings
I want to show you a mistake I see a lot when people start writing more complex scripts—specifically when they need to handle blocks of text like SQL queries, HTML templates, or long email bodies. Take a look at this snippet where someone is trying to build a basic database query:
def get_user_data(user_id):
query = "SELECT username, email, join_date
FROM users
WHERE id = " + str(user_id)
return query
print(get_user_data(101))
The EOL Scanning Error
If you try to run that, Python is going to throw a SyntaxError: EOL while scanning string literal. "EOL" stands for End of Line. Essentially, Python sees that opening double quote on the first line and starts looking for the closing quote. But it hits the end of the physical line before it finds one. Python doesn't just assume you wanted the string to continue on the next line; it assumes you forgot to close the quote and gives up.
Now, you could fix this by using concatenation or escape characters, but that makes your code look like a mess and is a pain to maintain. There's a much cleaner way.
Triple Quotes for Multiline Strings
In Python, we have triple quotes—either """ or '''. These tell Python, "Keep reading everything, including the line breaks, until you see another set of triple quotes." Let's fix that query:
def get_user_data(user_id):
query = """SELECT username, email, join_date
FROM users
WHERE id = """ + str(user_id)
return query
print(get_user_data(101))
This works perfectly. One thing to keep in mind: triple quotes preserve everything. If you indent the second and third lines of your string to make the code look pretty, those spaces and tabs actually become part of the string. I usually keep the multiline text flush against the left margin or use a helper function if the indentation is critical.
Turning Strings into Documentation
The exact same triple-quote syntax is used for something else entirely: Docstrings. A docstring is just a string literal that occurs as the first statement in a module, function, class, or method definition. Python doesn't just ignore these; it attaches them to the object as metadata.
I've worked on a few legacy projects where there were zero docstrings, and let me tell you—it's a nightmare. You spend half your day guessing what a function actually does. Here is how you should be doing it:
def calculate_compound_interest(principal, rate, time):
"""
Calculates the total amount of an investment over time.
Args:
principal (float): The initial amount of money.
rate (float): The annual interest rate (as a decimal).
time (int): The number of years.
Returns:
float: The final balance.
"""
return principal * (1 + rate) ** time
The magic here is that because this is a docstring, other developers (and your future self) can access this information without reading the source code. If you call help(calculate_compound_interest) in a Python console, Python will print out that exact block of text. It's the professional way to communicate how your code is intended to be used.
📋 Practical Task
Task: Building a Documented User Profile Generator
You need to create a function called generate_user_bio that takes three arguments: name, occupation, and hobby.
Your task is to:
- Add a comprehensive docstring to the function explaining its purpose, its arguments, and what it returns.
- Use a multiline string (triple quotes) to create a formatted biography template that looks like this:
Name: [name]
Job: [occupation]
Interest: [hobby]
--------------------
Status: Active
The function should return the completed biography string with the arguments inserted into the template. Test your function by calling it and printing the result to the console.
There are no comments for now.