Different Types of Print Commands in Python
1. Basic `print()`:
Prints basic strings, numbers, or variables.
print("Hello, World!")
print(42)
x = 10
print(x)
2. Print Multiple Items:
You can print multiple items by separating them with commas.
print("The answer is", 42)
a, b = 5, 10
print("a + b =", a + b)
3. Formatted String (f-strings):
Allows you to insert variables directly in strings using the `f` prefix.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
4. String Concatenation:
You can concatenate strings using the `+` operator.
first_name = "John"
last_name = "Doe"
print("Hello, " + first_name + " " + last_name)
5. Newlines with `\n`:
You can insert newlines inside strings with `\n`.
print("Line 1\nLine 2\nLine 3")
6. Escape Characters:
Handle special characters like quotes and slashes with escape sequences (`\`).
print("He said, \"Python is awesome!\"")
print("Path: C:\\Users\\Name")
7. End Parameter:
By default, `print()` ends with a newline (`\n`). You can change this using the `end` parameter.
print("Hello", end=" ")
print("World!")
8. Separator (`sep`) Parameter:
You can specify how to separate multiple items in a `print()` statement using the `sep` parameter.
print("apple", "banana", "cherry", sep=", ")
9. Print to a File:
You can direct the output of `print()` to a file using the `file` parameter.
with open("output.txt", "w") as file:
print("Writing to a file", file=file)
10. Formatted Print (`format()` function):
You can format strings using the `format()` method.
price = 19.99
quantity = 3
print("Price: ${}, Quantity: {}".format(price, quantity))
11. Printing Lists or Dictionaries:
You can directly print lists, dictionaries, and other data structures.
my_list = [1, 2, 3, 4]
my_dict = {'name': 'John', 'age': 30}
print(my_list)
print(my_dict)
12. Formatted Output for Floating Point Numbers:
You can control the number of decimal places when printing floating-point numbers.
pi = 3.14159
print(f"Pi to 2 decimal places: {pi:.2f}")
13. Suppressing Newline in Print:
To suppress the newline at the end of a `print()` call, use `end=""`.
for i in range(5):
print(i, end=" ")
14. Print Unicode or Special Characters:
You can print Unicode symbols and emojis (handled separately).
15. Flush Parameter:
The `flush` parameter forces the output to be written immediately.
import time
print("Loading...", end="", flush=True)
time.sleep(2)
print(" Done!")
Example combining various `print` features:
name = "John"
age = 30
print(f"Hello, {name}. You are {age} years old.", end=" ")
print("Have a great day!", sep=" ", end="\n")