0

I'm new to Python, and my tutor taught us about formatting, if else statements and print. He wants us to use the import function to read data from a CSV file, and he gave us a starting piece of code to help us with that, which is:

import csv
filePath = "data.csv"
with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['first_name'], row['last_name'])

The CSV file contains the following:

first_name,last_name,student_id,CSIT110,CSIT121,CSIT135,CSIT142
Peter,Tan,S1012342D,89,67,54,78
John,Lim,S1014322H,87,78,86,67
Ada,Ang,S1023456I,54,78,65,54

So what the objective is, is to prompt the user for their student number. And if the student number exists, it prints out their name, ID and grades. So far, my code is this:

import csv
filePath = "data.csv"
student_num=input("Enter student ID:")
with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
    #average =    int((row['CSIT110'])+int(row['CSIT121'])+int(row['CSIT135'])+int(row['CSIT142']))/4
        if (student_num == ""):
            print("Empty input. Please enter again.")       
        elif (student_num == "S1012342D"):
            print("=================")
            print("Student's details")
            print("=================")
            print("Student ID | First Name | Last Name")
            print("{0:<10} |{1:>11} | {2:<10}".format(row['student_id'],row['first_name'],row['last_name']))
            print("===============================================")
            print("CSIT110 | CSIT121 | CSIT135 | CSIT142 | Average")
            print("{0:^8}|{1:^9}|{2:^9}|{3:^9}|".format(row['CSIT110'],row['CSIT121'],row['CSIT135'],row['CSIT142']))

        elif (student_num == "S1014322H"):
            print("=================")
            print("Student ID | First Name | Last Name")
            print("{0:<10} |{1:>11} | {2:<10}".format(row['student_id'],row['first_name'],row['last_name']))
        else:
            print("No student record found.")

When I type one of the student ID, it just loops and prints out all the details. Would love some help!

3
  • 1
    What does elif (student_num == "S1012342D"): have to do with the task? Are you planning on hard-coding all the Id's? Commented Oct 5, 2018 at 15:40
  • Hi! Thank you for taking the time to look at my question! Since there's only 3 IDs, the tutor advised us to use the student ID as given. So yes, in a sense it's hardcoded. So if the student ID that the user input matches what's in the CSV, then it will display the data of that student. Commented Oct 5, 2018 at 15:47
  • Whats in the CSV and what you write as a hardcoded check are not the same thing, though Commented Oct 5, 2018 at 15:57

3 Answers 3

1

I suggest you:

  • to use the for...else to iterate over the student IDs
  • if an ID matches with the user input, to iterate over the row using for k,v in row.items() in order to display the student information

Here is the code:

import csv

filePath = "data.csv"

with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)
    student_id = input('Enter the sudent number: ')
    for row in reader:
        if student_id == row['student_id']:
            for k,v in row.items():
                print(k,':',v)
            break
    else:
        print('This number does not exist')

It prints Enter the sudent number:. If you enter S1014322H, then it outputs the following:

first_name : John
last_name : Lim
student_id : S1014322H
CSIT110 : 87
CSIT121 : 78
CSIT135 : 86
CSIT142 : 67
Sign up to request clarification or add additional context in comments.

Comments

0

You need to compare the entered student ID with the ones in the file line-by-line.

import csv
filePath = "data.csv"
student_num=input("Enter student ID:")
if (student_num == ""):
    print("Empty input. Please enter again.")
found = False
with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        if (row['student_id'] == student_num):
            average =    int((row['CSIT110'])+int(row['CSIT121'])+int(row['CSIT135'])+int(row['CSIT142']))/4
            print("=================")
            print("Student's details")
            print("=================")
            print("Student ID | First Name | Last Name")
            print("{0:<10} |{1:>11} | {2:<10}".format(row['student_id'],row['first_name'],row['last_name']))
            print("===============================================")
            print("CSIT110 | CSIT121 | CSIT135 | CSIT142 | Average")
            print("{0:^8}|{1:^9}|{2:^9}|{3:^9}|".format(row['CSIT110'],row['CSIT121'],row['CSIT135'],row['CSIT142']))
            found = True
            break
if not found:
    print("No student record found.")

2 Comments

This seems perfect! May I know the use of the word 'found'?
found is to check whether the student ID has been found. The error message will print if found is False. break ends the for-loop so that it doesn't continue when the student ID has been found.
0

If I understand you would catch information about a student by them ID. Try it :

import csv
filePath = "data.csv"
student_num=input("Enter student ID:")
with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)
    not_found = True
    for row in reader:
        if student_num == row['student_id']:
            not_found = False
            print("=================")
            print("Student's details")
            print("=================")
            print("Student ID | First Name | Last Name")
            print("{0:<10} |{1:>11} | {2:    <10}".format(row['student_id'],row['first_name'],row['last_name']))
            print("===============================================")
            print("CSIT110 | CSIT121 | CSIT135 | CSIT142 | Average")
            print("{0:^8}|{1:^9}|{2:^9}|{3:^9}|".format(row['CSIT110'],row['CSIT121'],row['CSIT135'],row['CSIT142']))
    if not_found:
        print("No student record found.")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.