简体   繁体   中英

Converting string data to integer in Python

I have the following program that reads some data from a csv file but it seems to be resisting all attempts to either read the "marks" data as an integer or convert it to one later on. I based this program on another I have which is fully functional with the only real difference that the integer field was a float in my functioning program.

I've tried entering the following line into the findHighest function just after the "for counter..." line.

**Students[0].marks = int(Students[0].marks)**

The code runs but doesn't find the highest number in the data (it comes back with 96 when the highest number is 100, the second highest is 96). I've also tried altering the following line...

Students[counter].marks = row[3]

and changed it to...

**Students[counter].marks = int(row[3])**

This gives me the following error:

ValueError: invalid literal for int() with base 10: ''

What am I missing here? :-/

import csv

class Student:
    def __init__(self,forename,surname,form,marks):
        self.forename = ""
        self.surname = ""
        self.form = ""
        self.marks = 0

def readFile():
    Students = []
    filename = "pupils.csv"
    csv_file = open(filename, "r")
    reader = csv.reader(csv_file)
    counter = 0
    for row in reader:
        Students.append(Student("", "", "", 0)) 
        Students[counter].forename = row[0] 
        Students[counter].surname = row[1] 
        Students[counter].form = row[2] 
        Students[counter].marks = row[3]
        counter = counter + 1
    return Students


def findHighest(Students):
    position=0
    highest = Students[0].marks
    for counter in range(len(Students)):
        Students[counter].marks = int(Students[counter].marks)
        if Students[counter].marks > highest:
            highest = Students[counter].marks
            position = counter
    return highest

def displayHighest(highest):
    print("the highest pupil score was:", highest)

Students = readFile()
highest = findHighest(Students)
displayHighest(highest)

CSV File:

CSV

I guess you have multiple problems

def findHighest(Students):
    position=0

#highest is set to a string. You should set highest to 0
    highest = Students[0].marks
    for counter in range(len(Students)):

#why do you always set Students[0] and not Students[counter]. You always convert Students[0] to int.
        Students[0].marks = int(Students[0].marks)

#As a result you always tests string again strings:
        if Students[counter].marks > highest:
            highest = Students[counter].marks
            position = counter
    return highest

This try

Students[counter].marks = int(row[3])

should be correct but the ValueError can be a hint that your content of your CSV is not at all lines a correct integer value. Please check your CSV or handle the exception like this: Converting String to Int using try/except in Python

It seems this was a problem with the CSV file rather than the code. I created a new file from scratch and it the Students[counter].marks = int(row[3]) line works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM