I needed to create a program that sums the even numbers between 2 and 100. I have the part for this written:
def main():
num = 2
total = 0
while num <= 100:
if num % 2 == 0:
total = total + num
num += 1
else:
num += 1
print("Sum of even numbers between 2 and 100 is:", total)
main()
The next part is I'm supposed to add a while loop within the current while loop that asks for an input of Y/N and will repeat the program if the input is yes. I have spent a long time trying to put the following in different locations:
while again == "Y" or again == "y":
again = input("Would you like to run this again? (Y/N)")
But I haven't been able to get it to work or in best case I get it to print the total of the numbers and ask if I want to run it again but when I type yes it goes back to asking if I want to run it again.
Where do I put the other while statement?
Answer
I the while loop asking for running the program again does not have to be inside the loop computing the sum, then the following should answer your constraints:
def main():
again = 'y'
while again.lower() == 'y':
num = 2
total = 0
while num <= 100:
if num % 2 == 0:
total = total + num
num += 1
else:
num += 1
print("Sum of even numbers between 2 and 100 is:", total)
again = input("Do you want to run this program again[Y/n]?")
main()
Do note that if you answer N
(no, or whatever else that is not Y
or y
) the program stops. It does not ask forever.
No comments:
Post a Comment