How to enter input into an array + PYTHON?

I am new to Python and want to read keyboard input into an array. The Python document does not describe arrays very well. Also, I think I have some errors with the for loop in Python.

I give the C code snippet that I want in python:

Code C:

int i; printf("Enter how many elements you want: "); scanf("%d", &n); printf("Enter the numbers in the array: "); for (i = 0; i < n; i++) scanf("%d", &arr[i]); 
+12
python
source share
5 answers

raw_input is your helper. From the documentation -

If the invitation argument is present, it is written to standard output without a trailing newline. Then the function reads the line from the input, converts it to a line (stripping the final new line) and returns that. When an EOF is read, an EOFError raises.

So your code will basically look like this.

 num_array = list() num = raw_input("Enter how many elements you want:") print 'Enter numbers in array: ' for i in range(int(num)): n = raw_input("num :") num_array.append(int(n)) print 'ARRAY: ',num_array 

PS: I scored all this free hand. The syntax may be wrong, but the methodology is correct. It should also be noted that raw_input does not check type, so you need to be careful ...

+13
source share

If the number of elements in the array is not specified, you can also use list comprehension, for example:

 str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space arr = [int(num) for num in str_arr] 
+12
source share

You want this - enter N, and then take N the number of elements. I view your input case just like this

 5 2 3 6 6 5 

have it this way in Python 3.x (for Python 2.x use raw_input() instead if input() )

Python 3

 n = int(input()) arr = input() # takes the whole line of n numbers l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5]) 

Python 2

 n = int(raw_input()) arr = raw_input() # takes the whole line of n numbers l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5]) 
+11
source share
 data = [] n = int(raw_input('Enter how many elements you want: ')) for i in range(0, n): x = raw_input('Enter the numbers into the array: ') data.append(x) print(data) 

Now it does not do any error checking and saves the data as a string.

+3
source share
 arr = [] elem = int(raw_input("insert how many elements you want:")) for i in range(0, elem): arr.append(int(raw_input("Enter next no :"))) print arr 
+1
source share

All Articles