Comparing input values with csv file in Python 3.4 - python

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

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

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

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:
pandas query

Related

How to make sure MM/DD/YYYY format actually works and prints in other file?

I have been having issues in Python making this code work. I am trying to make a loop in which I receive a birthdate and make sure it is in the MM/DD/YYYY format. But, whenever I try to run the program with the input formatted I still receive the Error message I coded to print out.
from datetime import datetime
a1 = open(to_file,'a')
def confirm_date(d):
a_value = False
value = ""
while a_value == False:
value = input("Insert BIRTHDDATE in MM/DD/YYYY format including slashes: ")
try:
datetime.strptime(d, '%m/%d/%Y')
a_value = True
if a_value == True:
c1 = value
else:
c1 != value
except ValueError:
print("Error: Date format invalid.")
c = confirm_date(d)
a1.write(c)
print("Thank you! Goodbye!")
a1.close()
As presented, your code has several indentation issues that will prevent it from running at all. Remember in Python indentation is used to represent a code block.
It's also good practice (pythonic) to use descriptive variable names to keep track of everything.
I've rewritten your script in line with this, assuming you've got a formatting issue that hasn't been properly transferred to StackOverflow.
from sys import argv
from datetime import datetime
script, to_file = argv
output_file = open(to_file, "a")
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
city = input("Enter city you are in: ")
state = input("Enter state you are in: ")
def get_date():
is_valid_date = False
date_str = ""
while not is_valid_date:
date_str = input("Insert BIRTHDDATE in MM/DD/YYYY format including slashes: ")
try:
datetime.strptime(date_str, "%m/%d/%Y")
# if the previous line does not throw an error, it can be parsed as a valid date,
# so we'll exit the loop
is_valid_date = True
except ValueError:
print("Error: Date format invalid.")
return date_str
birthday = get_date()
output_file.write(
first_name + " " + last_name + " " + city + " " + state + " " + birthday + "\n"
)
print("Thank you! Goodbye!")
output_file.close()
Note the indentation within the get_date function. The try-except block is now aligned. You could also use an infinite while loop with a break statement, but I've kept it in line with the way you've written it.
You've made a good start. Hopefully that clarifies things for you. If not, please add more information to your question.

How to recognize name (from text file) in user input and then print name

