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!
elif (student_num == "S1012342D"):have to do with the task? Are you planning on hard-coding all the Id's?