So im making a program that calculates the sum of squared values within a range. This is what I have so far:
def sum_squares():
one = eval(input("Enter lower range?: "))
two = eval(input("Enter upper range?: "))
for x in range(one,two+1):
print(x*x)
I want to put "print(sum(x*x))" at the end but it gives me an error. What do.
Videos
Hello, so I am trying to understand how to sum values through a for loop within python so that I start with a value, and then add to it, and then add the next value to that, and then add the next value to that, and so on, going through all values in my list/folder. I think this would be referred to as a "cumulative sum". So let's say I have a list of numbers:
list = [1,4,6,3,7,5,2,8,9]
I want to iterate over each value in this list and add all values to the previous like so:
for value in list:
1 + value
sum = 1 + value
print(sum)or something like that? I tried this, and it just adds one to each value in the list, when I want a single final cumulative sum produced. I am really confused about if my logic is correct there. Is this how I would carry out this cumulative sum operation? I am trying to take 1, and then add 4, and then add 6 to that, and then add 3 to that sum, and then add 7 to that sum, and so on. I realize one could also just add all of these values at once, but I am trying to understand how to do this with a for loop. Thanks!
prices[item] * cart[item] for item in cart is a generator. It produces an iterable, which is what the sum function takes as its first parameter.
for item in cart iterates over each of the keys in the cart dictionary. So in this case, it will iterate over the list ['apple', 'egg'], setting item to each of these in turn. For each iteration, the expression prices[item] * cart[item] looks up the price of an item (prices['apple'] for example) and multiplies it by the quantity of an item (cart['apple'] for example). The generator produces a sequence consisting of the result of computing the value of this expression for each key in cart, and then sum takes that sequence and adds the elements of it together to come up with the final total of the items in cart.
The code that's in the inside of the sum() is a generator expression which is basically syntactic sugar for creating an iterator from another iterator.
In your example the cart variable is an object of type Dictionary which is also an iterator, and the prices[item] * cart[item] part is how each item from the cart (the dictionary keys) is transformed into a new item for the result iterator.
The snippet bill = sum(prices[item] * cart[item] for item in cart) is equivalent to
Copybill = 0
for item in cart:
bill += prices[item] * cart[item]
This can be expressed using a list comprehension and the sum function:
a = int(input('Enter a number plz '))
print(sum(x*x for x in range(a+1)))
Expanded out, this would be equivalent to:
a = int(input('Enter a number plz '))
total = []
for x in range(a+1):
total.append(x*x)
print(sum(x))
Here's a simpler solution:
a = int(input('Enter a number plz '))
lst = []
for i in range(1, a+1):
def func(root):
print('Number', i, 'in square root is', root)
lst.append(root)
func(i*i)
print(f'The sum is {sum(lst)}')
You can create an empty list, then append all the values of root as you iterate through the for-loop. Now we have a list of all of the root values, so we can make use of the built-in sum function to achieve our final product.
Also note that it is not necessary to have your function in the for-loop:
a = int(input('Enter a number plz '))
def func(root):
print('Number', i, 'in square root is', root)
lst.append(root)
lst = []
for i in range(1, a+1):
func(i*i)
print(f'The sum is {sum(lst)}')
You are printing the value of variable "c" in the loop. To print only the sum, remove the indentation of "print(c)". And you are doing "=+" but you should do "+=" to obtain the sum.
c=0
for i in range(0,101):
c+=i
print(c)
There's a python function just for this - sum
print(sum([x for x in range(1, 101)]))
Edit: To address the concern about "struggling to understand"
[x for x in range(1, 101)] is called a list comprehension. They are used to create lists in a singular line, without using for loops - python can be a functional programming language after all. [x for x in range(1, 101)] returns a list from 1 to 100, that is-
[1, 2, 3, 4, 5, ......., 99, 100]
We skip 0 because it doesn't count in the sum anyway.
Now if you do sum() on this list, it'll return the sum of all elements in the list.
Hence sum([for x in range (1, 101)]) returns the sum of all numbers from 1 to 100 (inclusive) and print will print the final result.
Why use many lines when few do trick? :)
Remember, List Comprehension and sum() are 2 very important tools in the python toolbox, everyone should know about these 2.
Anyone asking you to write For loops in Mathematica for such a problem is a dolt. Nevertheless, here's how you might do that:
rslt = 0;
For[i = 0, i <= 50, i += 2, rslt += i];
rslt
And here's how someone with some familiarity with Mathematica might write it
Plus @@ Range[25]*2
Now, spend the time you were going to waste writing a For loop by reading the answers to this question Why should I avoid the For loop in Mathematica?
The first fifty positive integers can be computed with Table:
Q = 0; (* Initialization *)
T = Table[Q + k, {k, 2 Range[50]}]

We can sum up the values of T with Sum:
Sum[T[[k]], {k, Range[50]}]
2550
By for loop
def sumAll(n):
sum_all = 0
for i in range(1, n+1):
sum_all = sum_all + i
return sum_all
number = int(raw_input("Please enter a number: \n"))
print ("The answer is: ") + str(sumAll(number))
Output:
Please enter a number:
10
The answer is: 55
You can also use list Comprehension:
print sum([i for i in range(number+1)])
Output:
55
You can also use a mathematical series formula:
def sumAll(n):
return n * (n + 1) / 2
you can even do it without a loop:
def sumAll(n):
return sum(range(1,n+1))
print(sumAll(10)) # -> 55
if you insist on using a loop:
def sumAll(n):
s = 0
for i in range(1,n+1):
s += i
return s
but the mathematical solution is simply:
def sumAll(n):
return n * (n + 1) / 2
# in python 3:
# return n * (n + 1) // 2
(there are n elements with an average value of (n+1)/2; this will always be an integer since either n or n+1 is even; the proof by induction is often the first example when math students learn about induction...).
Yes! Both summations and for loops are designed as a shorthand of saying "I want to do this a whole bunch of times but I don't really want to write it all out. Here's the step to repeat and the pattern each step varies by, have at it ;) ."
I could define some variable x = 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 + 81 + 100, or I could just say x = [the sum of the squared integers 1 to 10, inclusive]. As you pointed out, this is just a summation: sigma from i=1 to 10 of i^2; if you were to ask a computer scientist to add those numbers together, immediatly (s)he would type something like this:
int x = 0;
for(int i = 1; i <= 10; i++) {
x += i*i;
}
As I'm sure you recognize, this is a rather trivial example. The power of a for loop comes not from adding a bunch of numbers but from executing statements of code with the altered variable as a parameter.
Whereas sigma can be thought of as a function that sums the results of some function (as it really is, in its most general form, sigma from i=[lower bound] to [upper bound] of f(i), where f(x) is some function... sorry about the formating, I'm not sure how to do mathematic symbols on SE), a for loop can perform actions with those values of f(i).
I'm not sure if that makes sense, but I guess the TL;DR summery would be that yes, a summation is just a specific kind of for-loop, but a for-loop is much more expressive as it allows the programmer to define what to do with the values of its incrementing variable(s). I suppose you could say there's greater logical control in a for-loop than you find in a summation.
$\sum_{n=a}^b f(n)$
is equivalent to
<?php
$sum = 0;
for ($n = a; $n <= b; $n++) {
sum +=f(n);
}
?>
Or in Python, sum([f(n) for n in range(a,b+1)])