I am new to Python and want to read keyboard input into an array. The python doc does not describe arrays well. Also I think I have some hiccups with the for loop in Python.
I am giving the C code snippet which I want in python:
C code:
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]);
You want this - enter N and then take N number of elements.I am considering your input case is just like this
5
2 3 6 6 5
have this in this way in python 3.x (for python 2.x use raw_input()
instead if input()
)
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])
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])
raw_input is your helper here. From documentation -
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
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
P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input
does not do any type checking, so you need to be careful...
If the number of elements in the array is not given, you can alternatively make use of list comprehension like:
str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]
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 this doesn't do any error checking and it stores data as a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With