Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loops
#1
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)
Reply
#2
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
Reply
#3
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020