Home > Enterprise >  How do I print a sum of numbers after a string in python?
How do I print a sum of numbers after a string in python?

Time:10-23

I want to print a sum of numebrs after a string in the same line in python.

print("Your answer is correct, this is your score:"   score=score 1)

CodePudding user response:

Add 1 to the score before printing.

You also need to convert the score to a string before you can concatenate it. Or you can use string formatting, which is simpler.

score  = 1
print(f"Your answer is correct, this is your score: {score}"

CodePudding user response:

If you use a f-string, you can add the operation in the formatting:

print(f"Your answer is correct, this is your score: {score 1}")

CodePudding user response:

There is a couple of way

>>> score = 10 #you do your calculation first
>>> print("Your answer is correct, this is your score:", score)#print can take any number of arguments
Your answer is correct, this is your score: 10
>>> print("Your answer is correct, this is your score: "   str(score))#make it a string first and concatenate it
Your answer is correct, this is your score: 10
>>> print(f"Your answer is correct, this is your score: {score}")#use f-string
Your answer is correct, this is your score: 10
>>> 

and there are like 2 or 3 other way to make string too, but the first and third examples are the one I recommend, specially f-string, they are awesome.

Additionally, in python 3.8 they introduce the assignment expression := , so you can also do it like you originally tried, with just some adjustments...

>>> score=10 
>>> print("Your answer is correct, this is your score:", (score:=score 1))
Your answer is correct, this is your score: 11
>>> score
11
>>> 

CodePudding user response:

You can use an f-string, but you should also be setting the value of score prior to printing it so it's more clear what's happening:

score  = 1
print(f"Your answer is correct, this is your score: {score}")

You can do it your way, but you have to convert score to a string before you can concatenate it (via ) to another string:

score  = 1
print("Your answer is correct, this is your score: "   str(score))

Another way is to add score as an argument to print; in that case you don't have to convert it to a string:

score  = 1
print("Your answer is correct, this is your score: ", score)
  • Related