Azaqi
Azaqi

Reputation: 125

How do I display data from CSV based on user input?

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!

Upvotes: 0

Views: 2756

Answers (3)

Mehdi Sadour
Mehdi Sadour

Reputation: 1

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.")

Upvotes: 0

Laurent H.
Laurent H.

Reputation: 6526

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

Upvotes: 1

riddler
riddler

Reputation: 467

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.")

Upvotes: 0

Related Questions