This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
Maybe this is a very basic question but i am a beginner in python and couldnt find any solution. i was writing a python script and got stuck because i cant use python lists effective. i want user to input (number or numbers) and store them in a python list as integers. for example user can input single number 1 or multiple numbers seperated by comma 1,2,3 and i want to save them to a list in integers.
i tried this ;
def inputnumber():
number =[]
num = input();
number.append(num)
number = map(int,number)
return (number)
def main():
x = inputnumber()
print x
for a single number there is no problem but if the the input is like 1,2,3 it gives an error:
Traceback (most recent call last):
File "test.py", line 26, in <module>
main()
File "test.py", line 21, in main
x = inputnumber()
File "test.py", line 16, in inputnumber
number = map(int,number)
TypeError: int() argument must be a string or a number, not 'tuple'
Also i have to take into account that user may input characters instead of numbers too. i have to filter this. if the user input a word a single char. i know that i must use try: except. but couldn't handle. i searched the stackoverflow and the internet but in the examples that i found the input wanted from user was like;
>>>[1,2,3]
i found something this Mark Byers's answer in stackoverflow but couldn't make it work
i use python 2.5 in windows.
Sorry for my English. Thank you so much for your helps.
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()]
input is not the way to go here - it evaluates the input as python code. Use raw_input instead, which returns a string. So what you want is this:
def inputnumber():
num = raw_input()
for i, j in enumerate(num):
if j not in ', ':
try:
int(num[i])
except ValueError:
#error handling goes here
return num
def main():
x = inputnumber()
print x
I guess all it is is a long-winded version of RocketDonkey's answer.
Related
I don't understand why I'm getting a Value Error. I specifically exclude the "*" character.....yet it still gets included and causes an error. I understand I have to figure out how to reverse the output too but I'll worry about that later.
Write a program that reads a list of integers, one per line, until an
"*" is read, then outputs those integers in reverse. For simplicity in coding output, follow each integer, including the last one, by a
comma.
Note: Use a while loop to output the integers. DO NOT use reverse() or
reversed().
Ex: If the input is:
2
4
6
8
10
*
the output is:
10,8,6,4,2,
my code:
''' Type your code here. '''
while True:
try:
if input().strip() != "*":
num = input().strip()
lst = []
lst.append(num)
print("{},".format(int(num),end=""))
else:
break
except EOFError:
break
Enter program input (optional)
2
4
6
8
10
*
Program errors displayed here
Traceback (most recent call last):
File "main.py", line 8, in <module>
print("{},".format(int(num),end=""))
ValueError: invalid literal for int() with base 10: '*'
Program output displayed here
4,
8,
It's because you're using input 2 times:
First input read 10 and it passes the if.
Second input read "*" inside the "action" section of your code and fails.
Also:
You're resetting the list on every loop. The initialization should be outside of the loop.
Using a more pythonic way to check if the "*" is in the data should avoid any further issues, for example, using "**" or having an incorrect input "1*".
An updated version of the code will be:
''' Type your code here. '''
lst = []
while True:
try:
data = input().strip()
if "*" not in data:
lst.append(num)
print("{},".format(int(num),end=""))
else:
break
except EOFError:
break
Use append to add numbers to the list lst, and pop to remove them from the end of the list. Use f-strings or formatted string literals to print the list elements.
num = input().strip()
lst = []
while num != '*':
num = int(num)
lst.append(num)
num = input().strip()
while lst:
num = lst.pop()
print(f"{num},", end='')
print('')
Comments on your code:
while True:
try: # No need for the try block.
if input().strip() != "*": # This input gets lost: not assigned to any variable.
num = input().strip() # This input is not tested whether it is '*'.
lst = [] # This list gets assigned anew ands becomes empty with every iteration.
lst.append(num)
print("{},".format(int(num),end="")) # Use f-strings instead (easier).
else:
break
except EOFError:
break
I am coding a simple program to add all positive integers not greater than a given integer n. My code:
print("Enter an integer:")
n=input()
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
#print("1+2+3+...+"+str(n)+"="+str(add(n)))
print(add(100))
The function works.
Why does the line in the one line comment not work, if I remove the hash tag? It should - there is a concatenation of four strings. Thank you.
EDIT: the whole output:
Enter an integer:
12
Traceback (most recent call last):
File "<string>", line 10, in <module>
File "<string>", line 6, in add
TypeError: can only concatenate str (not "int") to str
>
input() returns a string. You are passing n=input() which is a string so it is not working as expected.
change it to n=int(input())
Also sum is a reserved keyword and it will be best to change that to a different name
input returns a string, so add(n) will look something like add("1234"). Then, range(k+1) inside the function will be range("1234" + 1), but "1234" + 1 is an error since it's not possible to add a string and a number.
The problem exists in your input, it's current data type is str, and must be converted into int.
Also, it's best if you use .format() when printing strings.
print("Enter an integer:")
n = int(input())
def add(k):
sum=0
for i in range(k+1):
sum=sum+i
return sum
print("1 + 2 + 3 + ... + {} = {}".format(n, add(n)))
for my task, which I think I have already right, but on Snakify it shows me this error statement: Traceback (most recent call last): ValueError: invalid literal for int() with base 10: '1 2 3 4 5'
On google colab this error doesn't show up, on snakify it does, but I need this error to go so I can check my solutions. Any suggestions?
Task is: a list of numbers, find and print all the list elements with an even index number.
a = []
b = []
numbers = input()
for n in numbers.split():
a.append(int(n))
if int(n) % 2 == 0:
b.append(a[int(n)])
print(b)
int() can convert only numbers and raise error if argument contain a non-digit char, for example space ' '. You can use:
nums = input().split() # split() method splited string by spaces
a = []
for i in range(len(nums)): # len() function return count of list elements
if (i % 2) == 0:
a.append(nums[i])
print(a)
Also you can get
IndexError: list index out of range
Please comment if interesting why
int(input()) will only work on a single number. If you want to enter many numbers at once, you'll have to call input() first, split it into separate numbers, and call int() on each one:
numbers = input()
for n in numbers.split():
a.append(int(n))
Or using a list comprehension:
numbers = input()
a = [int(n) for n in numbers.split()]
I've been trying to write a program which finds the roots of an inputted mathematical function. I've only just started, so what I show here is only the start, and there are unused variables.
Here I wrote a function which is supposed to replace the term 'x' in a function with a value you input, say, 100. Here is the code:
code = list(input("Enter mathematical function: "))
lowBound = int(input("Enter lower bound: "))
upBound = int(input("Enter upper bound: "))
def plugin(myList, value):
for i in range(len(myList)):
if myList[i] == 'x':
myList[i] = value #replaces x with the inputted value
return ''.join(myList) #supposed to turn the list of characters back into a string
print(plugin(code,upBound))
But when I run the program, I get the error:
Traceback (most recent call last):
File "python", line 11, in <module>
File "python", line 9, in plugin
TypeError: sequence item 0: expected str instance, int found
(I'm using an online programming platform, so the file is just called 'python')
This doesn't make any sense to me. myList should not be an int, and even if it was the right data type (str), it should be a list. Can someone explain what's going on here?
You are replacing a str type (or character) with an int type.
Try this instead:
myList[i] = str(value)
You can only join an iterable of strings
return ''.join(str(x) for x in myList)
Or, more succinctly. Remove the function
print(''.join(str(upBound if x =='x' else x) for x in code)
My code:
number = raw_input().split()
# I can't get a line here to do the trick
a = list()
a.append(number)
All I need to do is enter 2 integers in a single line separated by a whitespace. Then enter them as integers in a Python list and then add the elements back into the result variable.
This splits everything you enter at whitespace and tries to convert each entry into an integer:
numbers = [int(x) for x in raw_input().split()]
This is a list comprehension. It does the same as this code:
numbers = []
for x in raw_input().split():
numbers.append(int(x))
The list comprehension is shorter. If you need to handle potential exceptions and your code gets more complicated, the loop might be more suitable.
Further improvement - Error Handling
There is always the possibility that the user enters erroneous data.
def get_numbers(count=2):
"""Get `count` integers from one line of user input.
"""
numbers = []
msg = 'Please enter {} integers separated by space: '.format(count)
for entry in raw_input(msg).split():
try:
numbers.append(int(entry))
except ValueError:
print('Found bad value: {}.'.format(entry))
return get_numbers()
if len(numbers) != count:
print('Need to enter exactly {} numbers. '
'Found: {}.'.format(count, len(numbers)))
return get_numbers()
return numbers
my_two_numbers = get_numbers()
You can map to int but any bad input will raise a valueError:
numbers = map(int,raw_input().split())
A safer approach would be a try/except to catch when the user enters bad input:
while True:
number = raw_input().split()
try:
# try casting to int
numbers = map(int, number)
break
except ValueError:
# user entered bad input so print message and ask again
print("Invalid input")
print(numbers) # list of ints
That will also allow one number or more than two numbers so if you want exactly two you need to check the length after splitting. You also have a list after splitting so a is not needed.
In order to avoid, bad input and forbidden characters I would use regex to search and then cast:
valid_integers = map(int, re.findall(r'-?\d+', user_input)) # cast found strs to ints