我试图制作一个程序来计算错过课程的费用。我接受一个学期的变量学费,课程数和周数;然后绘制结果(使用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)
由于某些数学原因我假设它,但我没有在整个程序中使用元组,所以我有点不知所措。
感谢任何帮助,谢谢。
答案 0 :(得分: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'
希望现在更有意义。即使你说'#34;我在整个程序中都没有使用元组&#34;,这正是(tuition, courses, weeks)
的所在。