Home > Mobile >  Could not convert string to float error in pyhton
Could not convert string to float error in pyhton

Time:10-29

heres the code

#l is a list that stores all the GPAs of 10 students
l = []
#iterates the loop to collect GPAs of 10 members in the class
for i in range(1, 11):
   j = int(float(input()))  #this is where the error is
   l.append(j)
#find the average GPA of the class and store the average in the "result" variable
result = sum(l)/10
#printing the result
print("Average is: ",result)

at first it was j=int(input) and that was also giving an error. im new to python

CodePudding user response:

I ran your code, it works without any problem! You have to give each value in the terminal and press enter.

CodePudding user response:

For input validation. Start with a try except block.

for i in range(0, 3):
  n = input('Enter a value..\n')
  while type(n) is not float:
    try:
      float(n)
      break
    except ValueError:
      n = input('Try again..\n')
  #append

CodePudding user response:

Why you need to convert that input to float ? All you need is check the input that can be convert to int with try and expect then when you Division a number every time you getting floating point number and I run your code it's working can you edit your questions and put the error there

score_list =[]

for num in range(10):
    number = int(float(input("enter a number")))
    score_list.append(number)
    
results = sum(score_list)/len(score_list)
print(results)
  • Related