print() function

The print() function is one of the most commonly used built-in functions in Python. Its primary job is to take data (like text, numbers, or variables) and display it on your screen (the console).

The Anatomy of print()

The complete syntax for the print() function looks like this:

Python

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

While it looks complex, you only need to use the parts you need. Here is a breakdown of what each parameter does:

  • *objects: The items you want to print. You can print as many objects as you want, separated by commas.
  • sep: How to separate multiple objects. The default is a single space (' ').
  • end: What to place at the very end of the printed line. The default is a newline character ('\n'), which is why each print() statement usually starts on a new line.
  • file: Where to send the output. The default is the standard output screen (sys.stdout), but you can use this to print directly into a text file.
  • flush: A boolean (True or False) that dictates whether to forcibly flush the stream. (Usually left as False).

Examples of Using print()

1. Basic Output

The simplest way to use print() is to pass a single string or number.

Python

print("Hello, World!")
print(42)

# Output:
# Hello, World!
# 42

2. Printing Multiple Items (*objects)

You can print multiple items in a single print() statement by separating them with commas. By default, Python will automatically insert a space between them.

Python

name = "Alice"
age = 13
print("My name is", name, "and I am", age, "years old.")

# Output:
# My name is Alice and I am 13 years old.

3. Changing the Separator (sep)

If you don’t want a space between your items, you can change the sep parameter. This is highly useful for formatting dates, times, or file paths.

Python

# Separating with a hyphen
print("apple", "banana", "cherry", sep="-")

# Separating with nothing (an empty string)
print("S", "u", "p", "e", "r", sep="")

# Output:
# apple-banana-cherry
# Super

4. Changing the Ending (end)

By default, every print() function ends by moving the cursor to the next line. If you want consecutive print() functions to display on the same line, you can change the end parameter.

Python

print("Loading", end="...")
print("Complete!")

# Output:
# Loading...Complete!

5. Combining sep and end

You can use multiple optional parameters in the same function call to get exactly the formatting you want.

Python

print("1", "2", "3", sep=" -> ", end=" GO!\n")

# Output:
# 1 -> 2 -> 3 GO!

6. Modern Printing: f-strings

While using commas to print multiple items works, modern Python (version 3.6+) uses f-strings (formatted string literals) as the standard way to mix variables and text. It makes the print() function much easier to read.

You simply place an f before the opening quote and put your variables inside curly brackets {}.

Python

item = "coffee"
price = 4.99

# Without f-string:
print("Your", item, "costs $", price, sep="")

# With f-string (Cleaner and easier to read):
print(f"Your {item} costs ${price}")

# Output for both:
# Your coffee costs $4.99

Similar Posts

  • Instance Variables,methods

    Instance Variables Instance variables are variables defined within a class but outside of any method. They are unique to each instance (object) of a class. This means that if you create multiple objects from the same class, each object will have its own separate copy of the instance variables. They are used to store the…

  • Python Statistics Module

    Python Statistics Module: Complete Methods Guide with Examples Here’s a detailed explanation of each method in the Python statistics module with 3 practical examples for each: 1. Measures of Central Tendency mean() – Arithmetic Average python import statistics as stats # Example 1: Basic mean calculation data1 = [1, 2, 3, 4, 5] result1 = stats.mean(data1) print(f”Mean of…

  •  index(), count(), reverse(), sort()

    Python List Methods: index(), count(), reverse(), sort() Let’s explore these essential list methods with multiple examples for each. 1. index() Method Returns the index of the first occurrence of a value. Examples: python # Example 1: Basic usage fruits = [‘apple’, ‘banana’, ‘cherry’, ‘banana’] print(fruits.index(‘banana’)) # Output: 1 # Example 2: With start parameter print(fruits.index(‘banana’, 2)) # Output: 3 (starts searching…

  • Classes and Objects in Python

    Classes and Objects in Python What are Classes and Objects? In Python, classes and objects are fundamental concepts of object-oriented programming (OOP). Real-world Analogy Think of a class as a “cookie cutter” and objects as the “cookies” made from it. The cookie cutter defines the shape, and each cookie is an instance of that shape. 1. Using type() function The type() function returns…

  • Dynamically Typed vs. Statically Typed Languages 🔄↔️

    Dynamically Typed vs. Statically Typed Languages 🔄↔️ Dynamically Typed Languages 🚀 Python Pros: Cons: Statically Typed Languages 🔒 Java Pros: Cons: Key Differences 🆚 Feature Dynamically Typed Statically Typed Type Checking Runtime Compile-time Variable Types Can change during execution Fixed after declaration Error Detection Runtime exceptions Compile-time failures Speed Slower (runtime checks) Faster (optimized binaries)…

Leave a Reply

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