0
a = False
while a == False:
    quant = int(input("Input the size:\n"))
    if type(quant) == int:
        a = True
    else:
        print('Please use numbers:\n')
        a = False

I'm trying to make it so that the user can't input characters, but if they do, it prints out the second message. However, when I try to input characters, this message appears:

Traceback (most recent call last):
  File "C:/Users/user/Desktop/pythonproject1/Actual Projects/password 
generator/Password_generator.py", line 34, in <module>
    quant = int(input("Input the:\n"))
ValueError: invalid literal for int() with base 10: 'thisiswhatIwrote'

It works fine when inputing integers. I have tried isinstance() and is_integer(), but couldn't get them to work, so just tried to make it simple.

David Buck
  • 3,752
  • 35
  • 31
  • 35
  • Does this answer your question? [ValueError: invalid literal for int() with base 10: 'stop'](https://stackoverflow.com/questions/16742432/valueerror-invalid-literal-for-int-with-base-10-stop) – David Buck Mar 16 '20 at 19:24
  • Kind of does. Just now I remembered about the int(input() thingy. – Luiz Eduardo Mar 16 '20 at 19:38

1 Answers1

5

There are a number of ways you can tackle this issue. Firstly your error comes because you are trying to convert the string to an int. when the string has chars those cannot be converted to an int so you get a ValueError. You could utilise this behaviour to validate the input

while True:
    try:
        quant = int(input("Input the size:\n"))
        break
    except ValueError as ve:
        print('Please use numbers:\n')

So try to convert to an int, if it works break the loop, if you get a value error tell them to use numbers.

Alternativly you can capture the input as a string then use the strings method isnumeric to see if its a number. If it is then convert it to a number and break the loop, else tell them to use a number.

while True:
    quant = input("Input the size: ")
    if quant.isnumeric():
        quant = int(quant)
        break
    else:
        print("Please use numbers")
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42