0

I'm creating a function that receives a number between 1 and 5 (likert scale), from a question. When the user inputs a wrong INT my loop is ok, the question repeats. But i want the question to repeat if the user inputs a string too. But in that case the program crashes "ValueError: invalid literal for int() with base 10"

def likert(msg):


    while True:
        L = int(input(msg))

        if 1 <= L <= 5 and type(L) == int:
            return L
        elif L < 1 or L > 5:
            print('\033[031mError  [1 to 5] only\033[m')
            continue
U13-Forward
  • 69,221
  • 14
  • 89
  • 114

3 Answers3

1

Instead of trying to abstract the input as int right off the bat, do this instead:

def likert():

    while True:
        L = input()

        if L.isalpha:
            #if input is string
            print('\033[031mError  [1 to 5] only\033[m')
            continue
        elif L.isdigit:
            #if input is int
            if 1 <= L <= 5:
                #if input is within range
                return L
            else:
                #if input is out of range
                print('\033[031mError  [1 to 5] only\033[m')
                continue
JLynchDesigns
  • 157
  • 14
0

You cast L to int before checking its type. So when L is a string, your program tries to cast it to int and it crashes. You should do numerical operations only when you are sure that L is not a string. The solution is either to use try and catch or to handle it with an if statement.

0

int() always returns an integer, so type(L) == int will always be true. If the user types something that isn't a valid integer, int() will signal an error.

Use try/except to handle the error if the user enters something that isn't an integer.

def likert(msg):
    while True:
        try:
            L = int(input(msg))
        except ValueError:
            print('\033[031mError  [1 to 5] only\033[m')
            continue

        if 1 <= L <= 5:
            return L
        else:
            print('\033[031mError  [1 to 5] only\033[m')

You don't need elif, since the condition is just the opposite of the if condition; use else. You also don't need continue, since it's at the end of the loop and it's just going to continue anyway.

Barmar
  • 741,623
  • 53
  • 500
  • 612