2

I am very new to programming, and have been trying to use python for my research calculations. I need to write a program that does something like this:

If chelDays = [0, 1, 5, 7] For every time t from 1 to 100 , I need t - chelDays for each member of the list chelDays if t > tchelDays. For example, I'd get the following results:see image

Here's what I tried:

chelDays = [0, 1, 5, 7]
while t <100:
    if t > tj:
        print (t, t-tj)
    else:
        print (t, " ")
    t +=1

Edit:

Finally found my solution: Tau = (0, 1, 5, 7) def tMinusTau(t, tj): if t > tj:
return t-tj else: return "" for t in range(1,100): print(t, tMinusTau(t,Tau[0]),tMinusTau(t,Tau1),tMinusTau(t,Tau[2]),tMinusTau(t,Tau[3]))

DPdl
  • 729
  • 6
  • 19
  • Try using a `for tj in range(len(chelDays)-1)` loop. – William Fernandes Oct 06 '16 at 22:29
  • 1
    iteration in python usually involves the `for` loop. Later, you might want to learn `comprehensions`. `while` loops are rarely used in Python, although they obviously have their place. – juanpa.arrivillaga Oct 06 '16 at 22:32
  • 3
    But seriously, next time please try googling your question. You would have found the [official docs](https://docs.python.org/2/tutorial/controlflow.html#for-statements). This would prevent from cluttering SO. Also, just read through the [official tutorial](https://docs.python.org/3.5/tutorial/introduction.html). It is quite good and would help you avoid these basic questions. – juanpa.arrivillaga Oct 06 '16 at 22:34

1 Answers1

4

A for loop is the pythonic way to iterate over items in a collection. You can get this same effect for a range of numbers using range For example, range(1,100) Are the numbers 1-99 (because the stop number is non-inclusive)

So if you want to iterate over t = 1 through t=100 and then check against each item in chelDays for every interval of t you could do the following:

for t in range(1,101):
    for tj in chelDays:
        if t > tj:
            #dostuff
        else:
            #dostuff

Edit: In hindsight, it was unclear if you wanted to check every item in chelDays or not. You may have meant the total value of all the days. If that's the case, you can sum the values by sum(chelDays) e.g sum([1,2,3]) == 6 Or if you wanted the number of items in that list, you would do len(chelDays) e.g len([504,123,234]) == 3

Lastly, a great thing you can do for yourself and others reading your code, try to make your variable names accurately describe what they are. Variable names like x, y, var, etc are usually not appropriate. Of course, there are contexts, such as math formulas where x y t and the like are perfectly fine.

sytech
  • 16,854
  • 2
  • 29
  • 61