Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren+ 1
Does sum() function in Python converts the output into string? Or Is the return type of sum() is string??
I was doing a simple code to calculate a sum of the list whose elements are user defined and ended up with a mess. The need of for loop is because I need to get i/p that many iterations Like... The for loop denotes the number of days My input on a line would be amount spend on each day. Atlast i need the total sum of all the days https://code.sololearn.com/ciWLa0L7Qadb/?ref=app
15 Antworten
+ 1
ATSHAYA KUMAR.R in python input() accepts input in the form of string.. So you are input is string and splitting into a list of strings.. Sum on list of string is error there..
You know that for Integer value, we use casting like int( input())
So after splitting, convert list values to Integer values before applying sum....
+ 8
ma be you thought about something like this:
count = int(input('enter number of runs: '))
my_sum = 0
for i in range(count):
nums_lst = list(map(int, input('enter numbers sep by comma: ').split(',')))
my_sum += sum(nums_lst)
print('total sum is: ', my_sum)
+ 4
The sum function wants only number and gives only number!
It raises exception if the input is string even though strings can be added
+ 3
ATSHAYA KUMAR.R Noo that's the wrong idea
Try this instead of int(ar):
ar = list(map(lambda x: int(x), ar))
+ 2
sum() returns int.
+ 2
https://code.sololearn.com/cpOFBXovE133/?ref=app
Thank you Namit Jain and Jayakrishna🇮🇳
I have rectified where I went wrong. That was a much needed snippet and I got my output as well😌
+ 2
ATSHAYA KUMAR.R Great!!
Just a small doubt!
Where are you using the variable n?
+ 2
Namit Jain 😂 At first I wrote the code in such a way of passing n as input to the function.but when I use map function there is no use for "for" and in turn making "n" dummy.
Now only seen it , corrected it ... Thanks for noting it up🙌🏼
+ 1
That is for single number of string type..
Your input contains spaces so on that stage not possible...
Add this before sum(ar)
ar=[int(i) for i in ar ]
Edit : ATSHAYA KUMAR.R
s=0
for i in range(0,4):
print("enter rupees:")
ar=input().split()
ar=[int(i) for i in ar ]
a=sum(ar)
s=s+a
print(a)
#but your code print last input sum only..
+ 1
Yeah Lothar having a second for loop confused me a lot now it's as simple as you said.
+ 1
Put the sum in a variable and print it ....
0
rkk could you look at my code and say whats wrong?!
0
give us an example with values of how the program should be.
0
For day 0 my values are 1 3 4
So it's sum 8
For day 1 my values are 5 6 2
Sum 13
For last day my values are 2 1 4 5
Sum is 12
And i want s=12+13+8
=33
0
Jayakrishna🇮🇳 I tried the int() to the list as you said there in the list there is string but again I come across a problem as int() needs string not list.