类型错误:对 % 操作数类型不支持:'Text' 和 '元组

0 投票
1 回答
6885 浏览
提问于 2025-04-18 01:38

我正在尝试制作一个程序,用来计算缺课的成本。我输入一些变量,比如学费、课程数量和一个学期的周数;然后程序会绘制结果(使用的是Python 2.7)。这是我正在编写的代码:

import matplotlib.pyplot as plot

def calculations(t, c, w, wk):

    two_week = (((t/c)/w)/2)*wk
    three_week = (((t/c)/w)/3)*wk
    return two_week, three_week

def main():
    tuition = float(raw_input('Tuition cost (not including fees): '))
    courses = int(raw_input('Number of courses: '))
    weeks = int(raw_input('Number of weeks in the semester: '))
    x_axis = range(0,10)
    y_axis = []
    y_axis2 = []
    for week in x_axis:
        cost_two, cost_three = calculations(tuition, courses, weeks, week)
        y_axis += [cost_two]
        y_axis2 += [cost_three]

    plot.plot(x_axis, y_axis ,marker='o', label='course meets 2x a week', color='b')
    plot.plot(x_axis, y_axis2,marker='o', label='course meets 3x a week', color='g')
    plot.xlabel('number of missed classes')
    plot.ylabel('cost ($)')
    plot.title('Tuition: %.2f Courses: %d Weeks in a semester: %d\n Created by <MyName>') %(tuition, courses, weeks)
    plot.legend()
    plot.xticks(x_axis)
    plot.xlim(0,x_axis[-1]+1)
    plot.yticks(y_axis)
    plot.ylim(0, y_axis[0]+1)
    plot.grid()
    plot.show()
    plot.savefig('missing-class-cost.pdf')

main()

但是,每当我运行我的程序时,都会收到以下错误信息:

Traceback (most recent call last):
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 36,     in <module>
  File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 26, in main
TypeError: unsupported operand type(s) for %: 'Text' and 'tuple'

第26行是指这行代码:

plot.title('Tuition: %.2f Courses: %d Weeks in a semester: %d\n Created by <MyName>') %(tuition, courses, weeks)

我猜这可能跟某些数学运算有关,但我在整个程序中没有使用元组,所以我有点困惑。

任何帮助都非常感谢,谢谢。

1 个回答

5

你的括号放错地方了。你可能想要的是

plot.title('Tuition: [...]' %(tuition, courses, weeks))

而现在你做的是

plot.title('Tuition: [...]') %(tuition, courses, weeks)

这样你就调用了 plot.title,它返回了一个 Text 对象,然后你又试图在这个对象上使用 %,这就导致了错误信息:

TypeError: unsupported operand type(s) for %: 'Text' and 'tuple'

希望现在你能更明白了。即使你说“我在整个程序中没有使用元组”,但实际上 (tuition, courses, weeks) 就是一个元组。

撰写回答