1

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

6
  • 3
    What does the user type? Commented Mar 1, 2016 at 3:16
  • In Python 3.5.1, I get an error that includes the string that failed, e.g. for the empty string (because I entered nothing): ValueError: invalid literal for int() with base 10: '' Are you not seeing those final quotes with the literal it tried to parse? Commented Mar 1, 2016 at 3:16
  • @zondo integer data that he wishes to add in the array Commented Mar 1, 2016 at 3:17
  • @brainst I mean what is his example that results in that? If he types the right numbers, he shouldn't get an error. I tested it, and it works if the right numbers are typed. Commented Mar 1, 2016 at 3:20
  • @zondo it seems that you're right Commented Mar 1, 2016 at 3:29

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

4 Comments

there's a syntax error :/ print my_array print(my_array) is also giving me a syntax error? What is the actual syntax? I tried searching but didn't get it
Hm, I fixed a couple things since I wrote this in Python 2.x and just realized they deprecated raw_input in Python 3.x, but everything else still works. Does the SyntaxError point at the first parenthesis in print(my_array)? If so, it's most likely an indentation error in the console.
Actually .. There's something strange .. I wrote the program then I run in IDLE then it says syntax error. But If i directly run in IDLE then it doesnt
@brainst: Hmm, I don't know what's the problem. I wrote the script and ran it in the REPL/IDLE and it works flawlessly for me. Let me know if there are any problems remaining.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.