Martin
Martin

Reputation: 7

Python print to the same line

if operation == "+":
    print("{} + {} = ".format(number_1, number_2))
    print(number_1 + number_2)

How do I get the print(number_1 + number_2) to the same line of print("{} + {} = ".format(number_1, number_2))?

Upvotes: 0

Views: 181

Answers (5)

direwolf
direwolf

Reputation: 85

This is the easiest way to use;

if operation == "+":
    print("{} + {} = ".format(number_1, number_2),number_1 + number_2)

or

print(f"{number_1} + {number_2} = {number_1 + number_2}")

Upvotes: 0

L3viathan
L3viathan

Reputation: 27333

The easiest way is just to use the same call to print:

if operation == "+":
    print("{} + {} =".format(number_1, number_2), number_1 + number_2)

Another option (probably the best) is to extend your format string:

if operation == "+":
    print("{} + {} = {}".format(number_1, number_2, number_1 + number_2))

But you can also suppress the newline character that print puts at the end of the line by default:

if operation == "+":
    print("{} + {} = ".format(number_1, number_2), end="")
    print(number_1 + number_2)

Final answer:

if operation == "+":
    print(number_1, "+", number_2, "=", number_1 + number_2)

All of these versions print the same thing.

Upvotes: 7

Andrii Chumakov
Andrii Chumakov

Reputation: 319

if you need two print statements, use:

print("{} + {} = ".format(number_1, number_2), end=' ')
print(number_1 + number_2)

end prints end of line by deafult, but I changed it in here to print a space instead.

Upvotes: 0

Biswa Bandhu Bhandary
Biswa Bandhu Bhandary

Reputation: 59

print(f"{number_1} + {number_2} = {number_1 + number_2}")

Python 3.6^ is required to use f string, its cool and nice, just an alternative to .format() method

Upvotes: 1

Sayok Majumder
Sayok Majumder

Reputation: 1091

You can change the line end element of the print statement in the following way:

if operation == "+":
    print("{} + {} = ".format(number_1, number_2),end = '')
    print(number_1 + number_2)

Upvotes: 1

Related Questions