简体   繁体   中英

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

我想在python的同一行中的字符串之后打印数字的总和。

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

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)

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}"

如果使用 f 字符串,则可以在格式中添加操作:

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

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
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM