Home > Mobile >  Error using try except in a function Python
Error using try except in a function Python

Time:04-20

Code image

def user_input():

a = input('Enter Ozone level here:')

try:
    user_num = float(a)
except:
    print('Invalid')
    user_input()

return user_num

a = user_input() print(a)

When I first input a number, the function worked just fine. However, When I enter a string first and then a number after error handling, there's an error: UnboundLocalError: local variable 'user_num' referenced before assignment.

CodePudding user response:

Try to put variable a outside of the function.

CodePudding user response:

Try this:

a = input('Enter Ozone level here:')
def user_input():
    try:
        user_num = float(a)
    except:
        print('Invalid')
        user_input()

    return user_num
a = user_input() 
print(a)

CodePudding user response:

This should do the trick

def user_input():
    user_num = None
    while True:
        try:
            user_num = float(input('Enter Ozone level here: '))
            break
        except ValueError:
            continue

    return user_num


print(user_input())

CodePudding user response:

Try using a for loop to filter out the non-numerical characters

Input

def filter_numbers(string):
  numbers = "0123456789."
  new_str = string

  for i in range(len(string)):
    if not string[i] in numbers:
      new_str = new_str.replace(string[i], "")
  return new_str

print(filter_numbers("cdsfsdsf1sdf2dfsd3"))

Output

>>> 123

This should handle it without any errors.

CodePudding user response:

This should work as you expected

def user_input(a):
    try: 
        user_num = float(a) 
        return user_num
    except: 
        return ('Invalid')          
a = user_input(input('Enter Ozone level here:') ) 
print(a)
  • Related