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

Time:12-15

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

CodePudding user response:

The program prints you all the numbers because the print statement is in a while loop, so it gets executed with each run of the loop. Just move the print function out of the while.

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)

CodePudding user response:

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.

  • Related