brainst
brainst

Reputation: 291

How to input integer values in a list(python 3.x)?

I am trying to use list as an array and I want to enter integer values in the list so that I can perform some arithmetic on it.

m=int(input())

I always used this for getting some integer input from the user.

//creating an array

myArray=[]
inp=int(input("Please enter the length of array you wish to create"))
for m in range(inp):
    myArray.append(int(input()))
print(myArray)

But this isn't working. Why?

Error :invalid literal for int() with base 10

Upvotes: 1

Views: 3696

Answers (2)

Eddo Hintoso
Eddo Hintoso

Reputation: 1442

REPL Demo

Okay, since the input would be parsed as a string and int can only coerce strings that are just numbers into integers... you are in big trouble for a bad input as it would stop your program immediately.

I would suggest using a while loop and try-except exception statements for error handling.

NOTE for Python 2.x: Use raw_input since input would result in a NameError: name <input_string> is not defined if you pass characters without string quotations.

>>> my_array = []  # camelCase is not the convention in Python
>>> 
>>> array_length = None
>>> while array_length is None:
...     try:
...         array_length = int(input("Please enter the length of array you wish to create: "))
...     except ValueError:
...         print("Invalid input - please enter a finite number for the array length.")
... 
Please enter the length of array you wish to create: 4
>>>
>>> print(array_length)
4
>>> while len(my_array) < array_length:
...     try:
...         my_array.append(int(input()))
...     except ValueError:
...         print("Invalid input - please enter a number!")
...
1
abc
Invalid input - please enter a number!
2
3
4
>>>
>>> print(my_array)
[1, 2, 3, 4]

Running as Script

# -*- coding: utf-8 -*-

INVALID_NUMERIC_INPUT_MSG = "Invalid input - please enter a finite number with no spaces!"
KEYBOARD_INTERRUPTION_MSG = "Keyboard interruption: program exited."

def main():
    my_array = []

    print()

    array_length = None  
    while array_length is None:  # accept input until valid
        try:
            array_length = int(input("Please enter the length of array you wish to create: "))
        except ValueError:
            print(INVALID_NUMERIC_INPUT_MSG)
        except KeyboardInterrupt:
            print("\n" + KEYBOARD_INTERRUPTION_MSG)
            quit()

    print("Your array length is {}.".format(array_length))
    print()

    while len(my_array) < array_length:
        try:
            my_array.append(int(input()))
        except ValueError:
            print(INVALID_NUMERIC_INPUT_MSG)
        except KeyboardInterrupt:
            print("\n" + KEYBOARD_INTERRUPTION_MSG)
            quit()

    assert len(my_array) == array_length  # check for program correctness

    print()
    print("Your array is: {}".format(my_array))
    print()

if __name__ == '__main__':
    main()

Running in my console:

$ python3 input-program.py

Please enter the length of array you wish to create: 4
Your array length is 4.

1
2
3
4

Your array is [1, 2, 3, 4]

Upvotes: 2

knowingpark
knowingpark

Reputation: 749

The str to int coercion can be done by just trying it out, to see if it input was a number.

Here we make a zeroed array and a consecutively numbered array (a range)

In python you call an array a list

array = [0]
try:
    array = array * int(raw_input('How long? ->'))
    print array
except:
    print "try using a number"

OR

try:
    array = range(int(raw_input('How long? ->')))
    print array
except:
    print "try using a number"

PS this is Python v2 code not v3

Upvotes: 0

Related Questions