Print Statements & Comments in Python
Introduction
Python is one of the easiest programming languages to learn, and two of the most basic yet powerful features are print statements and comments. These help you display output and make your code more understandable.
What is a Print Statement?
A print statement is used to display output on the screen. It is one of the first things beginners learn in Python.
Basic Syntax
print("Hello, World!")
Output
Hello, World!
Printing Multiple Values
You can print multiple values separated by commas.
print("Hello", "Awais")
Output
Hello Awais
Using Variables in Print
name = "Awais"
age = 20
print("Name:", name)
print("Age:", age)
Formatted Strings (f-strings)
Python provides a clean way to format strings using f-strings.
name = "Awais"
age = 20
print(f"My name is {name} and I am {age} years old")
Escape Characters
Escape characters are used to format output.
print("Hello\nWorld")
print("Hello\tWorld")
Output
Hello World Hello World
What are Comments?
Comments are used to explain code. They are ignored by Python during execution.
Single-line Comments
# This is a comment
print("Hello")
Inline Comments
print("Hello") # This prints Hello
Multi-line Comments
Python does not have a dedicated multi-line comment syntax, but you can use multiple # symbols or triple quotes.
# This is a multi-line comment # Written using multiple lines """ This is also a multi-line comment using triple quotes """
Why Use Comments?
- Improve code readability
- Explain logic
- Help other developers understand your code
- Make debugging easier
Best Practices
- Keep comments clear and short
- Do not overuse comments
- Update comments when code changes
- Use meaningful print statements for debugging
Conclusion
Print statements and comments are essential tools in Python. While print statements help you see output and debug your code, comments make your code easier to understand and maintain. Mastering these basics will build a strong foundation for your programming journey.