Python Forum

Full Version: Casting from str to int
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all, absolute Python beginner here...

Question: I am getting an "unsupported operand type" error on my code below on line 13 of my code. I think it's telling me I need to cast from a string to an integer but everything I try I still get an error.

Can anyone please tell me what i'm missing/doing wrong?

Error:
Traceback (most recent call last): File "C:/Users/aaron/PycharmProjects/assessment_two/marks.py", line 13, in <module> sumOfMarks = sum(marksList) TypeError: unsupported operand type(s) for +: 'int' and 'str'
ERROR
please enter your 5 marks below
enter mark 1: 10
enter mark 2: 12
enter mark 3: 16
enter mark 4: 14
enter mark 5: 18
['10', '12', '16', '14', '18']
Error:
Traceback (most recent call last): File "C:/Users/aaron/PycharmProjects/assessment_two/marks.py", line 13, in <module> sumOfMarks = sum(marksList) TypeError: unsupported operand type(s) for +: 'int' and 'str'
Process finished with exit code 1

CODE
print("please enter your 5 marks below")

mark1 = input("enter mark 1: ")
mark2 = input("enter mark 2: ")
mark3 = input("enter mark 3: ")
mark4 = input("enter mark 4: ")
mark5 = input("enter mark 5: ")

marksList = [mark1, mark2, mark3, mark4, mark5]

print(marksList)

sumOfMarks = sum(marksList)
averageOfMarks = sum(marksList)/5

print("The sum of your marks is: "+str(sumOfMarks))
print("The average of your marks is: "+str(averageOfMarks))
Thanks,
Aaron
look at int() function. input() will return str, so you need to cast them to int.
Thanks buran

But where do I put this in my code? I have tried putting it in several places but get a type error like the one below:

Traceback (most recent call last):
File "C:/Users/aaron/PycharmProjects/assessment_two/marks.py", line 9, in <module>
marksList = int[mark1, mark2, mark3, mark4, mark5]
TypeError: 'type' object is not subscriptable

Thanks,
Aaron
..Ah ignore me - i got it to work.

Thank you Big Grin
If you got it working then you should have time to consider some other aspects of your code:

- use naming conventions set in PEP8 (Function and Variable Names)
- on row #13 you calculate sum. On next line you calculate it again instead of using already calculated value.
- instead of repeating rows #3-7 and then putting variables into list you can do it in one step (note that I omitted datatype conversion problem as it is already solved):
 
>>> [input(f'Enter mark {i+1}: ') for i in range(5)]
Enter mark 1: 1
Enter mark 2: 2
Enter mark 3: 3
Enter mark 4: 4
Enter mark 5: 5
['1', '2', '3', '4', '5']