Python Output Variables

Discover how to use the print() function in Python to output variables. Explore basic examples of displaying variable values to the console.



Python - Output Variables

The Python print() function is commonly used to output variables. Let's explore some examples:

Basic Example

Example

x = "Python is awesome"
print(x)
            
Output

Python is awesome
            

Output Multiple Variables

You can use the print() function to output multiple variables, separated by commas:

Example

x = "Python"
y = "is"
z = "awesome"
(x, y, z)
            
Output

Python is awesome
            

Using the + Operator

You can also use the + operator to concatenate multiple variables:

Example

x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
            
Output

Python is awesome
            

Note the space characters after "Python " and "is ". Without them, the result would be "Pythonisawesome".

Mathematical Operations with Numbers

For numbers, the + operator performs addition:

Example

x = 5
y = 10
print(x + y)
Output

15

Combining Strings and Numbers

If you try to combine a string and a number with the + operator, Python will produce an error:

Example (with Syntax Error)

x = 5
y = "John"
print(x + y)
Error Output:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

This code will result in an error.

Using Commas for Mixed Data Types

The best way to output multiple variables in the print() function, especially when dealing with different data types, is to separate them with commas:

Example

x = 5
y = "John"
print(x, y)
Output

5 John