I'm having some trouble with a homework problem on MyPytutor which is asking me to write a function sum_from_to(start, end) that uses a while loop to compute the sum of the integers from start up to, but not including end.
The given code is:
def sum_from_to(start, end):
"""Return the sum of the integers from start up to but not including end.
sum_from_to(int, int) -> int
"""
# add your code here: use a while loop
Examples:
How would I approach this? I've seen this same question from half a year ago but it was never resolved. Any help would be greatly appreciated as I'm really stuck on this!
Initialize a while loop between [start, end[ (with end excluded with this sign : "<") Then iterate on the start number. So for 3 to 7 the numbers will be : 3,4,5,6 Then you just have to add this numbers, so just initialize a var befor your while loop and add this var with the number you iterate
def sum_from_to(start, end):
"""Return the sum of the integers from start up to but not including end.
sum_from_to(int, int) -> int
"""
result = 0
i = start
while i < end:
result += i
i += 1
return result
Here are some examples to get you started
a = 0
while a < 10:
a += 1
print a
You could probably do it with
sum(range(start, end))
I'd delivery this:
def sum_from_to(start, end):
ret = 0
while start < end:
ret += start
start += 1
return ret
But I like the way it looks below (without the while - which doesn't fit your requirements):
def sum_from_to(start, end):
return sum(x for x in range(start, end))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.