Can someone help...
My driver file is here:
from functions import process_marks
def main():
try:
f = open(argv[1])
except FileNotFoundError:
print("\nFile ", argv[1], "is not available")
exit()
process_marks(f)
f.close()
main()
I'm trying to modify process_marks(f) to run my code. and produce this (from file that runs without functions):
Names of students who have written tests:
Anthony Austyn Bronson Conor Mark
Enter name of student whose test results you wish to see: Anthony
Summary of Test Results for Anthony
===================================
Test scores: 85 85 85 85
Number of tests written .................. 4
This is what I currently have:
names = []
name_print = "\nSummary of Test Results for "
def process_marks(file_name):
names
for line in file_name:
names.append(line.split()[0])
print('\nNames of students who have written tests:')
print(*sorted(names), sep=' ')
name = input('Enter name of student whose test results '
'you wish to see: ')
check_name(name)
parts = line.split()
if parts[0] == name:
print_scores(name)
def check_name(person):
if person not in names:
print('\nNo test data found for ', person)
input("Press Enter to continue ...")
else:
print(name_print + person)
def print_scores(person, parts):
print('=' * ((len(name_print)) - 1))
test_scores = ' '.join(parts[1:])
print('Test scores: ', end=' ')
print(test_scores)
Which outputs:
Names of students who have written tests:
Anthony Austyn Bronson Conor Mark
Enter name of student whose test results you wish to see: Anthony
Summary of Test Results for Anthony
I need help making print_scores() function work in process_marks().
Can someone see where my errors lie?
Your error (mainly) lies in the fact that you are comparing the input name to the last row of the file. This is because you check if parts[0] == name where parts = line.split(). This means the parts are of the last row of the file always - no matter what name provided.
To fix this, I would start by a better way of storing your data. Right now you are just saving the names in a list. But what about the grades? I think a better solution would be to use a dict. So start by changing to:
names = {} # instead of []
Now you want to fill that dict with the names as keys (keeps the logic similar as with the list) and the list of grades as the value for that key. So your file parsing can look like:
for line in file_name:
elements = line.split()
names[elements[0]] = elements[1:]
# names now look like: {'Anthony': ['85', '85', '85', '85'], 'Conor': [...], ... }
Now another thing is that you call the check_name function but then make another check in process_marks. This seems redundant. I would change the ceck_name function to return a boolean indicating if the name is ok or not:
def check_name(person):
if person not in names:
print('\nNo test data found for ', person)
input("Press Enter to continue ...")
return False
else:
print(name_print + person)
return True
And in process_marks you can use it as:
name = input('Enter name of student whose test results you wish to see: ')
if check_name(name):
print_scores(name)
Lastly, regarding the parts issue. Now you have the grades stored in names along with the matching name they belong to. So all we have left to do is change print_scores to take only one argument grades and use that instead of parts, and from process_marks just call it:
print_scores(names[name])
A view of a possible complete code:
names = {}
name_print = "\nSummary of Test Results for "
def process_marks(file_name):
with open(file_name) as f:
for line in f:
elements = line.split()
names[elements[0]] = elements[1:]
print(names)
print('\nNames of students who have written tests:')
print(*sorted(names), sep=' ')
name = input('Enter name of student whose test results you wish to see: ')
if check_name(name):
print_scores(names[name])
def check_name(person):
if person not in names:
print('\nNo test data found for ', person)
input("Press Enter to continue ...")
return False
else:
print(name_print + person)
return True
def print_scores(grades):
print('=' * (len(name_print) - 1))
test_scores = ' '.join(grades)
print('Test scores: ', end=' ')
print(test_scores)
Related
I don't expect any coding answers, more just guidance. For my project I have to date-mine apple stock prices from a csv-file and implement it in my code. I provided a sample output below.
https://imgur.com/rPOPN1I
Right now, I am not getting any error messages but my code is not posting the columns requested from the csv.file. Are my definitions at fault or am I missing something else?
# Project No.: 5
# Author: burntchickennuget
# Description: making definitions, reading from a .csv file, validating input, data-mining,
f_list = list()
file_object = ()
my_tot = dict()
new_list = list()
def get_input_descriptor():
while True:
filename = input("Enter a file name: ")
if filename == 'table.csv':
with open(filename, "r") as infile:
infile.readlines()[1:]
# for line in lines:
# print(line.rstrip())
break
else:
print("Bad file name, try again")
return filename
def get_data_list(file_object, column_number):
dict = {}
for val in file_object:
date = val.split(",")[0]
data = float(val.split(",")[column_number])
dict[date] = data
return dict.items()
def average_data(new_list):
for date, price in new_list:
my_tot[date] = my_tot.get(date, 0) + float(price)
my_times[date] = my_times.get(date, 0) + 1
for key in my_tot:
f_list.append((float(my_tot[key] / my_times[key]), key))
def main():
get_input_descriptor()
column_number = int(input("Which column: "))
date_list = get_data_list(file_object, column_number)
final_list = average_data(date_list)
x = sorted(f_list)
print('Lowest 6:')
for tup in x[:6]:
print
tup[0], tup[1]
print('Highest 6:')
x = sorted(f_list, reverse=True)
for tup in x[:6]:
print
tup[0], tup[1]
while 1:
flag = input("do you want to continue? ")
if flag == '' or not flag[0].lower() in ['y', 'n']:
print("Please answer with a yes or no")
else:
break
if flag[0].lower() == 'y':
column = input("Which column: ")
print(column)
if flag[0].lower() == 'n':
print("Bye!")
if __name__ == "__main__":
main()
What can I try next?
Take a look around your get_input_descriptor method.
What are you returning from the method?
Where is the returned information being stored in the main method (is it being stored at all?)
What are you doing with the lines that you read from the file?
What is the file_object you are passing into get_data_list
My main advice would be to add print everywhere for debugging. See what it stored in your variables at different points in the program and see where a variable doesn't contain what you think it should
I want to create a python lookup function for students. I have a tab delimited file with ID and students name. I want to create a lookup program such that entering either a student's name or ID will return name of the student and student ID if a match has been found.
So far I have imported the data successfully. Snippet of data is shared. Having trouble defining a function. I am sharing my code below:
infile = open("D:/work/student_id.txt", "r")
def lookup():
word =raw_input("code to lookup: ")
print ("\n")
n = elements.index(word)
x = elements[n][0]
y = elements[n][0]
if word == x:
print x, ":", y, "\n"
else:
print("That code does not exist")
lookup()
I searched online(stackoverflow-found post by Erik and Alexander, I tried to model my code like theirs but still no help; O'riley books on Python) for help regarding creation of lookup function but they all involved writing the data out. But I found no guidance on creating a lookup function for an imported tab delimited file. I hope this will help others as well. Any advice?
What version of Python are you using?
Python 3 uses input(), not raw_input().
As your file is tab-separated you can use the csv function.
import csv
students = {}
search = input()
found = None
with open('student_id.txt', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
for row in reader:
students[row[0]] = row[1]
print(students)
for i in students.keys():
if search == i:
found = search + " " + students[i]
else:
if search == students[i]:
found = i + " " + students[i]
if found == None:
print("Not found")
else:
print(found)
I am new to coding and have a list of lists that I need to search.
I want to see what lists contained in the larger list have the variable full_choice as the 3rd item in the sequence.
All lists that contain third_choice i need to print to a txt file.
the code below works and adds exactly what I need it to to the file, however I need the function to start again if there is no match for the variable full_choice.
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I have tried inserting an else: at the end of the code however while that has ends up creating the file it doesn't write anything to it.
Tried to fix your indentation. I'm guessing you wanted something like this:
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I just moved the else block forward to align with the if block you had a few lines before.
As #Haken Lid suspected, please fix indentation:
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').
replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I have a text file set out in this layout:
Greg,Computer Science,Hard,5
Alex,Computer Science,Medium,2
Fiona,Maths,Easy,0
Cassie,Maths,Medium,5
Alex,Maths,Medium,1
In my program I want the user to be able to choose a certain name and see their results. My code for this looks like this:
name = input("Enter name: ")
for each in file:
each = each.split(",")
realName = each[0]
subject = each[1]
difficulty = each[2]
score = each[3]
if name == realName:
print(subject, difficulty, score)
break
else:
print()
print("Invalid name.")
name = input("Re-enter your name: ")
A few things are wrong with it though and I can't figure out what to do:
If the user entered "Alex", only one of his results will be displayed.
If a wrong name is inputted once, every other name inputted will return as "Invalid".
If the correct name is inputted and the results are displayed, the program will continue to ask for a name.
Does anybody have any solutions to these problems?
If you're going to query your file repeatedly, I'd recommend pre-loading your data once into a dictionary, and printing data as and when needed. Something like this:
data = {}
with open('file.txt', 'r') as file:
for line in file:
realName, subject, difficulty, score = each.split(',')
data.setdefault(realName, []).append((subject, difficulty, score))
while True:
name = input('>>> ')
data.get(name, 'Invalid Name')
This solves problems one and two. If you just want to break after the first valid name is input, you can query the return value of dict.get:
while True:
name = input('>>> ')
result = data.get(name)
if result:
print(result)
break
print('Invalid name')
This solves problem three.
You're better off using the csv module since your file syntax is simple CSV.
Then you can loop through the rows (each row will be an array of values).
import csv
def parse_csv_file(csv_file, operation, value, index):
with open(csv_file, newline='') as file:
reader = csv.reader(file, delimiter=',',
quotechar='|')
return operation(reader,
value, index)
def find_first_row(csv_reader, value, index):
for row in csv_reader:
if row[index] == value:
return row
return None
def main():
query = input('Enter a name: ')
result = parse_csv_file('file.csv',
find_first_row,
query, 0)
if result:
print(result)
else:
print('Nothing found!')
main()
I need to create a program that saves people's information e.g. their name in a text file depending on the first letter of their surname so if their surname starts with a K it goes into MyFile1.
I need it to loop like I have done because it's an unknown number of people however I want each person to be written in a different line in the text file is there a way to do this.
The code at the bottom puts each separate information into a new line and I don't want that I want each different person to be in a new line.
MyFile1 = open("AL.txt", "wt")
MyFile2 = open("MZ.txt", "wt")
myListAL = ([])
myListMZ = ([])
while 1:
SurName = input("Enter your surname name.")
if SurName[0] in ("A","B","C","D","E","F","G","H","I","J","K","L"):
Title = input("Enter your title.")
myListAL.append(Title);
FirstName = input("Enter your first name.")
myListAL.append(FirstName);
myListAL.append(SurName);
Birthday = input("Enter birthdate in mm/dd/yyyy format:")
myListAL.append(Birthday);
Email = input("Enter your email.")
myListAL.append(Email);
PhoneNumber = input("Enter your phone number.")
myListAL.append(PhoneNumber);
for item in myListAL:
MyFile1.write(item+"\n")
elif SurName[0] in ("M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"):
Title = input("Enter your title.")
myListMZ.insert(Title);
FirstName = input("Enter your first name.")
myListMZ.append(FirstName);
myListMZ.append(SurName);
Birthday = input("Enter birthdate in mm/dd/yyyy format:")
myListMZ.append(Birthday);
Email = input("Enter your email.")
myListMZ.append(Email);
PhoneNumber = input("Enter your phone number.")
myListMZ.append(PhoneNumber);
line.write("\n")
for item in myListMZ:
MyFile2.write(line)
elif SurName == "1":
break
MyFile1.close()
MyFile2.close()
You are looking for join.
When you have a list of items you can join them in a single string with.
l = ['a', 'b', 'c']
print(''.join(l))
produces
abc
You can not only use the empty string but also another string which will be used as separator
l = ['a', 'b', 'c']
print(', '.join(l))
which now produces
a, b, c
In your examples (for example the first write)
MyFile1.write(','.join(MyListAL) + '\n')
If you happen to have something in the list which is not a string:
MyFile1.write(','.join(str(x) for x in MyListAL) + '\n')
(you can also use map, but a generator expression suffices)
Edit: adding the map:
MyFile1.write(','.join(map(str, MyListAL)) + '\n')
In your case I would rather use a list of dictionaries, where a person with all its infos is a dictionary. Then you can convert it to a JSON string, which is a standard format for representing data. (Otherwise you need to define your own format, with delimiters between the items.)
So something like this:
import json # at the top of your script
# I would create a function to get the information from a person:
def get_person_input():
person = {}
person["surname"] = input("Surname: ")
person["title"] = input("Title: ")
person["email"] = input("Email: ")
# TODO: do whatever you still want
return person
# Later in the script when you want to write it to a file:
new_line = json.dumps( person )
myfile.write( new_line + "\n" )
Parsing a json is also very easy after all:
person = json.loads(current_line) # you can handle exception if you want to make sure, that it is a JSON format
You can use in your code for the decision in which array it should be written something like this:
SurName = input("Enter your surname name.")
if SurName[0] <= 'L':
...
else:
...
This will make your script more clear and robust.