0

Just started learning python and wanted to make a calculator. I currently have some code that tries to turn what the user inputs into an integer, but what I want to do is be able to check if the attempt was successful or not.

Here is the part i'm having trouble with.

import sys

first_number = input('Enter a number: ')

try:
  int(first_number)
except:
  print("Sorry, that's not a number.")
  exit()
Zodiac770
  • 13
  • 1
  • 3
  • You said you're "having trouble", but what is thr trouble with what you've tried (aside from using bare `except:`, which is almost never a good idea)? – Davis Herring May 23 '21 at 02:39
  • If the line works, it will simply continue after the line. If it reaches the except, then it continues after the except clause. – Tim Roberts May 23 '21 at 02:39

3 Answers3

3

You can just do:

try:
    int(first_number)
    print("try successful!")
except ValueError:
    print("Sorry, that's not a number.")
    print("try unsuccessful!")
    exit()
chepner
  • 497,756
  • 71
  • 530
  • 681
CoolCoder
  • 786
  • 7
  • 20
-1

To have this make more sense, make it a function:

def getNumber():
    while True:
        number = input('Enter a number: ')
        if number.isnumeric():
            return int(number)
        print( "Not a number, please try again." )
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
-1

You can set a flag after int that is only set on success:

success=False
nums=iter(['abc','123'])
while not success:
    try:
        x=int(next(nums))
        success=True
    except ValueError as e:
        print(e, 'Try Again!')
        
print(x)

Prints:

invalid literal for int() with base 10: 'abc' Try Again!
123

First time with 'abc' is an error, second time a success.

Since nums first try is an error, that will not set success to True. Second time is not an error, success is set to True and the while loop terminates. You can use the same method with user input. The iterator is just simulating that...

So for your example:

success=False
while not success: 
    try:
        n_string = input('Enter a number: ')
        int(n_string)
        success=True
    except ValueError as e:
        print(f'"{n_string}" is not a number. Try again')

Which is commonly simplified into this common idiom in Python for user input:

while True:
    try:
        n_string = input('Enter a number: ')
        int(n_string)
        break
    except ValueError as e:
        print(f'"{n_string}" is not a number. Try again')
dawg
  • 98,345
  • 23
  • 131
  • 206