Reputation: 1
Why does " TypeError: unsupported operand type(s) for /: 'str' and 'int' " pop up and how could I fix it?
CODE:
import sys
import statistics
list_num = sys.argv[1:]
print(list_num)
for i in range(0, len(list_num)):
if list_num[i].isdigit():
list_num[i] = str(list_num[i])
else:
list_num[i] = str(len(list_num[i]))
print(list_num)
print("Mode: " + str(statistics.mode(list_num)))
print("Median: " + str(statistics.median(list_num)))
OUTPUT:
['1', '2', 'way', 'fdk', '4', 'fdsfdsds']
['1', '2', '3', '3', '4', '8']
Mode: 3
Traceback (most recent call last):
File "main.py", line 12, in
print("Median: " + str(statistics.median(list_num)))
File "/usr/lib/python3.4/statistics.py", line 318, in median
return (data[i - 1] + data[i])/2
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Upvotes: 0
Views: 848
Reputation: 200
The array list_num you have as argument should be composed by numbers, ints or floats. You have a list of strings: ['1', '2', '3', '3', '4', '8']. It should be: [1, 2, 3, 3, 4, 8], without single quotes.
Upvotes: -1
Reputation: 3248
You're trying to do a calculation with strings. Don't convert the items in the list to strings before calculating the median
import sys
import statistics
list_num = sys.argv[1:]
print(list_num)
for i in range(0, len(list_num)):
if list_num[i].isdigit():
list_num[i] = float(list_num[i])
else:
list_num[i] = float(len(list_num[i]))
print(list_num)
print("Mode:", str(statistics.mode(list_num)))
print("Median:", str(statistics.median(list_num)))
I've changed the str() functions for float() functions. You can also use int(), depending on what you want to achieve.
Moreover, you are converting the outcome of the mode and median functions to a string. A string is text, and not a number. Are you sure this is what you want to do?
Upvotes: 0