OzzyPyro
OzzyPyro

Reputation: 47

Repeating a while loop after user input

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?

Upvotes: 1

Views: 9164

Answers (4)

domochevski
domochevski

Reputation: 553

If 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.

Upvotes: 1

Olivier Melan&#231;on
Olivier Melan&#231;on

Reputation: 22294

It is always good to check if your summation has a closed form. This series being similar to the sum of positive integers, it has one so there is no reason to iterate over even numbers.

def sum_even(stop):
    return (stop // 2) * (stop // 2 + 1)

print(sum_even(100)) # 2550

To put that in a while loop, ask for the user input after the function call and break if it is 'y'.

while True:
    stop = int(input('Sum even up to... '))
    print(sum_even(stop))
    if input('Type Y/y to run again? ').lower() != 'y':
        break

Output

Sum even up to... 100
2550
Type Y/y to run again? y
Sum even up to... 50
650
Type Y/y to run again? n

Upvotes: 1

probat
probat

Reputation: 1532

def sum_evens():
    active = True
    while active:
        sum_of_evens = 0
        for even in range(2, 101, 2):
            sum_of_evens += even
        print('Sum of the evens is:', sum_of_evens)
        while True:
            prompt = input('Type "Y" to start again or "N" to quit...\n')
            if prompt.lower() == 'y':  # doesn't matter if input is caps or not
                break
            elif prompt.lower() == 'n':
                active = False
                break
            else:
                print('You must input a valid option!')
                continue

sum_evens()

Upvotes: 1

Mahir Islam
Mahir Islam

Reputation: 1972

You should add the while loop at the beginning and ask the user at the end. Like this:

num = 2
total = 0
con_1 = True
while con_1:
   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)
   ask = str(input("Do you want to run this program again(Y/n)?:"))
   if ask == "Y" or ask == "y":
       con_1 = True
   elif ask == "N" or ask == "n":
       con_1 = False
   else:
       print("Your input is out of bounds.")
       break

Upvotes: 0

Related Questions