Python Forum
Help with try, except, else finally
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with try, except, else finally
#1
Hi everyone,

Nice to meet you all! I'm building a calculator with python and I want to add try except else and finally. I have added the try except and the calculator is working but it doesn't return the error message if user input is not an integer.

Can you please take a look?
#User inputs math type
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
* for multiplication
''')
#User inputs number
number_1 = int(input('Enter your first number: ')) 

number_2 = int(input('Enter your second number: '))

#If user chooses addition
try: 
    if operation == '+':
        print('{} + {} = '.format(number_1, number_2))
        print(number_1 + number_2)
except Exception:
    print: ("You have not input a number")

#if user chooses multiplication
try:    
    if operation == '*':
        print('{} * {} = '.format(number_1, number_2))
        print(number_1 * number_2)
except: 
    print: ("You have not input a number")
snippsat write Mar-21-2021, 04:29 PM:
Added code tag in your post,look at BBCode on how to use.
Reply
#2
The calls to int aren't in a try block, are they?
Pytho13 and supuflounder like this post
Reply
#3
No, they're not.
Should I move them to surround the try block? and take them off where they are now?

Please see below? Shy

#User inputs math type
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
* for multiplication
''')
#User inputs number
try:
number_1 = int(input('Enter your first number: '))
except Exception:
print: ("You have not input a number")

try:
number_2 = int(input('Enter your second number: '))
except Exception:
print: ("You have not input a number")

#If user chooses addition
if operation == '+':
print('{} + {} = '.format(number_1, number_2))
print(number_1 + number_2)


#if user chooses multiplication
if operation == '*':
print('{} * {} = '.format(number_1, number_2))
print(number_1 * number_2)
Reply
#4
If number_1 and number_2 are actually numbers, then you don't need to wrap the operations in try/except. Only the conversion from string to number can fail until you add division to your calculator.

Why are you limiting your calculator to integers? Why not floats. There's no extra code and a lot more capability.

Why do you force the user enter equations in such an awkward way. I would prefer to enter something like "3 + 4" instead of first having to enter the "+" and then the "3" and finally the "4". By the time I'm finished doing that I already forgot my equation.

Why do you have this?
print('{} + {} = '.format(number_1, number_2))
and this?
print('{} * {} = '.format(number_1, number_2))
Aren't they the same except the "+" or "*"? You made the user enter the operator, why don't you use it here?
Reply
#5
Also, if you see a lot of repetitive code (like here), take a step back to see how things can be combined - often in a function, but even easier here. Combining what has been stated here
#User inputs math type
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
* for multiplication
''')
#User inputs number

while True:
    number_str = input('Enter your numbers, separate by comma: ')
    try: 
        numbersstrings = number_str.split(sep=',')
        n1 = float(numbersstrings[0])
        n2 = float(numbersstrings[1])
    except Exception:
        print("You have not followed instructions!")
        continue
    break
     
print(f'{n1} {operation} {n2}')
if operation == '*':
    print(n1*n2)
if operation == "+":
    print(n1+n2)
Now this still is not great - I agree with Dean that you should allow the user to enter the operation at the same time as the numbers, but this illustrates a number of items/learning points -
The while loop that goes back until the user enters properly formatted numbers
The use of break and continue
The use of f strings rather than .format
Minimizing repetitious code
Reply
#6
Use python tags for code.

Yes, that code looks better.

You are using Polish notation, developed by the Polish mathematician Jan Łukasiewicz. Most calculators of the past used Reverse Polish notation (RPN), so you would type in the two values and then provide the operator. Note that PN and RPN are both parenthesis-free. So instead of prompting for the operator, and then the two operands, you could do like old mechanical calculators did: ask for the values, and then the operator. However, you could also use a single line of input, e.g.


1 2 +
but, even better
1 2 + 3 * 4 /
This involves having a stack; when you encounter an integer, you push it onto the stack, when you encounter an operator, you pop off the top two stack elements, do the computation, and push them back on. The above expression computes
(1 + 2)*3 / 4
whereas
1 2 + 3 * 3 1 + /
computes
(1 + 2) * 3 / (3 + 1)
and works like this
1 2 + 3 * 3 1 + /
 ^
 |
 you are here
stack:
1

1 2 + 3 * 3 1 + /
   ^
stack:
1 2

1 2 + 3 * 3 1 + /
     ^
stack:
3
1 2 + 3 * 3 1 + /
       ^
stack:
3 3

1 2 + 3 * 3 1 + /
         ^
stack:
9
1 2 + 3 * 3 1 + /
           ^
stack:
9 3

1 2 + 3 * 3 1 + /
             ^
stack:
9 3 1

1 2 + 3 * 3 1 + /
               ^
Stack:
9 4

1 2 + 3 * 3 1 + /
                 ^
Stack:
2
Now you have invented the HP calculator. However, there are a couple very simple algorithms for converting infix (with parentheses or not) using standard operator hierarchy, but I don't want to go into that until you have chosen to implement RPN or not.
Reply
#7
(Mar-21-2021, 07:17 PM)jefsummers Wrote: Also, if you see a lot of repetitive code (like here), take a step back to see how things can be combined - often in a function, but even easier here. Combining what has been stated here
#User inputs math type
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
* for multiplication
''')
#User inputs number

