How to return or print multiple variables in Python

0

We have discussed ways to handle variables and the best practices for naming variables in Python. We have noticed a number of searches on the site for how to return or print multiple variables in Python.

Printing multiple variables in Python is quite simple. We are focused on Python 3 with a variation for 3.6+ towards the end.

We will give four examples of how to print multiple variables in Python.

Our initial variables are:

a = 5
b = 10
c = a + b

The first example is using normal string concatenation:

print("sum of", a , "and" , b , "is" , c) 
sum of 5 and 10 is 15

Another method would be to convert variable into str

print("sum of " + str(a) + " and " + str(b) + " is " + str(c))
sum of 5 and 10 is 15

This methods is good in the event you want to print as a tuple

print("sum of %s and %s is %s " %(a,b,c)) 
sum of 5 and 10 is 15

And finally, this f-string formatting works to print multiple variables for Python 3.6 and higher. You’ll see how much simpler this is than previous methods for Python.

print(f'sum of {a} and {b} is {c}')
sum of 5 and 10 is 15

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here