
input()函数仅接受单个字符串作为提示信息,不支持逗号分隔的多个参数或关键字参数;需通过字符串格式化(如f-string、str()拼接或.format())动态插入变量值。
`input()`函数仅接受单个字符串作为提示信息,不支持逗号分隔的多个参数或关键字参数;需通过字符串格式化(如f-string、`str()`拼接或`.format()`)动态插入变量值。
在Python中,input()函数的设计非常简洁:它只接收一个可选的位置参数——即提示字符串(prompt),且不接受任何关键字参数(如sep=、end=等),也不支持类似print()那样的多参数自动转换与拼接。这正是你遇到 TypeError: input() takes no keyword arguments 的根本原因。
观察出错代码:
sets = int(input("How many sets were completed in workout #", a, "?\n", sep=""))此处你误将 input() 当作 print() 使用:print() 支持多参数 + sep,会自动将各参数转为字符串并按分隔符连接;但 input() 仅接受一个字符串,其余参数(包括sep=)均被解释为非法关键字参数,从而触发 TypeError。
✅ 正确做法是:先构造完整的提示字符串,再传给 input()。推荐以下三种现代、清晰且安全的方式:
立即学习“Python免费学习笔记(深入)”;
✅ 推荐方案1:f-string(Python 3.6+,最简洁直观)
workouts = int(input("How many workouts do you have data for?\n"))
a = 0
b = 0
for i in range(workouts):
a += 1 # 注意:原代码中a未递增,会导致所有提示均为"workout #0"
sets = int(input(f"How many sets were completed in workout #{a}?\n"))✅ 推荐方案2:str.format()(兼容性更广)
sets = int(input("How many sets were completed in workout #{}?\n".format(a)))✅ 推荐方案3:+ 拼接(需显式转换为字符串)
sets = int(input("How many sets were completed in workout #" + str(a) + "?\n"))⚠️ 重要注意事项:
- 原代码中变量 a 初始化为 0,但在循环内未更新,导致每次提示都是 "workout #0"。务必在循环中递增(如 a += 1)或直接使用循环变量 i(推荐:workout #{i+1});
- 对用户输入执行 int() 转换前,建议添加异常处理,避免非数字输入导致程序崩溃(生产环境必备):
while True: try: sets = int(input(f"How many sets were completed in workout #{i+1}?\n")) break except ValueError: print("Please enter a valid integer.")
? 总结:牢记 input(prompt) 是单参数函数,所有动态内容必须预先整合进 prompt 字符串。优先使用 f-string 提升可读性与维护性,同时注意逻辑变量的正确更新与输入校验,才能写出健壮、专业的交互式Python程序。










