Marie Pears
Marie Pears

Reputation: 23

error with elif and if statements

I am trying to write a heater function but I am having a few difficulties. I am fairly new to Python.

I want my heater to run for 15000 seconds but for the first 120 seconds (inclusive of 120) I want it to follow a linear path T = 0.0804 * t + 16.081 and then after 120 seconds I want it to remain constant for the rest of the remaining time at the final temperature found from the linear equation.

The code I have written is below which I am getting errors with

import math, numpy as np
from random import *

a = 0.0804
time = range(15001)

for time in xrange(15001):
   if 0 < = time < = 120:
     Temp = a * np.array(time) + 18.3
   elif time > 121:
     Temp = Temp[120]

Errors:

TypeError
Traceback (most recent call last)
  /Library/Python/2.7/site-packages/ipython-1.0.0_dev-py2.7.egg/IPython/utils/py3c‌​ompat.pyc in execfile(fname, *where)
      202 else:
      203 filename = fname
  --> 204 builtin.execfile(filename, *where)
/Users/mariepears/Desktop/heaterfunction.py in <module>
    () 16 print T
       17 elif t>121:
  ---> 18 T=T[120]
TypeError: 'int' object is not subscriptable`

Upvotes: 0

Views: 210

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121266

It looks like you are getting muddled up between time (the range() result, so a list of integers) and Temp (uppercase, the loop variable, an integer).

time = range(15001)
for Temp in xrange(15001):
   if 0 <= Temp <= 120:
     Temp = a * np.array(time) + 18.3
   elif Temp > 121:
     Temp = time[120]

Because time is a list, you should not try to test against if it is smaller or greater than a single integer either; 0 <= time <= 120 makes no sense; ordering between different types always places numbers first, then orders them by type name; integers are always lower than lists, so time > 121 is always True.

temperatures = []
for second in xrange(121):
    last = a * second + 18.3
    temperatures.append(last)

temperatures += temperatures[120:] * (15000 - 120)

Or as a list comprehension:

temperatures = [a * min(sec, 120) + 18.3 for sec in xrange(150001)]

Upvotes: 3

Andrew Jaffe
Andrew Jaffe

Reputation: 27077

In your loop, T is an integer from xrange(150001). In the then clause of your if statement, you set T to be an array, but that doesn't have anything to do with what happens in the elif clause.

In general, you should not reset the loop variable in the loop (and that's probably not what you mean to do).

In your edited version, you have Temp = Temp[120] which is no better: Temp is still not an array here, so you can't subscript it.

Upvotes: 0

Related Questions