Reputation: 13
I've got a simple question but I can't really find a right solution for that.
I have a csv file that contains students' names and subjects for which they are registered: name,subject1,subject2,subject3 Student1,MN1,MN2,MN3 Student2,BN1,BN2,BN3 Student3,MN4,MN5,MN6
Student needs to enter his name and subject name in order to check whether he is registered or not for this subject
My code:
import csv
Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")
with open('students.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (row['name'] == Name and row['subject1'] == Subject or
row['subject2'] == Subject or row['subject3'] == Subject):
print ("You are registered. It won't take long to run your VM")
else:
print ("You are not registered")
My problem is that it gives multiple outputs to me Output: Please provide your name: Student3 Please provide your Subject: MN4 You are not registered You are not registered You are registered. It won't take long to run your VM
Obviously, it should be just: You are registered. It won't take long to run your VM
Could you please help me to solve this problem? Thank you
Upvotes: 0
Views: 1491
Reputation: 71461
I believe a dictionary will work best for you:
import csv
data = {i[0]:i[1:] for i in csv.reader(open('filename.csv'))}
Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")
if Subject in data[Name]:
print("you are registered")
else:
print("you are not registered")
Upvotes: 1
Reputation: 57357
A dataframe will be a good structure to store you csv file. Please give it a read here, anyway coming to your code. Please refer the below code.
Please install pandas and numpy for this
pip install pandas
pip install numpy
Code:
import pandas as pd
import numpy as np
df = pd.read_csv("testing.csv")
Name = input("Please provide your name: ")
Subject = input("Please provide your Subject: ")
query = '(name == '+ '\'' + Name + '\'' + ') and (subject1 == '+ '\'' \
+ Subject + '\'' + ' or subject2 == ' + '\'' + Subject + '\'' \
+ ' or subject2 == ' + '\'' + Subject + '\')'
if df.query(query).empty:
print ("You are registered. It won't take long to run your VM")
else:
print ("You are not registered")
Reference:
Upvotes: 0
Reputation: 5942
Note that for
loops in Python have an optional else
clause that will execute when the loop ends without a break
statement...
Your code prints each iteration of the loop. What you want is to print only at the end of the loop...
with open('students.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (row['name'] == Name and (row['subject1'] == Subject or row['subject2'] == Subject or row['subject3'] == Subject)):
print("You are registered. It won't take long to run your VM")
break
else:
print("You are not registered")
Upvotes: 2