-1

I'm trying to convert a string number to int in visual studio, but whenever I do it shows me an error.

"c:\Users\USER\Desktop\Appbrewery_course\Day_5\Average_height_exercise.py", line 5, in <module>
        student_heights[i] = int(student_heights[i])
    ValueError: invalid literal for int() with base 10: '180,'

Here is the below code i have written.

    #  Don't change the code below 
student_heights = input("Input a list of student heights ").split()
print(student_heights)
for i in range(0,len(student_heights)):
    student_heights[i] = int(student_heights[i])
#  Don't change the code above 
print(type(student_heights[0]))
  • Either don't enter the comma, or remove it. – Klaus D. Jan 29 '22 at 06:25
  • 1
    `.split()` doesn't know you've passed a comma-separated list, so they're still in the resulting strings, which can't be parsed as `int`. – Joe Jan 29 '22 at 06:26
  • @KlausD. Thanks dear, I did a little mistake. I didn't pass the argument into the split() function. I sitting almost 1 hour to fix these bugs. – Rajanul Islam Jan 29 '22 at 06:33

1 Answers1

0
student_heights = input("Input a list of student heights ").split()

This line takes a string and splits it whenever it encounters a space. Make sure to seperate the input string with spaces rather than any other character.

For example, with the current setup, input string should look like : 100 200 300 400 500

and not like : 100,200,300,400

Your code is correct, just enter the input string according to your input method as mentioned above.

EDIT: If you want to use a comma seperated input string (i.e 100,200,300,400) then change line 5 to :

student_heights = input("Input a list of student heights ").split(",")
kun101
  • 1
  • 1