Python Variables 4

Python Variables Tutorial 4# |Output Variables









How to Use the Python print() Function to Output Variables | Devyra

Using the Python print() Function to Output Variables

The print() function in Python serves as a primary method for displaying variables and outputs. It is commonly used to print the values of variables to the console during program execution.

Basic Variable Output

To display the value stored in a variable, pass it directly into the print() function:

x = "Python is awesome"
print(x)

Outputting Multiple Variables

Python allows the output of multiple variables in a single line by separating them with commas within the print() function:

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

This method automatically inserts spaces between the variables.

String Concatenation with the + Operator

Another way to combine multiple strings is by using the + operator, which concatenates the strings manually:

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

Note: Ensure to include space characters at the end of each string when using +, or the output will appear concatenated without spacing (e.g., Pythonisawesome).

Working with Numbers

When used with numeric variables, the + operator performs mathematical addition:

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

This results in the sum of the two numbers, in this case, 15.

Mixing Strings and Numbers

Attempting to use + to combine a string and a number in Python will raise a TypeError:

x = 5
y = "John"
print(x + y)  # This will cause an error

To output mixed data types correctly, separate them with commas:

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

This approach handles the different types automatically and prints them in a readable format.


For more beginner-friendly Python tutorials, visit Devyra, your trusted learning resource for modern programming education.


More From Author

Python Variables 3

Python Variables Tutorial 3# | Python Variable Assignment: Assigning Multiple Values to Variables

Python Variables 5

Python Variables Tutorial 5# Last | Understanding Global Variables in Python with Practical Examples

Leave a Reply

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

Recent Comments

No comments to show.

Archives

Categories

About Me

Sam Doe

Frequent Traveller

Many lives. Many faces. Different crossroads to different places. 🎶 Listen to my new single release “In My Head” Harlem House Shuffle remix