The print() Function

The print() Function Syntax in Python 🖨️

The basic syntax of the print() function in Python is:

Python

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Let’s break down each part:

  • print(): This is the function name.
  • *objects (positional argument, arbitrary number):
    • This represents one or more items (objects) that you want to print.
    • You can pass numbers, strings, variables, lists, dictionaries, results of expressions, etc.
    • If you pass multiple objects, they will be converted to strings and printed.
  • sep=' ' (keyword argument, optional):
    • This stands for “separator”.
    • It specifies how the objects are separated when multiple items are printed.
    • By default, it’s a single space character (' ').
    • You can change it to any string, e.g., sep=',' for comma-separated values, or sep='---' for dashes.
  • end='\n' (keyword argument, optional):
    • This specifies what to print at the end of the output.
    • By default, it’s a newline character ('\n'), which means after print() finishes, the cursor moves to the next line.
    • You can change it to an empty string (end='') to keep the cursor on the same line, or any other string.
  • file=sys.stdout (keyword argument, optional):
    • This specifies where the output should go.
    • By default, it’s sys.stdout, which means the output is sent to the standard output device (usually your console or terminal).
    • You can redirect the output to a file by providing a file object, e.g., file=my_file_object.
  • flush=False (keyword argument, optional):
    • This is a boolean argument that controls whether the output stream is forcibly flushed.
    • When True, the output is immediately written to the file.
    • When False (default), the output might be buffered, meaning it’s held in memory for a short time before being written, which can be more efficient for large outputs.

Simple Examples to Illustrate: 💡

Python

# 1. Printing a single string
print("Hello, Python!") # Output: Hello, Python!

# 2. Printing multiple objects with default separator
name = "Alice"
age = 30
print("Name:", name, "Age:", age) # Output: Name: Alice Age: 30

# 3. Changing the separator
print("Apple", "Banana", "Cherry", sep="-") # Output: Apple-Banana-Cherry

# 4. Preventing a newline at the end
print("Loading...", end="")
print("Done!") # Output: Loading...Done!

# 5. Redirecting output to a file
# with open("log.txt", "w") as f:
#     print("This message goes to a file!", file=f)
#     # This will write "This message goes to a file!" into a new file named log.txt

# 6. Printing expressions
print(2 + 3 * 4) # Output: 14

Basic print() Function in Python with Examples 🖨️

The print() function is used to display output in Python. It can print text, numbers, variables, or any combination of these.


1. Simple Print Statement 🗣️

Prints a string or number directly:

Python

print("Hello, World!")  # Output: Hello, World!
print(42)              # Output: 42

2. Printing Multiple Items 🧩

Separates items with a space by default:

Python

name = "Alice"
age = 25
print("Name:", name, "Age:", age)  # Output: Name: Alice Age: 25

3. Changing the Separator (sep) ↔️

Use sep to customize how items are separated:

Python

print("Python", "Java", "C++", sep=" | ")  # Output: Python | Java | C++

4. Preventing Line Breaks (end) ➡️

Override the default newline (\n) with end:

Python

print("Hello", end=" ")
print("World!")  # Output: Hello World!

5. Printing Special Characters ✨

Use escape sequences for formatting:

Python

print("Line1\nLine2\tIndented")
# Output:
# Line1
# Line2    Indented

6. Printing Variables with f-strings (Python 3.6+) 💬

Embed variables directly in strings:

Python

name = "Bob"
print(f"Hello, {name}!")  # Output: Hello, Bob!

Key Takeaways 🎯

  • Basic Syntax: print("text") or print(variable). 📝
  • Multiple Items: Separate with commas (default space separator). ➕
  • Custom Separators: Use sep="|" to change the delimiter. ↔️
  • No Newline: Set end="" to print on the same line. ➡️
  • f-strings: Clean way to embed variables (Python 3.6+). ✨

The print() function is essential for debugging and displaying results in Python! 🚀

Here are 10 practical examples of f-strings in Python, covering basic to advanced usage: ✨


1. Basic Variable Insertion 📝

Embed variables directly in strings.

Python

name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old.")
# Output: My name is Alice and I'm 25 years old.

2. Mathematical Expressions ➕

Perform calculations inside the f-string.

Python

x = 10
y = 3
print(f"{x} + {y} = {x + y}")
# Output: 10 + 3 = 13

3. Number Formatting 🔢

Control the display of numbers.

