Python Forum
While loops - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: While loops (/thread-4739.html)



While loops - seliz955 - Sep-06-2017

I know that for this program, I need to use a while loop but I am lost on where to even start. I'm confused on what statements even go into the loop. Any help is appreciated. I'm very new at python :)
Generate a list of odd numbers starting from 13, and ending with 2001 and add them together. Print out
the final sum of these odd numbers

#assign a range
x=13
while x<=2001:
y=
print(x,y)


RE: While loops - CroXV - Sep-06-2017

A while statement would run while the expression is true.
for example:
x = 13
while x <= 2001:
    print x
would print 13 infinitely cause there is no way for this expression to be false.

Instead you could increment x within the while loop to exit
x = 13
while x <= 2001:
    print x
    x += 1



RE: While loops - arp0009 - Sep-06-2017

There are two ways to approach this.

1) As you know that every second number will be an odd number. So, we will increase the counter by 2.
x=13
sum = 0
while x<=2001:
sum+=x
x+=2
print(sum)
2) In this approach, we will see if the number is odd and then we will add it to the sum.

x=13
sum = 0
while x<=2001:
if x%2==1:
sum+=x
x+=1
print(sum)
Moreover, Just practice the flow. I mean how things are actually working in the background and you will be able to master it easily. Use this www.pythontutor.com/visualize.html to visualize what's going on behind the scenes.

p.s.: That's not my website and I am not promoting it in any way, just trying to help out OP.