Python Forum
Calculator exceptions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calculator exceptions
#1
Hello everyone,
Could anyone tell me how I could create a exception (error handling) to deal with users who put letters or "+"/"-" into the calculator. Along with any other exceptions important to that calculator. Also if there is any code I need to fix could you help me out? Still pretty new to this

def addition(number1,number2):
    return number1+number2

def subtraction(number1,number2):
    return number1-number2

def multiplication(number1,number2):
    return number1*number2

def division(number1,number2):
    return number1/number2

def IsInRange(LowerRange,HigherRange,Number):
    return LowerRange<Number<HigherRange


def main ():
   
                            
    print ("Welcome to my calculator")
    ans = input ('Would you like to use the following calculator (Yes/No): ').format ()


    LowerRange = int(input("Enter the lower range:"))
    HigherRange = int(input("Enter the higher range:"))
    number1 = int(input("Enter the first number:"))
    number2 = int(input("Enter the second number:"))

    if IsInRange(LowerRange,HigherRange,number1) and IsInRange(LowerRange,HigherRange,number2):
       

        print('{} + {} = '.format(number1, number2))
        print(number1 + number2)

        print('{} - {} = '.format(number1, number2))
        print(number1 - number2)

        print('{} * {} = '.format(number1, number2))
        print(number1 * number2)

        if number2 == 0 :
            print ("Cannot divide by zero please input a different number")
        else:
            print('{} / {} = '.format(number1, number2))
            print(number1 / number2)
        main()
    else:
        print ("Thanks for using my calculator!")
main()

    # Loop to restart calculator
reset= input("Continue Looping Y/N:  ").format()
if reset != "Y":
        main()

else:
            print ("Thanks for using my calculator!")
            exit ()
main()
Yoriz write Jun-29-2021, 06:04 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
There is a forum tutorial on Validating User Input
Reply
#3
Hi @HereweareSwole ,
Your code looks quite neatly formatted. I hope the hint of Yoriz helps you. Please show us the result of what you made of it. You are asking the user 4 times for an integer, perhaps you can define a function "input_int(promp)". This function would show the prompt string (e.g. "Enter the first number:") and repeat this until a valid integer is entered. The function should then return that integer. In your "main()" function you can then use "input_int()" instead of "input()".

About your code: you make use of the .format() method of string, but not always useful. For example:
ans = input ('Would you like to use the following calculator (Yes/No): ').format ()
It has no function here. Sufficient is:
ans = input ('Would you like to use the following calculator (Yes/No): ')
On other places you use it correctly:
        print('{} + {} = '.format(number1, number2))
        print(number1 + number2)
There is nothing wrong with that but nowadays most programmers use F-string. This goes like this:
        print(f'{number1} + {number2} = {number1 + number2}')
Which is much easyer. You can read about it in f-string, string format, and string expression.

Then about the structure. Your main() starts asking 'Would you like to use the following calculator (Yes/No): '. But you do nothing with the response. I would leave that out. They started your program so they want to use it.

At the end you start using your functions and try to repeat the main function, but you are using "if" where you intend to use "while".
main()
     # Loop to restart calculator
reset= input("Continue Looping Y/N:  ").format()
if reset != "Y":
        main()
 
else:
            print ("Thanks for using my calculator!")
            exit ()
main()
I think you meant to do something like this:
ans = "y"
# Loop to start calculator
while ans.lower() = "y":
    main()
    ans= input("Start again? Y/N:  ")
 
print ("Thanks for using my calculator!")
Please tell us if this helps you.
Reply
#4
hey thank you so much for all the help so far. So i really deep cleansed my code and figured out how to fic the ValueError but I still can'y manage to fic my ZeroDivisionError.

def IsInRange(LowerRange,HigherRange,Number):
        return LowerRange<Number<HigherRange

def calculator():
    try:

        LowerRange = float(input("Enter your lower range:"))

        HigherRange = float(input("Enter your higher range:"))

        number1 = float(input("Please enter your first number: "))

        number2 = float(input("Please enter your second number: "))
    except ValueError as ERROR:
        print("Invalid number input\n")
        print(ERROR)
        print("\nTry Again")
        return

    if IsInRange(LowerRange,HigherRange,number1) and IsInRange(LowerRange,HigherRange,number2):
       

        print(f'{number1} + {number2} = {number1 + number2}')
        

        print(f'{number1} - {number2} = {number1 - number2}')
    

        print(f'{number1} * {number2} = {number1 * number2}')


        try: 
            print(f'{number1} / {number2} = {number1 / number2}')
        
        except ZeroDivisionError as ERROR:
            print("The input values are outside the input ranges. Please check numbers and try again. Thanks for using our calculator!")
            print(ERROR)
            print("\nTry again")
            return
    else:
        ans = "The input values are outside the input ranges. Please check numbers and try again. Thanks for using our calculator!"
        print (f"Ans: {ans}")
while True:

    ans1 = input("Start again? Y/N:  ")
    calculator()
Yoriz write Jul-01-2021, 05:08 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#5
Well nice. It works. But it is strange the program starts with asking "Start again? Y/N". And even worse: whatever I answer, the loop continues. So I am already calculating some hours but I can't quit your program. Wink
Can you help me out and do something so the program stops when I answer "N"?
Reply
#6
Hint: there are two ways to exit a while loop. The classic way according to the rules of Stuctured Programming is to use a condition:
answer = "y"
while answer == "y" :
    # do your thing
   answer = input("Start again? y/n ")
Or else you can break from the loop.
while True:
    # do your thing
    answer = input("Start again? y/n ")
    if answer == "n":
        break
Let us know how you solved it.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  writing user exceptions ccm1776 1 2,026 Oct-04-2018, 07:36 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020