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

Python学生学分计算程序报错:TypeError: 字符串无法执行减法运算

解决Python学分计算代码的字符串减法报错问题

问题原因

你代码里的错误出在获取学分的两行:

Credits_Required = input(int( ))
Credits_Attained = input(int( ))

input()函数的参数是用来显示提示文本的,你传int()进去毫无意义,而且input()默认返回的是字符串类型,所以这两个变量实际存的是用户输入的字符串,字符串之间不能用减法运算,就触发了TypeError。

修正方案

把用户输入的字符串转换成整数类型,正确的写法是用int()包裹input(),先获取输入再转类型:

Credits_Required = int(input())
Credits_Attained = int(input())

完整修正后的代码

print('Enter student name: ')
StudentName = input()

print('What degree program are you in?: ')
Degree = input()

print("How many credits are required to graduate?: ")
Credits_Required = int(input())

print("How many credits have you acquired?: ")
Credits_Attained = int(input())

Credits_Needed = Credits_Required - Credits_Attained

print("The student's name is " + StudentName)
print("Degree Program: " + Degree)
print(StudentName, "needs", Credits_Needed, "more credits.")

可选优化写法

可以把提示文本直接放进input()里,同时用f-string简化输出,让代码更简洁:

StudentName = input('Enter student name: ')
Degree = input('What degree program are you in?: ')
Credits_Required = int(input("How many credits are required to graduate?: "))
Credits_Attained = int(input("How many credits have you acquired?: "))

Credits_Needed = Credits_Required - Credits_Attained

print(f"The student's name is {StudentName}")
print(f"Degree Program: {Degree}")
print(f"{StudentName} needs {Credits_Needed} more credits.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 17:33:14