Python > Core Python Basics > Input and Output > Printing Output (print())

Basic Printing with `print()`

This snippet demonstrates the fundamental use of the `print()` function in Python to display output to the console. It covers printing strings, numbers, and variables.

Basic `print()` Usage

The `print()` function displays the given arguments to the standard output (usually the console). Multiple arguments can be passed, separated by commas. Python automatically inserts a space between them. You can print literal strings, numbers, and the values of variables.

print("Hello, world!")
print(123)

name = "Alice"
age = 30
print(name)
print(age)
print("Name:", name, "Age:", age)

Concepts Behind the Snippet

The `print()` function is a built-in function in Python. It converts the input arguments to strings (if necessary) and writes them to the output stream. By default, it adds a newline character (`\n`) at the end, so each `print()` statement starts on a new line. Understanding how to use `print()` is crucial for debugging and displaying program results.

Real-Life Use Case

Imagine you're writing a program to calculate the average score of students in a class. You can use `print()` to display each student's score, the total score, and the calculated average. This helps you verify that your calculations are correct and provides useful information to the user.

Best Practices

Use descriptive variable names to make your code more readable. Add comments to explain what your code is doing. When printing multiple values, consider using f-strings for more concise formatting (see next snippet).

When to use them

`print()` is essential whenever you need to display information to the user, whether it's the result of a calculation, the current state of a program, or debugging messages.

Pros

`print()` is simple, easy to use, and widely available in all Python environments.

Cons

For complex output formatting, using f-strings or other formatting techniques (like `str.format()`) can provide more control and readability.

FAQ

  • How do I print multiple values on the same line without a space in between?

    You can use the `sep` argument of the `print()` function to specify a different separator. For example, `print("Hello", "world", sep="")` will print "Helloworld".
  • How do I prevent `print()` from adding a newline at the end?

    Use the `end` argument. For example, `print("Hello", end=" ")` will print "Hello" followed by a space, and the next `print()` statement will continue on the same line.