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

Python函数两参数相乘结果异常:输入4和5未得到预期值20

问题排查与修复

错误根源

你代码里的data_size_input = int(input("What is the data size? ")),这一行末尾多了个逗号,这个逗号让data_size_input变成了仅包含单个整数的元组(比如输入4时,它的值是(4,))。

在Python中,元组与整数相乘的逻辑是重复元组内的元素N次,而非数值乘法。所以当你把(4,)和5传入函数后,data*backup执行的是元组重复操作,最终得到(4,4,4,4,4)。

修复后的代码

只需去掉data_size_input赋值语句末尾的逗号即可:

#!/usr/bin/python3

#Create a function named calculate_backup_size that takes two arguments: data and backup. 
#This function should return the data multiplied by backup, representing the total storage needed for backups in a week.

data_size_input = int(input("What is the data size? "))
backup_frequency_input = int(input("What is the backup frequency? "))

def calculate_backup_size(data, backup):
    return data*backup

storage = calculate_backup_size(data_size_input, backup_frequency_input)
print(storage)

验证结果

输入4和5时,函数会执行整数乘法4*5,输出预期的20。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:07:19