Python如何在字符串后同一行打印数字求和结果
你写的代码存在两处错误:
- 赋值操作
score=score+1不能直接放在+拼接符后参与字符串运算 - 数字类型的
score不能直接和字符串拼接,需要先做类型转换
以下是几种可直接运行的修改方案:
方案1:通用字符串拼接方案(兼容所有Python版本)
# 先更新score的值 score = score + 1 # 把score转成字符串后再拼接 print("Your answer is correct, this is your score:" + str(score))
方案2:f-string方案(Python3.6及以上版本推荐,写法最简洁)
不需要手动做类型转换,代码可读性更高:
score += 1 print(f"Your answer is correct, this is your score:{score}")
如果不需要保留更新后的score值,也可以直接把求和逻辑写在占位符中:
print(f"Your answer is correct, this is your score:{score + 1}")
方案3:print多参数输出方案
利用print的多参数特性,设置分隔符为空即可避免手动拼接:
score += 1 print("Your answer is correct, this is your score:", score, sep='')
内容的提问来源于stack exchange,提问作者ProgrammerKidLOL
相关产品推荐
相关产品推荐

