Completely stuck on functions....
I have a .txt file:
Bronson 90 85 75 76
Conor 90 90 90 90
Austyn 50 55 32 75
Mark 96 95 85 85
Anthony 85 85 85 85
And I'm trying to take this code (below). And turn it into functions to produce the same output:
with open(argv[1]) as f:
names = []
for line in f:
names.append(line.split()[0])
print('
Names of students who have written tests:')
print(*sorted(names), sep=' ')
# prompt user to input which student you want to view
name = input('Enter name of student whose test results '
'you wish to see: ')
if name not in names:
print('
No test data found for ', name)
input("Press Enter to continue ...")
else:
name_print = "
Summary of Test Results for " + name
# print test scores of the student selected
with open(argv[1]) as f:
for line in f:
parts = line.split()
if parts[0] == name:
print(name_print)
print('=' * ((len(name_print)) - 1))
test_scores = ' '.join(parts[1:])
print('Test scores: ', end=' ')
print(test_scores)
Currently 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
===================================
Test scores: 85 85 85 85
Number of tests written .................. 4
I want to make it run on one main() module using process_marks(f)
:
from functions import process_marks
def main():
try:
f = open(argv[1])
except FileNotFoundError:
print("
File ", argv[1], "is not available")
exit()
process_marks(f). #The program essentially runs in this function with help from helpers
f.close()
main()
This is what I currently have:
def process_marks(f):
names = []
for line in f:
names.append(line.split()[0])
print('
Names of students who have written tests:')
names = sorted(names)
print(*names, sep=' ')
name = input('Enter name of student whose test results '
'you wish to see: ')
check_name(name, names)
print_grades(name, line)
def check_name(name, names):
if name not in names:
print('
No test data found for ', name)
input("Press Enter to continue ...")
else:
name_print = "
Summary of Test Results for " + name
print(name_print)
print('=' * ((len(name_print)) - 1))
def print_grades(name, line):
test_scores = ' '.join(line[1:])
print('Test scores: ', end=' ')
print(test_scores)
This is what outputs using above code:
Names of students who have written tests:
Anthony Austyn Bronson Conor Mark
Enter name of student whose test results you wish to see: Mark
Summary of Test Results for Mark
================================
Test scores: n t h o n y 8 5 8 5 8 5 8 5
I don't want to go to far away from the current code I have (i want to use lists etc because id like to eventually include averages, max, min etc. However, I have been grinding over this for a while having obvious problems getting the code to access the line that corresponds to the name.
See Question&Answers more detail:
os