You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python整数求和与乘积输出问题:如何正确分线显示结果?

问题解决方案

问题分析

  1. 第一段代码里,sum函数的第二个return永远不会执行——函数遇到第一个return就会终止并返回结果,后续代码不会被触发。
  2. 第二段代码中,函数返回了包含和与乘积的元组,但打印时直接输出整个元组,导致两个结果挤在同一行;同时代码重复计算了乘积,属于冗余操作。

修正后的代码方案

方案一:合理使用函数返回值并解包

# 避免用sum作为函数名,和Python内置函数重名引发冲突
def calc_sum_product(a, b, c):
    return a + b + c, a * b * c

a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))
c = int(input('Enter 3rd number: '))

# 解包函数返回的元组,分别获取和与乘积
total_sum, total_product = calc_sum_product(a, b, c)

print(f'sum of the numbers is equal to: {total_sum}')
print(f'multiplication of numbers is equal to: {total_product}')

方案二:直接计算(更简洁)

a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))
c = int(input('Enter 3rd number: '))

print(f'sum of the numbers is equal to: {a + b + c}')
print(f'multiplication of numbers is equal to: {a * b * c}')

关键说明

  • 输入方式不需要调整,当前input配合int()转换已经能正确读取整数输入。
  • 上述两种方案在输入5、5、5时,都会输出预期结果:
sum of the numbers is equal to: 15
multiplication of numbers is equal to: 125

内容的提问来源于stack exchange,提问作者onlyonce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 21:42:06