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
#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


Messages In This Thread
Help with try, except, else finally - by Pytho13 - Mar-21-2021, 04:17 PM
RE: Help with try, except, else finally - by jefsummers - Mar-21-2021, 07:17 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Am I a retard - else and finally blocks in a try statement RubenF85 6 2,748 Jan-12-2021, 05:56 PM
Last Post: bowlofred
  finally clause Skaperen 6 4,027 Jun-02-2019, 09:02 PM
Last Post: snippsat
  try, except, finally ? microphone_head 3 2,945 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