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

  • Top Programming Languages and Tools Developed Using Python

    Python itself is not typically used to develop other programming languages, as it is a high-level language designed for general-purpose programming. However, Python has been used to create domain-specific languages (DSLs), tools for language development, and educational languages. Here are some examples: 1. Hy 2. Coconut Description: A functional programming language that compiles to Python. It adds…

  • Currency Converter

    Challenge: Currency Converter Class with Accessors & Mutators Objective: Create a CurrencyConverter class that converts an amount from a foreign currency to your local currency, using accessor and mutator methods. 1. Class Properties (Instance Variables) 2. Class Methods 3. Task Instructions

  • non-capturing group, Named Groups,groupdict()

    To create a non-capturing group in Python’s re module, you use the syntax (?:…). This groups a part of a regular expression together without creating a backreference for that group. A capturing group (…) saves the matched text. You can then access this captured text using methods like group(1), group(2), etc. A non-capturing group (?:…)…

  • File Handling in Python

    File Handling in Python File handling is a crucial aspect of programming that allows you to read from and write to files. Python provides built-in functions and methods to work with files efficiently. Basic File Operations 1. Opening a File Use the open() function to open a file. It returns a file object. python # Syntax: open(filename,…

  • AttributeError: ‘NoneType’ Error in Python re

    AttributeError: ‘NoneType’ Error in Python re This error occurs when you try to call match object methods on None instead of an actual match object. It’s one of the most common errors when working with Python’s regex module. Why This Happens: The re.search(), re.match(), and re.fullmatch() functions return: When you try to call methods like .group(), .start(), or .span() on None, you get this error. Example That Causes…

  • Operator Overloading

    Operator Overloading in Python with Simple Examples Operator overloading allows you to define how Python operators (like +, -, *, etc.) work with your custom classes. This makes your objects behave more like built-in types. 1. What is Operator Overloading? 2. Basic Syntax python class ClassName: def __special_method__(self, other): # Define custom behavior 3. Common Operator Overloading Methods Operator…

Leave a Reply

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