Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to only show the final result after adding or multiplying all natural numbers

It has been a week since I started to self-study python and I tried making a program that adds or multiplies all natural numbers and the problem is I want to only show the final result of all the sum or product of all natural numbers. How do I do it?

repeat = 'y'
a=0
while repeat.lower() == 'y':
    result = 0
    choice = 0
    i=0
    product = 1
   
    
    num = int(input("Enter the value of n: "))
    if num < 1 or num > 100 :
        print('must be from 1-100 only')
        repeat = input("\nDo you want to try again?Y/N\n>>> ")
        continue
        
    print('1. Sum of all natural numbers')
    print('2. Product of all numbers')
    choice  = int(input("Enter choice: "))
    

    
    if choice == 1:
        while(num > 0):
            result += num
            num -= 1
            print(' ',result)
            
    if choice ==2:
    
        while i<num:
            i=i+1
            product=product*i
            print(' ', product)

    
    repeat = input("\nDo you want to try again Y/N?  \n>>> ")
        
        
while repeat.lower() == 'n': 
    print('\nthank you')
    break

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You have two problems. First, your print statements that print the results need to be un-indented by one step, so they are not PART of loop, but execute AFTER the loop. Second, you need to initialize product = 1 after the if choice == 2:. As a side note, you don’t need that final while loop. After you have exited the loop, just print(‘Thanks’) and leave it at that.

So the end of the code is:

    if choice == 1:
        while num > 0 :
            result += num
            num -= 1
        print(' ',result)
            
    if choice == 2:
        product = 1
        while i<num:
            i=i+1
            product=product*i
        print(' ', product)
    
    repeat = input("\nDo you want to try again Y/N?  \n>>> ")
                
print('thank you\n')

I presume you’ll learn pretty quickly how to do those with a for loop instead of a while loop.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading