Ovi
Ovi

Reputation: 573

Python file processing?

My assignment was to write a program which extracts the first/last names, birth year, and ID from a file, manipulate that information to create a username and formatted ID, prompt the user for 3 test grades, calculate the average, and finally write all the information to a new file. This is the program I wrote, and the error I got is listed below the program. Define main function

def main():
infile = open("studentinfo.txt", "r")
data = infile.read()
fName, lName, ID, year = data.split(",")
year = int(year)

Prompt the user for three test scores

grades = eval(input("Enter the three test scores separated by a comma: "))

Create a username

uName = (lName[:4] + fName[:2] + str(year)).lower()
converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
grade_1, grade_2, grade_3 = grades

Convert the grades to strings so they can be written to a new file

[grade_1, grade_2, grade_3] = [str(grade_1), str(grade_2), str(grade_3)]

Calculate the average

average =(grade_1 + grade_2+ grade_3)/3

Convert the average to a string

average = str(average)

Write the information the file

outfile = open("studentreport.txt", "w")
outfile.write("*******Student Report*******\nStudent Name:" + fName + " " + lName)
outfile.write("\nStudent ID:  " + converted_id + "\n" + "Username:    " + uName + "\n\n")
outfile.write("Grade 1:    " + grade_1 + "\n" "Grade 2:    " + grade_2 + "\n" + "Grade 3:    " + grade_3 + "\n" + "Average:    " + average)   

infile.close()
outfile.close()

main()

Traceback (most recent call last):

File "C:/Users/ovi/Desktop/Python Project 1.py", line 34, in

main()

File "C:/Users/ovi/Desktop/Python Project 1.py", line 22, in main

average =(grade_1 + grade_2+ grade_3)/3

TypeError: unsupported operand type(s) for /: 'str' and 'int'

Upvotes: 0

Views: 169

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

You need to convert the variables of type int to strings.

outfile.write("Grade 1:    " + str(grade_1) + "\n" "Grade 2:    " + str(grade_2) + "\n" + "Grade 3:    " + str(grade_3) + "\n" + "Average:    " + str(average))

OR

You could simply do like this..

>>> gr1 = 23
>>> gr2 = 45
>>> gr3 = 56
>>> total = gr1+gr2+gr3
>>> avg = total/3
>>> l = [gr1, gr2, gr3, total, avg]
>>> print("GRade 1: {} grade 2: {} grade 3: {} total: {} average : {}".format(*l))
GRade 1: 23 grade 2: 45 grade 3: 56

Upvotes: 1

Lazik
Lazik

Reputation: 2520

You need to convert your converted string grades to floats (or int)

average =(float(grade_1) + float(grade_2)+ float(grade_3))/3.0
average = str(average)

Upvotes: 1

Related Questions