My ideal goal is for the chat bot to recognize that you are talking about one of your siblings. So, when you mention your brother or sister (either by name or the keywords: my brother/sister) the chat bot will already know who they are from the data given in their text file. I have already figured out the keyword part, but when I mention them by name (For example: I can't stand James). The chat bot doesn't print what I want it to and when the user tells the chat bot their sibling's name it ends up printing both ("Oh, so your brother's name is") and ("I'll make sure to remember that, so what about " + brother_status['name'] + "?"). What can I do to fix this problem?
I have already tried this, but this doesn't seem to work either:
import string
user_input = raw_input("Please enter your sisters name: ").translate(string.maketrans("",""), string.punctuation)
with open('file.txt') as sibling_database:
if len(user_input.split()) >= 2:
for line in sibling_database:
for word in line.split(':'):
for words in user_input.split():
if words in word:
print("Oh, so your brother's name is " + line.split(':')[1])
Also here is my original code (In case you want to make any other changes):
import string
brother_status = dict([
('name', ''),
('nickname', ''),
('current age', ''),
('relationship', '')])
brother_keywords = ["Brother", "brother"]
sister_keywords = ["Sister", "sister"]
def main():
while True:
user_input = raw_input("What type of sibling do you have: ").translate(string.maketrans("",""), string.punctuation)
for keyword in brother_keywords:
if keyword in user_input:
with open('file.txt', 'r') as sibling_database:
for brother_data in sibling_database:
if brother_data.startswith("Brother's Name"):
print (brother_data.split(':')[1])
return
break
if user_input.split():
with open('file.txt') as sibling_database:
for line in sibling_database:
for word in user_input.split():
if word in line:
print("Oh, so your brother's name is " + line.split(':')[1] * 1)
return
break
if user_input.split():
for keyword in brother_keywords:
if keyword in user_input:
if user_input not in brother_status:
with open ('file.txt') as sibling_database:
first = sibling_database.read(1)
if not first:
print ("You never mentioned a brother. What's his name?")
user_input = raw_input("What's his name: ")
brother_status['name'] = (user_input)
with open('file.txt', 'w') as sibling_database:
sibling_database.write("Brother's Name:" + brother_status['name'] * 1 + '\n')
print ("I'll make sure to remember that, so what about " + brother_status['name'] + "?")
continue
if __name__ == "__main__":
main()
Your bigger problem is managing the state of your program.
Everyloop; you are testing all of your if, and them being true will get executed all the time, which is not what you want.
I would suggest to not rush steps too quickly, for instance I don't think if not first: does what you expect.
One way to help organise and manage that state is to use functions. Use plenty of them!
Then I would suggest going piece by piece : you need to figure out under what conditions you want each question/answer to appear in your code. If you're asking about a brother you don't know, then probably the code that talks about an unknown brother shouldn't be in the place. Or should have condition to guard the code from executing.
You'll probably get to a point where you'll have conditions all over the place, when that happens (and not before, or for curiosity) you should check out "state machines".
Side notes about python 3 :
Python 2 is becoming obsolete in 2020 and should not be used anymore. Systems will not ship with them, and people are expected to use python 3, and support for python 2 will stop.
This is not to say you shouldn't continue using python 2 as a learning tool, but you should think about learning python 3, you'll get more help more easily. Also there's a few cool features that python 2 doesn't have and you wouldn't want to miss out on that^^
I have updated your code with nltk pos tags to extract out the names from text file. Try it:
import string
import nltk
nltk.download('maxent_treebank_pos_tagger')
brother_status = dict([
('name', ''),
('nickname', ''),
('current age', ''),
('relationship', '')])
brother_keywords = ["Brother", "brother"]
sister_keywords = ["Sister", "sister"]
def main():
while True:
user_input = raw_input("What type of sibling do you have: ").translate(string.maketrans("",""), string.punctuation)
for keyword in brother_keywords:
if keyword in user_input:
with open('file.txt', 'r') as sibling_database:
data = sibling_database.readline()
data = nltk.word_tokenize(data)
tagged_data = nltk.pos_tag(data)
for name, pos in tagged_data:
if pos == "NNP":
print(name)
return
break
if user_input.split():
with open('file.txt') as sibling_database:
for line in sibling_database:
for word in user_input.split():
if word in line:
print("Oh, so your brother's name is " + line.split(':')[1] * 1)
return
break
if user_input.split():
for keyword in brother_keywords:
if keyword in user_input:
if user_input not in brother_status:
with open ('file.txt') as sibling_database:
first = sibling_database.read(1)
if not first:
print ("You never mentioned a brother. What's his name?")
user_input = raw_input("What's his name: ")
brother_status['name'] = (user_input)
with open('file.txt', 'w') as sibling_database:
sibling_database.write("Brother's Name:" + brother_status['name'] * 1 + '\n')
print ("I'll make sure to remember that, so what about " + brother_status['name'] + "?")
continue
if __name__ == "__main__":
main()

Insert new string into list and for it to hold the information

I'm learning Python and I'm wondering how you would insert a name into a list and for it to be held in that variable so the script can identify if it's seen you before.
Any help would be much appreciated
# Default People Already In List at program start
list = ['Bob','Jim',]
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in list:
print("Nice to meet you again" + Name)
else:
list.insert(0, Name)
print("Hi " + Name + ", Nice too meet you for the first time.")
# Troubleshoot
print(list)
Your should rename your variables - here a short correction of your code, although it is looking good already! I changed the insert to append as well!
But it will obviously forget since the list is always initialized with Bob and Jim in it, and then you ask for the name - if is not Bob or Jim, it is new and therefore appended. But then your program ends, so when you start it new, your list is only populated with Bob & Jim again. You could put the whole construct in a "while True" construct to make the same question multiple times until you dont want to anymore!
EDIT: included the while (you can enter it numerous times if you just press "Enter" for the question! and put the list in the beginning, so it will not be initialized every time you run a new name! and important: if you see someone for the first time, include the print in the else-clause, otherwise it will be printed everytime, even if you saw the name before!
name_list = ['Bob','Jim']
while True:
print("Hello, What\'s your name? ")
input_name = input("Enter your Name: ")
if str(input_name) in name_list:
print("Nice to meet you again, " + input_name)
else:
name_list.append(input_name)
print("Hi " + input_name + ", Nice too meet you for the first time.")
# Troubleshoot
print(name_list)
if str(input("Another name? ")) == '':
continue
else:
break
This is what I did. This works with a CSV file.
# Load from file
list = []
listfile = open('list.csv', 'r+')
for name in listfile:
list.append(name[:-1])
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in list:
print("Nice to meet you again " + Name)
else:
print("Hi " + Name + ", Nice too meet you for the first time.")
listfile.write(Name + "\n") #adding to file
# Troubleshoot
print(list)
This will store it to a file, also its not a good practice to use built in functions and utilities as variable names. so I modified the name as lists
try:
with open("listofnames.txt","r") as fd:
lists=eval(fd.read())
except:
lists=[['Bob','Jim',]]
print("Hello, What\'s your name ?")
Name = input("Enter your Name: ")
if Name in lists:
print("Nice to meet you again", Name)
else:
lists.insert(0, Name)
with open("listofnames.txt","w") as f:
f.write(str(lists))
print("Hi " + Name + ", Nice too meet you for the first time.")
# Troubleshoot
print(lists)

registration of clients with list

I need to make a function for client registration where the client's username must be unique. I made a dict and a list where I put everything from my txt file, and now I've been trying to set for and while loops, but it isn't going well:
client_list = []
def c_l():
with open("svi.txt","r") as f:
pieces = ["username","password","name","lastname","role"]
for r in f.readlines():
dicct = {}
bla = r.strip().split("|")
count = 0
for i in bla:
dicct[pieces[count]] = i
count += 1
client_list.append(dicct)
c_l()
def reg():
for r in client_list:
while True:
username = input("Username: ")
if (username == r["username"] ):
print("Username is already taken, please try again: ")
else:
break
password = input("Your password:")
name = input("Your name: ")
lastname = input("Your lastname: ")
client = username + "|" + password + "|" + name + "|" + lastname + "|" + "buyer"
with open("svi.txt","a") as f:
f.write(client)
reg()
When I was typing this function for the first time, I made all in one function, where I opened the file, typed code for unique username and then printed client into that txt file. In that function my while loop worked, because all I had to do is to split the parts of the file and index the right one, then make this while loop, which worked fine. But now I've been told that I have to do it by using dict and list and I tried doing this, I don't know what the problem is with my approach.
You may want to load usernames into a set which ensures uniqueness. Then, in your reg function check whether the new username is in the set, like:
if username in myset:
raise InvalidUsernameError
else:
myset.add(username)

Python script error "function object has not attribute 'firstName'

I'm trying to make a few scripts of my own to practice what I'm learning. But I'm coming up with some issues on the following script.
#!/usr/bin/python
def empInfoEntry():
firstName = input("Enter Employee's First Name: ")
lastName = input("Enter Employee's Last Name: ")
address = input("Enter Employee's Address: ")
city = input("Enter Employee's City: ")
state = input("Enter Employee's Complete State: ")
zip = input("Enter Employee's Zip Code: ")
def empInfo():
empFirstName = empInfoEntry.firstName
empLastName = empInfoEntry.lastName
print (empFirstName + " " + empLastName)
empAddress = empInfoEntry.address
print (empAddress)
empCity = empInfoEntry.city
empState = empInfoEntry.state
empZip = empInfoEntry.zip
print (empCity + ", " + empState + " " + empZip)
empInfoEntry()
empInfo()
According to the error "unhandled AttributeError "'function; object has no attribute 'firstName'"
I've looked it up but most of the results I find are quite complex and confusing to grasp my issue here.
I know that when this script runs it starts with empInfoEntry()
It works since I can type all the info in.
however, empInfo() seems to give me that function error. I have tried also using a simple print (firstName) although I know that it's outside of the function. Even when I append it to print (empInfoEntry.firstName) it gives me an error.
I can imagine it's because there is no return but i'm still a bit confused about returns as simple as people claim.
Any eli5 responses would be appreciated but a full explanation will work as well.
Thanks.
Also using python 3.4 and eric 6 on windows 8
Firstly, try to use raw_input() instead of input().
According to the official documentation, input() is actually eval(raw_input()). You might want to know what is eval(), check the documentation, we do not discuss it here. Sorry I thought it was Python 2.
As it seems you are not far from start learning Python, I would not write a class for you. Just using functions and basic data structures.
If you are interested, check pep8 for the naming convention in Python.
#!/usr/bin/python
def enter_employee_info_and_print():
# use a dictionary to store the information
employee_info = {}
employee_info['first_name'] = input("Enter Employee's First Name: ")
employee_info['last_name'] = input("Enter Employee's Last Name: ")
employee_info['address'] = input("Enter Employee's Address: ")
employee_info['city'] = input("Enter Employee's City: ")
employee_info['state'] = input("Enter Employee's Complete State: ")
employee_info['zip'] = input("Enter Employee's Zip Code: ")
first_name = employee_info['first_name']
last_name = employee_info['last_name']
# pay attention that there is no space between `print` and `(`
print(first_name + " " + last_name)
address = employee_info['address']
print(address)
city = employee_info['city']
state = employee_info['state']
zip = employee_info['zip']
print(city + ", " + state + " " + zip)
# use this statement to run a main function when you are directly running the script.
if __name__ == '__main__':
enter_employee_info_and_print()
Try this. I think this is the sort of thing your'e looking for.
class InfoEntry(object):
def __init__(self):
self.first_name = input("Enter your first name:")
self.last_name = input("Enter your last name:")
def __str__(self):
return self.first_name + " " + self.last_name
me = InfoEntry()
print(me)
Although functions can have attributes, when you want something to hold information, the format of which you know a priori, the thing you want is a class

Categories

Resources