Output in Python
In Python, the most common way to display output is by using the built-in print() function. It writes data to the standard output (typically the console or terminal).
Python also supports advanced output formatting with:
- String concatenation
- Formatted string literals (f-strings)
str.format()method
Basic Usage of print()
print_basic.py
print("Hello, World!")output.txt
Hello, World!Explanation:
print()takes one or more arguments and displays them, separated by a space, followed by a newline.
Example 1: Printing Multiple Items
print_multiple.py
print("Python", "is", "fun!")output.txt
Python is fun!Explanation:
print()separates multiple arguments with spaces by default.
Example 2: Printing Variables
print_variables.py
name = "Alice"
age = 30
print(name, "is", age, "years old.")output.txt
Alice is 30 years old.Controlling Separators and End
Using sep argument
print_sep.py
print("Python", "Java", "C++", sep=", ")output.txt
Python, Java, C++Using end argument
print_end.py
print("Hello,", end=" ")
print("World!")output.txt
Hello, World!Explanation:
sepchanges the separator between arguments.endchanges what is printed after the final argument (default is newline\n).
Example 3: String Concatenation with +
print_concat.py
first = "Hello"
second = "World"
print(first + ", " + second + "!")output.txt
Hello, World!Explanation:
- You can concatenate strings using
+. - You must manually handle spaces and punctuation.
Example 4: Using f-strings (Formatted String Literals)
print_fstring.py
name = "Bob"
score = 95.5
print(f"Student {name} scored {score} marks.")output.txt
Student Bob scored 95.5 marks.Explanation:
- Introduced in Python 3.6.
- An
fbefore the string allows embedding expressions inside{}.
Example 5: Using str.format()
print_format.py
product = "Laptop"
price = 899.99
print("The {} costs ${:.2f}".format(product, price))output.txt
The Laptop costs $899.99Explanation:
str.format()inserts values into placeholders{}.:.2fformats the float to 2 decimal places.
Example 6: Formatting Numbers
print_numbers.py
num = 1234567.891
print(f"Formatted number: {num:,.2f}")
print(f"Binary: {42:b}")
print(f"Hexadecimal: {255:x}")output.txt
Formatted number: 1,234,567.89
Binary: 101010
Hexadecimal: ffExplanation:
:,adds comma as thousands separator.bprints binary,xprints hexadecimal.
Example 7: Printing Collections
print_collections.py
fruits = ["apple", "banana", "cherry"]
print(f"Fruits: {fruits}")
person = {"name": "Alice", "age": 28}
print(f"Person: {person}")output.txt
Fruits: ['apple', 'banana', 'cherry']
Person: {'name': 'Alice', 'age': 28}Summary
-
The
print()function is versatile and easy to use. -
You can customize output using:
sepandend- String concatenation with
+ - f-strings (recommended)
str.format()
-
Python makes it simple to display formatted data of any type.