Repository navigation
PyPrint
Welcome to this guide on the Python print() function! This fundamental tool is often the first thing new Python programmers learn, and it's incredibly useful for displaying output, debugging, and more.
- Basic Usage
- Printing Multiple Items
- Formatting Strings
- Escape Characters
- Advanced Print Options
- Common Pitfalls
- Practice Exercises
The print() function is used to output text to the console. Here's the simplest way to use it:
print("Hello, World!")This will display:
Hello, World!
You can print numbers without quotes:
print(42)Output:
42
You can print multiple items by separating them with commas:
print("The answer is", 42)Output:
The answer is 42
Python automatically adds a space between items.
F-strings provide an easy way to embed expressions inside string literals:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")Output:
My name is Alice and I am 30 years old.
For earlier Python versions, use the .format() method:
print("My name is {} and I am {} years old.".format(name, age))Escape characters allow you to include special characters in strings:
-
\n: Newline -
\t: Tab -
\\: Backslash -
\": Double quote -
\': Single quote
Example:
print("First line\nSecond line\n\tIndented")Output:
First line
Second line
Indented
The print() function has several optional parameters:
-
sep: Separator between items (default is a space) -
end: String to append at the end (default is newline) -
file: Object with a write method (default is sys.stdout)
Example:
print("Hello", "World", sep="-", end="!")Output:
Hello-World!
-
Forgetting parentheses:
print "Hello" # SyntaxError in Python 3.x
-
Using commas instead of
+for string concatenation:print("Hello" + "World") # Correct print("Hello", "World") # Prints with a space in between
-
Mixing strings and numbers without conversion:
age = 30 print("I am " + str(age) + " years old.") # Correct print("I am " + age + " years old.") # TypeError
- Print your name and age using an f-string.
- Create a multi-line print statement using escape characters.
- Print the numbers 1 to 5 on the same line, separated by dashes.
- Use the
sepandendparameters to create a custom output format.