Reputation: 1
def displaymsg(avg):
DL=str("deans list")
AP=str("academic probation")
message=("no message")
if (avg>3.5):#if input for avg is > 3.5 message will is = DL
message=DL
else:
if (avg<2.0):#if avg is < 2.0 message is =AP
message=AP
return str(message)
gpa=[ ]
stu_data=open ("studentData.txt", encoding = "UTF-8")
firstData=()
for data in stu_data:
if firstData==0:
gpa.append(data)
print("student name:", gpa[firstData])
firstData=1
else:
gpa.append (float(data))
stu_data.close()
sumGpa=0
count=5
for index in range (1, count) :
sumGpa=sumGpa+gpa[index]
print(gpa[index])
count=count-1
average=sumGpa/count
msg=displaymsg(average)
print(msg)
when I run this I get a could not convert string to float error. what is inside the studentData.txt document is david smith followed by the numbers 3.2, 3.1, 3.4, 3.3,and 3.5.
Upvotes: 0
Views: 430
Reputation: 169
I see two issues with your code:
You initialize firstData to a tuple. So the line
if firstData==0:
will never be true.
You should surround this statement within a try/except clause:
gpa.append (float(data))
The reason why you're getting the exception is because of 1, since your if statement is always false, the first line from the file which is not a number gets passed to the append statement, where it tries to convert a string that has no numbers to a float.
A utility function like this may be helpful:
def is_number(value):
try:
float(value)
return True
except ValueError:
return False
Upvotes: 1