A. Round Floats 🔢. Specify the number of decimal places.

Python

pi = 3.14159
print(f"Pi ≈ {pi:.2f}")  # 2 decimal places
# Output: Pi ≈ 3.14

B. Add Commas to Large Numbers 💲 Improve readability of large numbers.

Python

population = 1_000_000
print(f"Population: {population:,}")
# Output: Population: 1,000,000

C. Percentages 📈 Format as a percentage.

Python

ratio = 0.75
print(f"Completion: {ratio:.0%}")
# Output: Completion: 75%

4. String Alignment ↔️

Align text within a specified width.

Python

text = "Python"
print(f"{text:>10}")  # Right-aligned (10 spaces)
print(f"{text:<10}")  # Left-aligned
print(f"{text:^10}")  # Centered
# Output:
#     Python
# Python    
#   Python  

5. Date Formatting 📅

Format datetime objects.

Python

from datetime import datetime
today = datetime.now()
print(f"Today: {today:%B %d, %Y}")
# Output: Today: June 23, 2025 (or current date)

6. Dictionary Values 📚

Access dictionary values directly.

Python

user = {"name": "Bob", "age": 30}
print(f"{user['name']} is {user['age']} years old.")
# Output: Bob is 30 years old.

7. Function Calls 📞

Embed function calls within the string.

Python

def greet(name):
    return f"Hello, {name}!"
print(f"{greet('Alice')}")
# Output: Hello, Alice!

8. Debugging (Python 3.8+) 🐞

Print variable name and value for quick debugging.

Python

x = 42
print(f"{x = }")  # Prints variable name and value
# Output: x = 42

9. Multiline F-Strings 📜

Create formatted multiline strings.

Python

name = "Alice"
score = 95.5
print(f"""
Name: {name}
Score: {score:.1f}/100
""")
# Output:
# Name: Alice
# Score: 95.5/100

10. Conditional Logic 🤔

Use a ternary operator for simple conditions.

Python

age = 17
print(f"{'Adult' if age >= 18 else 'Minor'}")
# Output: Minor

Key Advantages of F-Strings ✨

  • Readability: Embed variables/expressions directly in strings. 📖
  • Performance: Faster than % formatting or .format(). 🚀
  • Flexibility: Supports expressions, formatting, and even debugging. 🤸

When to Use F-Strings? 💡

  • Dynamic messages (e.g., user greetings). 💬
  • Formatting numbers/dates. 🔢📅
  • Debugging complex variables. 🐛

F-strings make your code cleaner and more efficient! ✅

Similar Posts

  • Sets in Python

    Sets in Python A set in Python is an unordered collection of unique elements. Sets are mutable, meaning you can add or remove items, but the elements themselves must be immutable (like numbers, strings, or tuples). Key Characteristics of Sets: Different Ways to Create Sets in Python Here are various methods to create sets in…

  • Why Python is So Popular: Key Reasons Behind Its Global Fame

    Python’s fame and widespread adoption across various sectors can be attributed to its unique combination of simplicity, versatility, and a robust ecosystem. Here are the key reasons why Python is so popular and widely used in different industries: 1. Easy to Learn and Use 2. Versatility Python supports multiple programming paradigms, including: This versatility allows…

  • group() and groups()

    Python re group() and groups() Methods Explained The group() and groups() methods are used with match objects to extract captured groups from regex patterns. They work on the result of re.search(), re.match(), or re.finditer(). group() Method groups() Method Example 1: Basic Group Extraction python import retext = “John Doe, age 30, email: john.doe@email.com”# Pattern with multiple capture groupspattern = r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’///The Pattern: r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’Breakdown by Capture…

  •  List Comprehensions 

    List Comprehensions in Python (Basic) with Examples List comprehensions provide a concise way to create lists in Python. They are more readable and often faster than using loops. Basic Syntax: python [expression for item in iterable if condition] Example 1: Simple List Comprehension Create a list of squares from 0 to 9. Using Loop: python…

  • Thonny: A User-Friendly Python IDE for Beginners in 2025

    Thonny is a free and open-source Integrated Development Environment (IDE) specifically designed for beginners learning Python. It provides a simple and user-friendly interface, making it an excellent choice for those new to programming. Key Features: Why Thonny is good for beginners: How to install Thonny: If you’re new to Python and looking for a user-friendly…

Leave a Reply

Your email address will not be published. Required fields are marked *