Python percentage calculator does not call exit()

Advertisements

I am trying to write a percentage calculator that asks for the number of subjects, marks in the specified number of subjects and computes the percentage. It works well, but does not exit on calling exit() after the user presses "n":

value = input("Do you want to calculate again (y/n):")
if value.lower == "y":
   percentage()  
elif value.lower == "n":       
   print("ok, sayonara") 
   exit() 

The complete code is:

def percentage():           
    numbers = [] 
    x = int(input('How many subjects would you like to find the percentage for:')) 
    for i in range(x):
        n = int(input('subject ' + str(i+1) + ': '))
        numbers.append(n)
    final = sum(numbers) / len(numbers)
    print("The percentage is",final,"%")
while True:
    try:
        percentage()
        value = input("Do you want to calculate again (y/n):")
        if value.lower == "y":
           percentage()  
        elif value.lower == "n":       
           print("ok, sayonara") 
           exit() 
    except:
       print("\nOops! Error.  Try again...\n")

here’s what happens:

>Solution :

There are two bugs in your code:

if value.lower == "y":

Here you are comparing the function object value.lower with the string "y", they will always be different. You probably meant:

if value.lower() == "y":

And the same for == "n".

Fixing this does not fix the whole code because except: catches all interrupts including the exit() interrupt, so you need need to except ValueError: instead to allow the exit() interrupt to finish your program.

Here is the fixed code:

def percentage():           
    numbers = [] 
    x = int(input('How many subjects would you like to find the percentage for:')) 
    for i in range(x):
        n = int(input('subject ' + str(i+1) + ': '))
        numbers.append(n)
    final = sum(numbers) / len(numbers)
    print("The percentage is",final,"%")
    
while True:
    try:
        percentage()
        value = input("Do you want to calculate again (y/n):")
        if value.lower() == "y":
           percentage()  
        elif value.lower() == "n":       
           print("ok, sayonara") 
           exit() 
    except ValueError:
       print("\nOops! Error.  Try again...\n")

Leave a ReplyCancel reply