while True:
    number_str = input('Enter your numbers, separate by comma: ')
    try: 
        numbersstrings = number_str.split(sep=',')
        n1 = float(numbersstrings[0])
        n2 = float(numbersstrings[1])
    except Exception:
        print("You have not followed instructions!")
        continue
    break
     
print(f'{n1} {operation} {n2}')
if operation == '*':
    print(n1*n2)
if operation == "+":
    print(n1+n2)
Now this still is not great - I agree with Dean that you should allow the user to enter the operation at the same time as the numbers, but this illustrates a number of items/learning points -
The while loop that goes back until the user enters properly formatted numbers
The use of break and continue
The use of f strings rather than .format
Minimizing repetitious code

Hi, thanks so much for this.
that's the first thing I was trying to do, the while loop that loops until the user enters the numbers correctly
the use of f strings, I'm not too sure about but I'm going to go back and look at strings instead of .format

Honestly, thank you, this has been extremely helpful.
Reply
#8
(Mar-22-2021, 09:52 AM)supuflounder Wrote: Use python tags for code.

Yes, that code looks better.

You are using Polish notation, developed by the Polish mathematician Jan Łukasiewicz. Most calculators of the past used Reverse Polish notation (RPN), so you would type in the two values and then provide the operator. Note that PN and RPN are both parenthesis-free. So instead of prompting for the operator, and then the two operands, you could do like old mechanical calculators did: ask for the values, and then the operator. However, you could also use a single line of input, e.g.


1 2 +
but, even better
1 2 + 3 * 4 /
This involves having a stack; when you encounter an integer, you push it onto the stack, when you encounter an operator, you pop off the top two stack elements, do the computation, and push them back on. The above expression computes
(1 + 2)*3 / 4
whereas
1 2 + 3 * 3 1 + /
computes
(1 + 2) * 3 / (3 + 1)
and works like this
1 2 + 3 * 3 1 + /
 ^
 |
 you are here
stack:
1

1 2 + 3 * 3 1 + /
   ^
stack:
1 2

1 2 + 3 * 3 1 + /
     ^
stack:
3
1 2 + 3 * 3 1 + /
       ^
stack:
3 3

1 2 + 3 * 3 1 + /
         ^
stack:
9
1 2 + 3 * 3 1 + /
           ^
stack:
9 3

1 2 + 3 * 3 1 + /
             ^
stack:
9 3 1

1 2 + 3 * 3 1 + /
               ^
Stack:
9 4

1 2 + 3 * 3 1 + /
                 ^
Stack:
2
Now you have invented the HP calculator. However, there are a couple very simple algorithms for converting infix (with parentheses or not) using standard operator hierarchy, but I don't want to go into that until you have chosen to implement RPN or not.

Hi Tim,

Thanks so much. I am going to stick with the type of notation I have for now. Only reason is, I'm only beginning to write code and just trying to get my head around the most basic elements such as strings etc.

Hopefully someday, I will be able to use your stack method.
Thanks for the help.
Reply
#9
Actually, I have no idea who "Tim" is; that description appeared and I can't delete it.

I am a programmer named "flounder". I am also known as "Joe", "Dr. Joe" to my third-grade tutorees, and that "%$&*! smartass" on Quora.
Reply
#10
The line under your name reflects the number of posts. Monty Python references
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Am I a retard - else and finally blocks in a try statement RubenF85 6 2,610 Jan-12-2021, 05:56 PM
Last Post: bowlofred
  finally clause Skaperen 6 3,888 Jun-02-2019, 09:02 PM
Last Post: snippsat
  try, except, finally ? microphone_head 3 2,861 Apr-28-2019, 09:36 PM
Last Post: microphone_head

Forum Jump:

User Panel Messages

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