[Tutor] While condition
Alan Gauld
alan.gauld at yahoo.co.uk
Fri Mar 17 15:18:01 EDT 2017
On 17/03/17 14:46, Aaliyah Ebrahim wrote:
> Hi, in my code below, why is it returning a value that is greater than 1200
> if my condition is that the value should be less than 1200?
Your condition is that it be less than 1200 when it enters the loop
body. That means it will *always* be 1200 or greater when it exits the
loop. In this case n is 14 when it enters the last loop iteration so the
loop body does:
n = n+1 -> 15
term = n**2 -> 225
list_sum = list_sum + term -> 1240
That means that when it entered the loop the value was
1240-225 = 1015, which is less than 1200.
> def sum_list(val):
> list_sum = 0
> n =0
> mylist = []
> while list_sum < val:
> n = n+1
> term = n**2
> list_sum = list_sum + term
>
> mylist.append(list_sum)
> return list_sum,n,mylist
>
> print(sum_list(1200))
>
> This is the output:
> (1240, 15, [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225])
Incidentally it looks as if your code actually did
mylist.append(term)
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list