How do I save incremented Numbers and calculate them?
Question:
I want to write myself a program where a variable is going to increment everytime in the while-loop and want at the end, that all values will be stored in a list. At the end the values of the list should be summed with sum().
My problem is that when I execute my program it just let me show the last number of all. I want to have like l = [5,10,15,...,175]
and not just l = [175]
(I hope its clear what I mean)
def calc_cost():
x = 0
k = 34
j = 0
while x <= k:
x = x + 1
j = j + 5
l = []
l.append(j)
print(sum(l))
print(calc_cost())
Answers:
def calc_cost():
x = 0
k = 34
j = 0
l = []
while x <= k:
x = x + 1
j = j + 5
l.append(j)
print(l)
return sum(l)
print(calc_cost())
I made the edit I suggested. I also returned the sum so it could be printed by the line: print(calc_cost())
Here is the output:
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175]
3150
Here’s a similar approach using the range function:
def calc_cost():
k = 34
l = list( range( 5, (k+2) * 5, 5 ) )
print(l)
return sum(l)
print(calc_cost())
I want to write myself a program where a variable is going to increment everytime in the while-loop and want at the end, that all values will be stored in a list. At the end the values of the list should be summed with sum().
My problem is that when I execute my program it just let me show the last number of all. I want to have like l = [5,10,15,...,175]
and not just l = [175]
(I hope its clear what I mean)
def calc_cost():
x = 0
k = 34
j = 0
while x <= k:
x = x + 1
j = j + 5
l = []
l.append(j)
print(sum(l))
print(calc_cost())
def calc_cost():
x = 0
k = 34
j = 0
l = []
while x <= k:
x = x + 1
j = j + 5
l.append(j)
print(l)
return sum(l)
print(calc_cost())
I made the edit I suggested. I also returned the sum so it could be printed by the line: print(calc_cost())
Here is the output:
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175]
3150
Here’s a similar approach using the range function:
def calc_cost():
k = 34
l = list( range( 5, (k+2) * 5, 5 ) )
print(l)
return sum(l)
print(calc_cost())