0

tried to use exception handling to force my basic calculator to correct the user if anything other than an integer is given

so I included ;

try:
    number_1 = int(input("Enter first number: "))
    number_2 = int(input("Enter second number: "))

except ValueError :
    print("try something else, an actual number maybe ? like actual figures?   ")

instead i got

Enter first number: djrgkl

try something else, an actual number maybe ? like actual figures.

Traceback (most recent call last): File "C:/Users/Papy/.PyCharmCE2019.2/config/scratches/calc.py", line 52, in print(number_1, "/(divided by)", number_2, "(equals)=", NameError: name 'number_1' is not defined

The Great
  • 7,215
  • 7
  • 40
  • 128
Papy
  • 11
  • 1
  • 1
    `number_1` will not be assigned since `djrgkl` cannot be converted into an integer. Therefore, it is not defined and thus not available to be printed!. – Khalil Al Hooti Aug 21 '19 at 23:45
  • Your `try/except` block is working - you just need to loop back and do the `input()` again. – DaveStSomeWhere Aug 21 '19 at 23:45
  • 1
    Possible duplicate [Functional approach or "look mum no loops!":](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Trenton McKinney Aug 21 '19 at 23:48
  • @DaveStSomeWhere thank you. i ended up using a while true loop and it worked in this case but didnt work when i included it in the division function creation (zero error handling). it exits the code instead of looping back to the place where it asks for input. – Papy Aug 23 '19 at 16:45
  • @DaveStSomeWhere `def divide(num1, num2):` `while True:` `try:` `return num1 / num2` `except ZeroDivisionError:` `print("you tried to divide by zero, try something else ")` `continue` `else:` `break ` – Papy Aug 23 '19 at 16:47
  • @Papy, please update your question with your full code and your issues. Kind of tough to debug from comments. – DaveStSomeWhere Aug 23 '19 at 17:00

1 Answers1

1
from itertools import chain, repeat

num_dict = dict()
for x in range(2):
    number = chain(["Enter a number: "], repeat("Not a number! Try again: "))
    replies = map(input, number)
    num_dict[x] = next(filter(str.isdigit, replies))
    print(num_dict[x])

Output:

Enter a number:  asdf
Not a number! Try again:  asdf
Not a number! Try again:  cccc
Not a number! Try again:  4
4
Enter a number:  adfas
Not a number! Try again:  g4
Not a number! Try again:  asdf
Not a number! Try again:  asg
Not a number! Try again:  55678
55678
print(num_dict)
{0: '4', 1: '55678'}
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158