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

Python中for循环获取科目分数时input函数报错求助

解决Python中input()多参数导致的TypeError问题

嗨,我来帮你理清楚这个报错的原因并搞定它!

为什么会出现这个报错?

你写的input("enter score for subject no ",i)里,Python的input()函数只接受1个位置参数——也就是用来提示用户的字符串。但你这里传了两个独立的内容:前面的提示字符串和变量i,Python会把它们当成两个参数,所以就触发了TypeError: raw_input() takes from 1 to 2 positional arguments but 3 were given(注:Python2里是raw_input(),Python3统一为input(),报错逻辑一致)。

怎么实现按科目编号追踪分数?

核心思路是把科目编号i先整合到提示字符串里,变成一个完整的字符串再传给input()。这里给你三种常用的写法,选你顺手的就行:

1. 用f-string(最推荐,Python3.6+可用)

f-string是Python里最简洁直观的字符串格式化方式,直接把变量嵌在字符串里:

list1 = []
no = int(input("enter your no. of subjects: "))
for i in range(no):
    # 把i改成i+1,让科目编号从1开始显示,更符合日常习惯
    score = int(input(f"enter score for subject no {i+1}: "))
    list1.append(score)
print(list1)

2. 用str.format()(兼容更早Python版本)

如果你的Python版本比较老,用这种方式也能实现:

list1 = []
no = int(input("enter your no. of subjects: "))
for i in range(no):
    score = int(input("enter score for subject no {}: ".format(i+1)))
    list1.append(score)
print(list1)

3. 字符串拼接(最基础的写法)

把变量转换成字符串后,和原提示字符串拼接在一起:

list1 = []
no = int(input("enter your no. of subjects: "))
for i in range(no):
    score = int(input("enter score for subject no " + str(i+1) + ": "))
    list1.append(score)
print(list1)

小提醒

原代码里range(no)生成的索引是从0开始的,所以我在示例里都改成了i+1,这样用户看到的科目编号就是1、2、3...而不是0、1、2啦,更符合使用习惯~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 11:37:28