This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 5 years ago.
I am trying to create a piece of code that allows me to ask the user to enter 5 numbers at once that will be stored into a list. For instance the code would would be ran and something like this would appear in the shell
Please enter five numbers separated by a single space only:
To which the user could reply like this
1 2 3 4 5
And then the numbers 1 2 3 4 5 would be stored into a list as integer values that could be called on later in the program.
Your best way of doing this, is probably going to be a list comprehension.
user_input = raw_input("Please enter five numbers separated by a single space only: ")
input_numbers = [int(i) for i in user_input.split(' ') if i.isdigit()]
This will split the user's input at the spaces, and create an integer list.
You can use something like this:
my_list = input("Please enter five numbers separated by a single space only")
my_list = my_list.split(' ')
This could be achieved very easily by using the raw_input() function and then convert them to a list of string using split() and map()
num = map(int,raw_input("enter five numbers separated by a single space only" ).split())
[1, 2, 3, 4, 5]
You'll need to use regular expressions as the user may also enter non-integer values as well:
nums = [int(a) for a in re.findall(r'\d+', raw_input('Enter five integers: '))]
nums = nums if len(nums) <= 5 else nums[:5] # cut off the numbers to hold five
Here is a subtle way to take user input into a list:
l=list()
while len(l) < 5: # any range
test=input()
i=int(test)
l.append(i)
print(l)
It should be easy enough to understand. Any range range can be applied to the while loop, and simply request a number, one at a time.
Related
How to accept input into array and sort it?
Good day, I am new to programming and new to Python Language.
I would like to try to code the user is asked to input 10 numbers and then display it in ascending order. I am not sure on how to make this work. Here is what I have:
print("Input 10 numbers:")
num = list(map(int, input().split()))
num.sort()
print("Element value in ascending order:")
print(*num)
But this code is list. I need to accept the input and then make it as an array and then sort it into ascending. Thanks in advance.
You can do so like this:
nums = input()
# say user inputs 1 2 3 4 ....10
nums = nums.split() # converts it to a list of strings
nums = [int(num) for num in nums] # convert them to ints
print(sorted(nums))
You can also test if the strings can be converted into ints or not to make you code more robust.
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 months ago.
I want to know how to take an input from the user as a list. For instance, there will be a message wanting input from the user and the user will input [1,2,3]. Then, the program will create a new variable with a type list and assign the input to that variable. (I've tried to use the enter code function but I couldn't figure it out since It's my first time asking a question so, that's why I explained my code instead of writing it)
You can use list comprehension for this. It provides a concise way to create lists. The code in the square brackets asks the user for input, splits the input into a text based list, and then converts the values in the list to integers. Unfortunately, you can't create variables unless they are explicitly written in the code.
Code
x = [int(val) for val in input("Enter your numbers: ").split()]
print(x)
Input:
Enter your numbers: 1 2 3 4 5
Output:
[1, 2, 3, 4, 5]
Additional link:
https://www.geeksforgeeks.org/python-get-a-list-as-input-from-user/
do you mean something:
inp = input("Type something")
l = [inp.split(" ")]
As far as I have understood your question, you want to make a list from the set of inputs of numbers having comma or space.
a = list(input("Enter your number: "))
b = [int(elements) for elements in a if elements not in (" ",",",'[',']')]
# Remove int if you are doing for strings
print(b)
Output:
Enter your number: [1,2,3]
[1 ,2 ,3]
This question already has answers here:
for or while loop to do something n times [duplicate]
(4 answers)
Closed 3 years ago.
I am relatively new to programming and especially to Python. I am asked to create a for loop which prints 10 numbers given by the user. I know how to take input and how to create a for loop. What bothers me, is the fact that with my program I rely on the user to insert 10 numbers. How can I make the program control how many numbers are inserted? Here is what I tried:
x = input('Enter 10 numbers: ')
for i in x:
print(i)
You need to
ask 10 times : make a loop of size 10
ask user input : use the input function
for i in range(10):
choice = input(f'Please enter the {i+1}th value :')
If you want to keep them after, use a list
choices = []
for i in range(10):
choices.append(input(f'Please enter the {i + 1}th value :'))
# Or with list comprehension
choices = [input(f'Please enter the {i + 1}th value :') for i in range(10)]
What if input is row that contains word (numbers) separated by spaces? I offer you to check if there are 10 words and that they are numbers for sure.
import re
def isnumber(text):
# returns if text is number ()
return re.match(re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"), text)
your_text = input() #your input
splitted_text = your_text.split(' ') #text splitted into items
# raising exception if there are not 10 numbers:
if len(splitted_text) != 10:
raise ValueError('you inputted {0} numbers; 10 is expected'.format(len(splitted_text)))
# raising exception if there are any words that are not numbers
for word in splitted_text:
if not(isnumber(word)):
raise ValueError(word + 'is not a number')
# finally, printing all the numbers
for word in splitted_text:
print(word)
I borrowed number checking from this answer
This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 8 years ago.
Im writing a program that reads in a list, then displays the length of the list, and displays the list with one number displayed per line. This is what I have so far:
from List import *
def main():
numbers = eval(input("Give me an list of integers: "))
strings = ArrayToList(numbers)
length = len(strings)
print("The length of the list: ", length)
This is what Im expecting the result to be like:
Enter a list of integers: [3, [5, [1, [6, [7, None]]]]]
The length of the list:
5
The list:
3
5
1
6
7
Can anybody help me out? Im getting the length of the list to show as 2 instead of 5 which is what it should be.
Without seeing the implementation of ArrayToList, this is just a guess.
That said, I imagine your problem is that you aren't entering a list of integers, you're entering a list composed of an integer and another list... which itself is a list containing an integer and another list, all the way down. Hence len(strings) is 2, because len is not recursive.
You're could try inputting the list like [1, 2, 3, 4, 5] instead.
Alternatively, you could build your list in a loop, asking for user input for each character until an "end of input" event (of your choosing) is hit. This would let you avoid eval entirely, which is often a good idea.
def main():
numbers = input("Give me a list of space-separated integers: ").split()
print("length of the list:", len(numbers))
print("The list:", *numbers, sep='\n')
Output
In [14]: main()
Give me a list of space-separated integers: 3 5 1 6 7
length of the list: 5
The list:
3
5
1
6
7
I am assuming you are in Python3, because in Python2 you would not need the eval around input.
numbers = eval(input("Give me an list of integers: "))
length = len(numbers)
print("The length of the list: %d" % length)
print("The list: ")
for i in numbers:
print(i)
Here, you would have to enter the list in standard Python fashion though:
[1,2,3,4,5]
The equivalent in Python2 would just be a one-line change.
numbers = input("Give me an list of integers: ")
In Python 2 I would do it like this:
def main():
numbers = []
integers = []
numbers.append(raw_input("Give me an list of integers: "))
for integer in numbers[0]:
print integer
if integer.isdigit():
integers.append(integer)
print ("The length of the list: ", len(integers))
main()
i know i can use the input function in conjunction with the eval function to input a list of numbers:
numbers = eval(input("enter a list of numbers enclosed in brackets: "))
Also, given a list named items, i can get the list of all the elements of items, except the first one, with
the expression:
items[1:]
im just not sure how to go about getting the program to do what i want it to do
If you have a list and you want to know if the first value appears again later in the list, you can use:
items[0] in items[1:]
That will return True or False depending on whether the first element in items appears again later in items.
Don't use eval, ast.literal_eval is safer
import ast
numbers = ast.literal_eval(raw_input("enter a list of numbers enclosed in brackets: "))
An easier solution will be
x = l[0]
l[0] = None
print x in l
l[0] = x
The advantage is that you don't need to recreate the list
There are two parts to your problem:
get a list of numbers from the user
check if the first number is repeated in this list
There are several ways to get a list of numbers from a user. Since you seem to be new to python, I will show you the easiest way to program this:
n = raw_input("How many numbers in your list?: ")
n = int(n) # assuming the user typed in a valid integer
numbers = []
for i in range(n):
num = raw_input("enter a number: ")
num = int(num)
numbers.append(num)
# now you have a list of numbers that the user inputted. Step 1 is complete
# on to step 2
first_num = numbers[0]
for n in numbers[1:]:
if n == first_num:
print "found duplicate of the first number"
Now, there are more elegant ways to accomplish step 1. For example, you could use a list comprehension:
numbers = [int(n) for n in raw_input("Enter a bunch of space-separated numbers: ").split()]
Further, step 2 can be simplified as follows:
if numbers[0] in numbers[1:]:
print "found duplicates of the first number"
Hope this helps