Home > database >  How would I type a string in an int input without getting an Error in Python?
How would I type a string in an int input without getting an Error in Python?

Time:01-17

I was wondering how I would allow my input to allow both strings and int. For example, if I wanted to type 'string' I wouldn't get an error. But when I type a string into it I get this error: ValueError: invalid literal for int() with base 10: 'string' I know I have an int() at the start of the input line but I've tried other things and it still doesn't work. This is the code:

 row = int(input('Which row do you want to change?: '))

CodePudding user response:

You can validate the input rather than arbitrarily converting it to integer.

row = input('Which row do you want to change?: ')
if row.isdigit():
    row = int(row)
else:
    print("That's a string")

CodePudding user response:

while True:
    try:
        age = int(input("Which row do you want to change? "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue
    else:
        break

CodePudding user response:

You may try the following, it can detect all whole numbers. It converts the string input into integer type only if the input is numeric, unlike your case. You can thereby allow both integer and string inputs.

row = input('Which row do you want to change?: ')
if row.isnumeric():
    row = int(row)
  •  Tags:  
  • Related