The question is to iterate through the list and calculate and return the sum of any numeric values in the list.
That's all I've written so far...
def main():
my_list = input("Enter a list: ")
total(my_list)
def total(my_list1):
list_sum = 0
try:
for number in my_list1:
list_sum += number
except ValueError:
#don't know what to do here
print list_sum
main()
If you check to see whether the list item is an int, you can use a generator:
>>> a = [1, 2, 3, 'a']
>>> sum(x for x in a if isinstance(x, int))
6
You can use a generator expression such that:
from numbers import Number
a = [1,2,3,'sss']
sum(x for x in a if isinstance(x,Number)) # 6
This will iterate over the list and check whether each element is int/float using isinstance()
Maybe try and catch numerical
this seams to work:
data = [1,2,3,4,5, "hfhf", 6, 4]
result= []
for d in data:
try:
if float(d):
result.append(d)
except:
pass
print sum(result) #25, it is equal to 1+2+3+4+5+6+4
Using the generator removes the need for the below line but as a side note, when you do something like this for this:
try:
for number in my_list1:
list_sum += number
except ValueError:
#don't know what to do here
You need to call float() on the number to force a ValueError when a string is evaluated. Also, something needs to follow your except which could simply be pass or a print statement. This way of doing it will only escape the current loop and not continue counting. As mentioned previously, using generators is the way to go if you just want to ignore the strings.
def main():
my_list = input("Enter a list: ")
total(my_list)
return
def total(my_list1):
list_sum = 0
try:
for number in my_list1:
list_sum += float(number)
except ValueError:
print "Error"
return list_sum
if __name__ == "__main__":
main()
Related
I had the assignment to create a function which would allow the user to input a string of numbers and then receive that string as an int list. I was also supposed to use string slicing for this particular function. That being said I couldn't come up with anything fancy and this is what I wrote:
def Split_to_Integers():
print("Put in a string:")
Input = str(input())
List = []
List.append(Input)
print(List)
It is nothing fancy but it somehow got the job done. However, I also have the official solution which looks as follows:
def split_to_integers(inputstr):
res = []
last = 0
max = len(inputstr)
for i in range(max):
if inputstr[i] == " ":
nmbr = inputstr[last:i]
last = i+1
res.append(int(nmbr))
nmbr = inputstr[last:]
res.append(int(nmbr))
return res
The second function works when I put in one integer, however, as soon as I put in a second one, the function crashes, and I dont know where the Problem is.
You can use the split function of strings. Like so:
def list_from_string(number_string: str):
ints = [int(item) for item in number_string.split(" ")]
return ints
if __name__ == "__main__":
s = input("Enter the string: ")
result = list_from_string(s)
print(result, type(result))
This is the behavior in a console:
Enter the string: 6 5 4
[6, 5, 4] <class 'list'>
I just started learning Python and want to create a simple script that will read integer numbers from user input and print their sum.
The code that I wrote is
inflow = list(map(int, input().split(" ")))
result = 1
for i in inflow:
result += inflow[i]
print(result)
It gives me an error
IndexError: list index out of range
pointing to result += inflow[i] line. Can't see what am I doing wrong?
BTW, is there more elegant way to split input flow to the list of integers?
You can also avoid the loop altogether:
inflow = '1 2 34 5'
Then
sum(map(int, inflow.split()))
will give the expected value
42
EDIT:
As you initialize your result with 1 and not 0, you can then also simply do:
sum(map(int, input.split()), 1)
My answer assumes that the input is always valid. If you want to catch invalid inputs, check Anton vBR's answer.
Considering: I just started learning Python
I'd suggest something like this, which handle input errors:
inflow = raw_input("Type numbers (e.g. '1 3 5') ") #in py3 input()
#inflow = '1 2 34 5'
try:
nums = map(int, inflow.split())
result = sum(nums)
print(result)
except ValueError:
print("Not a valid input")
for i in list gives the values of the list, not the index.
inflow = list(map(int, input().split(" ")))
result = 1
for i in inflow:
result += i
print(result)
If you wanted the index and not the value:
inflow = list(map(int, input().split(" ")))
result = 1
for i in range(len(inflow)):
result += inflow[i]
print(result)
And finally, if you wanted both:
for index, value in enumerate(inflow):
script that will read integer numbers from user input and print their
sum.
try this :
inflow = list(map(int, input().split(" ")))
result = 0
for i in inflow:
result += i
print(result)
If you were going to index the list object you would do:
for i in range(len(inflow)):
result += inflow[i]
However, you are already mapping int and turning the map object into a list so thus you can just iterate over it and add up its elements:
for i in inflow:
result += i
As to your second question, since you arent doing any type testing upon cast (i.e. what happens if a user supplies 3.14159; in that case int() on a str that represents a float throws a ValueError), you can wrap it all up like so:
inflow = [int(x) for x in input().split(' ')] # input() returns `str` so just cast `int`
result = 1
for i in inflow:
result += i
print(result)
To be safe and ensure inputs are valid, I'd add a function to test type casting before building the list with the aforementioned list comprehension:
def typ(x):
try:
int(x)
return True # cast worked
except ValueError:
return False # invalid cast
inflow = [x for x in input().split(' ') in typ(x)]
result = 1
for i in inflow:
result += i
print(result)
So if a user supplies '1 2 3 4.5 5 6.3 7', inflow = [1, 2, 3, 5, 7].
What your code is doing, in chronological order, is this:
Gather user input, split per space and convert to integer, and lastly store in inflow
Initialize result to 1
Iterate over every item in inflow and set item to i
Add the current item, i to result and continue
After loop is done, print the result total.
The broken logic would be at step 4.
To answer your question, the problem is that you're not gathering the index from the list as expected-- you're iterating over each value in the list opposed to the index, so it's really undefined behavior based on what the user inputs. Though of course, it isn't what you want.
What you'd want to do is:
inflow = list(map(int, input().split(" ")))
result = 1
for i in range(len(inflow)):
result += inflow[i]
print(result)
And on your last regard; there are two real ways to do it, one being the way you're doing right now using list, map and:
inflow = [int(v) for v in input().split()]
IMO the latter looks better. Also a suggestion; you could call stdlib function sum(<iterable>) over a list of integers or floats and it'll add each number and return the summation, which would appear more clean over a for loop.
Note: if you're splitting per whitespace you can just call the str.split() function without any parameters, as it'll split at every whitespace regardless.
>>> "hello world!".split()
['hello', 'world!']
Note: also if you want extra verification you could add a bit more logic to the list comprehension:
inflow = [int(v) for v in input().split() if v.isdigit()]
Which checks whether the user inputted valid data, and if not, skip past the data and check the following.
This sounds so simple, but I cannot find anything on how to do this on the internet. I've gone through documentation but that didn't help me.
I have to get inputs from the user to create a list. This is what I am using right now.
t = raw_input("Enter list items: ")
l = map(str,t.split())
But this is converting every element into a string. If I use int in map function, then every element would be converted to int.
What should I do? Is there any other function that I am missing?
You can use a list comprehension to only call int on the strings which contain nothing but numerical characters (this is determined by str.isdigit):
t = raw_input("Enter list items: ")
l = [int(x) if x.isdigit() else x for x in t.split()]
Demo:
>>> t = raw_input("Enter list items: ")
Enter list items: 1 hello 2 world
>>> l = [int(x) if x.isdigit() else x for x in t.split()]
>>> l
[1, 'hello', 2, 'world']
>>>
use try/except. Try to make it an int. If that fails, leave it as a string.
def operation(str):
try:
val = int(str)
except ValueError:
val = str
return val
t = raw_input("Enter list items: ")
l = map(operation,t.split())
print l
You can use a list comprehension rather than map for more "pythonic" code:
t = raw_input("Enter list items: ")
l = [operation(x) for x in t.split()]
Edit: I like iCodez's better... the isDigit test is nicer than try except.
i'm trying to write a function where user can input a list of numbers, and then each number gets squared, example [1,2,3] to [1,4,9]. so far my code is this:
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()] ##display user input
list = []
for n in num:
list += int(n)*int(n)
print list;
x = squarenumber()
but i get this error saying 'int' object is not iterable. I tried different ways, but still no clue so if anyone can help me i'd be greatly appreciated.
First of all do not use list as a variable, use lst. Also you are incrementing a value not appending to a list in your original code. To create the list, then use lst.append(). You also need to return the list
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()] ##display user input
lst = []
for n in num:
if n.isdigit():
nn = int(n)
lst.append(nn*nn)
print lst
return lst
x = squarenumber()
With lists, you should use append() instead of +=. Here is the corrected code:
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()] ##display user input
lst = []
for n in num:
lst.append(int(n)*int(n))
print lst
x = squarenumber()
[Running the code]
Enter numbers, eg 1,2,3: 1,2,3
[1, 2, 3]
[1, 4, 9]
def squarenumber(inp):
result = [i**2 for i in inp]
return result
>>>inp = [1,2,3,4,5]
>>>squarenumber(inp)
[1, 4, 9, 16, 25]
You can get the desired output using list comprehension instead another loop to append the square of a number to list. Dont use list as a variable name
def squarenumber():
num = raw_input('Enter numbers, eg 1,2,3: ').split(',')
print num # display user input
lst= [int(n)* int(n) for n in num if n.isdigit()]
print lst # display output
x = squarenumber()
Since you're using the list comprehension to print the input, I thought you might like a solution that uses another one:
def squarenumber():
num = raw_input('Enter numbers, e.g., 1,2,3: ').split(',')
print [int(n) for n in num if n.isdigit()]
print [int(n)**2 for n in num if n.isdigit()]
x = squarenumber()
I'm trying to do a for loop with [i] number of similar functions in Python:
i = int(raw_input())
for i in range (0, i):
myfunction[i] = str(raw_input())
And I'm getting an error that it isn't defined. So I'm defining it.... How do I define [i] number of similar functions?
larsmans answer can also be implemented this way:
def make_function(x):
def function(y):
return x + y
return function
functions = [make_function(i) for i in xrange(5)]
# prints [4, 5, 6, 7, 8]
print [f(4) for f in functions]
Updated
From the edit and all the comments it seems that you want to ask the user for a number N and then ask for N strings and have them put into a list.
i = int(raw_input('How many? '))
strings = [raw_input('Enter: ') for j in xrange(i)]
print strings
When run:
How many? 3
Enter: a
Enter: b
Enter: c
['a', 'b', 'c']
If the list comprehension seems unreadable to you, here's how you do it without it, with some comments:
i = int(raw_input('How many? '))
# create an empty list
strings = []
# run the indented block i times
for j in xrange(i):
# ask the user for a string and append it to the list
strings.append(raw_input('Enter: '))
print strings
You can't set list items by index, try:
myfunction = []
for i in range(0, 5):
myfunction.append(whatever)
I'm not sure what you want here, but from all that you said, it appears to me to be simply this:
def myfunction(j):
for i in range(j):
variable.append(raw_input('Input something: '))
I still think this may not be what you want. Correct me if I am wrong, and please be a little clear.
myfunction[i] is the i'th element of the list myfunction, which you have not already defined; hence the error.
If you want a sequence of functions, you can try something like this:
def myfunction(i,x):
if i==0:
return sin(x)
elif i==1:
return cos(x)
elif i==2:
return x**2
else:
print 'Index outside range'
return
If you need similar functions that have something to do with i, it gets simpler, like this example:
def myfunction(i,x):
return x**i