Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

python - Converting a program that takes in a .txt file and modifying to functions

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your method-breakdown is a bit off.

For example this line:

print_grades(name, line)

Will use the last value of line from the for loop above. Which will always be "Anthony"

You can try to pass the values from method to method as below:

from sys import argv


def get_names(my_file):
    names = []
    for line in my_file:
        names.append(line.split()[0])
        print('
Names of students who have written tests:')
        print(*sorted(names), sep=' ')
    return names


def get_and_check_name(names):
    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
        return name, name_print


def print_scores(f, name, name_print):
    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)


def process_marks(f):
    While True:
        names = get_names(f)
        name, name_print = get_and_check_name(names)
        f.seek(0)
        print_scores(f, name, name_print)
        yes_no = input('
Do again for another student?')
        if yes_no == 'n':
            break
        continue 

with open(argv[1]) as f:
    process_marks(f)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...