0

I have the code below working the way I want it to. How do I add an error if the user does not enter an integer?

userdata = input("Input the number of numbers to be stored :")

userNumz = []          

print("Input " + str(userdata) + " numbers :")  
for index in range(int(userdata)):
    userNumz.append(input(str(index) + " is ")) 

I have tried to use ValueError but can't get it to work . My attempt below:

while True
    try:
        userdata = input("Input the number of numbers to be stored :")
    except ValueError:
        print("The input was not a valid integer.)    
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
kalpx
  • 53
  • 1
  • 2
  • 5

3 Answers3

4

If you cast the input as int then it will throw the error you want:

while True
    try:
        userdata = int(input("Input the number of numbers to be stored :"))
    except ValueError:
        print("The input was not a valid integer.)
damores
  • 2,251
  • 2
  • 18
  • 31
3

Code:

To invoke an error on an invalid conversion try:

userdata = int(userdata)

In Context:

while True
    try:
        userdata = input("Input the number of numbers to be stored :")
        userdata = int(userdata)
    except ValueError:
        print("The input was not a valid integer.)
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
1

User input will be a string, so when you try to convert it to an int you'll get a ValueError if the user gave you a letter or word.

def get_int():
    userdata = input("Enter an int, or 'q' to quit: ")
    if userdata == 'q':
        return None
    try:
        user_num = int(userdata)
        return user_num
    except ValueError:
        print("I need an integer to continue.")
        return(get_int())

user_number = get_int()

This function will loop until the user enters an int or quits with a 'q'. The following lines would deal with the returned number (or the None object if they quit).