0

我正在尝试制作一个程序来计算错过课程的成本。我接受变量学费、课程数量和一个学期的周数;然后它绘制结果(使用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)

我假设这是由于一些数学问题,但我没有在整个程序中使用元组,所以我有点不知所措。

任何帮助表示赞赏,谢谢。

4

1 回答 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)

于 2014-04-06T21:35:08.683 回答