Get a list of numbers as input from the user
In Python 3.x, use this.
a = [int(x) for x in input().split()]
Example
>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>>
How to input numbers of a list individually from user input?
Try this.
I am using f-strings
here. This only works in Python 3.6+.
n = int(input('How many numbers do you want to add to the list? '))
lst = []
for i in range(1,n+1):
temp = int(input(f'Number {i}: '))
lst.append(temp)
print(f'List:\n{lst}')
Output:
How many numbers do you want to add to the list? 5
Number 1: 67
Number 2: 6
Number 3: 45
Number 4: 9
Number 5: 1
List:
[67, 6, 45, 9, 1]
How to input list of number from users and output the numbers on console in Dart
import 'dart:io';
void main(List<String> arguments) {
var arr = <int>[];
var i = 0;
while (i < 10) {
stdout.write('Enter #${i+1}: ');
var x = stdin.readLineSync();
if (x == null) continue;
var n = int.tryParse(x);
if (n == null) continue;
arr.add(n);
i++;
}
print('\nMy numbers: $arr');
}
Output:
Enter #1: 2
Enter #2: 43
Enter #3: er
Enter #3: 45
Enter #4: 7
Enter #5: 5
Enter #6: -3
Enter #7: ñ
Enter #7: 5
Enter #8: 6
Enter #9: 87
Enter #10: 2
My numbers: [2, 43, 45, 7, 5, -3, 5, 6, 87, 2]
Get user input as a list of integers
Try something like:
user_input: list = list(map(int, input().split()))
We firstly grab an input()
, eg. "1 2 3 4 5", then we split()
it and we have ["1", "2", "3", "4", "5"]
, finally we map them into integers and convert to a list :)
number/numbers to list by using input()
In your function, you can directly convert num
into a list by calling split(',')
, which will split on a comma - in the case a comma doesn't exist, you just get a single-element list. For example:
In [1]: num = '1'
In [2]: num.split(',')
Out[2]: ['1']
In [3]: num = '1,2,3,4'
In [4]: num.split(',')
Out[4]: ['1', '2', '3', '4']
You can then use your function as you have it:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
number = map(int,num)
return number
x = inputnumber()
print x
However you can take it a step further if you want - map
here can be replaced by a list comprehension, and you can also get rid of the intermediate variable number
and return the result of the comprehension (same would work for map
as well, if you want to keep that):
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num]
x = inputnumber()
print x
If you want to handle other types of input without error, you can use a try/except
block (and handle the ValueError
exception), or use one of the fun methods on strings to check if the number is a digit:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num if n.isdigit()]
x = inputnumber()
print x
This shows some of the power of a list comprehension - here we say 'cast this value as an integer, but only if it is a digit (that is the if n.isdigit()
part).
And as you may have guessed, you can collapse it even more by getting rid of the function entirely and just making it a one-liner (this is an awesome/tricky feature of Python - condensing to one-liners is surprisingly easy, but can lead to less readable code in some case, so I vote for your approach above :) ):
print [int(n) for n in raw_input('Number(s): ').split(',') if n.isdigit()]
Related Topics
How to Parse Xml and Get Instances of a Particular Node Attribute
Remap Values in Pandas Column With a Dict, Preserve Nans
How to Select Rows from a Dataframe Based on Column Values
How to Sort a Dictionary by Value
Why Is Using 'Eval' a Bad Practice
How to Iterate Over Rows in a Dataframe in Pandas
Pandas Conditional Creation of a Series/Dataframe Column
Does Python Have a Ternary Conditional Operator
Unboundlocalerror on Local Variable When Reassigned After First Use
How to Get Keyboard Input in Pygame
Tkinter Assign Button Command in a For Loop With Lambda
What Is Wrong With Using a Bare 'Except'
Why Do I Get Attributeerror: 'Nonetype' Object Has No Attribute 'Something'
Get Difference Between Two Lists
Selenium - Wait Until Element Is Present, Visible and Interactable