Question

In: Computer Science

Write a program that loops, prompting the user for their full name, their exam result (an...

Write a program that loops, prompting the user for their full name, their exam result (an integer between 1 and 100), and then writes that data out to file called ‘customers.txt’. The program should check inputs for validity according to the following rules:

  • First and last names must use only alphabetical characters. No spaces, hyphens or special characters. Names must be less than 20 characters long.
  • Exam result (an integer between 1 and 100 inclusive)

The file should record each customers information on a single line and the output file should have the following appearance.

Nurke Fred 58

Cranium Richard 97

Write a second program that opens the ‘customers.txt’ file for reading and then reads each record, splitting it into its component fields and checking each field for validity.

The rules for validity are as in your first program, with the addition of a rule that specifies that each record must contain exactly 3 fields.

Your program should print out each valid record it reads.

The program should be able to raise an exception on invalid input, print out an error message with the line and what the error was, and continue running properly on the next line(s).

Solutions

Expert Solution

Thanks for the question.

Here is the completed code for this problem. 

Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. 

If you are satisfied with the solution, please rate the answer. 

Thanks

===========================================================================

# function takes in a name and validate if it meets all
# conditions , return True if all conditions are met False otherwise
def validateName(name):
    if len(name) > 20:
        print('Name should be less than 20 characters.')
        return False
    for letter in name.lower():
        if letter < 'a' or letter > 'z':
            print('Name contains invalid characters.')
            return False
    return True


# function takes in a score as string value
# validate the score is an integer and ranges between 1 and 100
# returns True if all conditions are meet False otherwise
def validateScore(score):
    try:
        result = int(score)
        if result < 1 or result > 100:
            print('Exam result should be between 1 and 100')
            return False
        else:
            return True
    except:
        print('Invalid number entered.')
        return False

# keep asking input from user until input meets all the condition
def getName(message):
    while True:
        name = input(message).lower()
        if validateName(name):
            return name.title()

# keep asking valid score from user until input meets all the condition
def getScore():
    while True:
        score = input('Enter exam result: ')
        if validateScore(score):
            return int(score)

# takes in the list of records user entered, the filename
# and saves the data in the file
def save_to_file(records, filename):
    with open(filename, 'w') as outfile:
        for record in records:
            outfile.write('{} {} {}\n'.format(record[0], record[1], record[2]))
    print('Data written to file: {} successfully.'.format(filename))

# reads data from file and validates the record contains valid entries
def read_file(filename):
    with open(filename, 'r') as infile:
        for line in infile.readlines():
            values = line.strip().split()
            if len(values) != 3:
                print('ERROR: {} contains not exactly 3 values'.format(line))
            elif validateName(values[0].strip()) and validateName(values[1].strip()) and validateScore(
                    values[2].strip()):
                print('VALID RECORD: {} {} {}'.format(values[0], values[1], values[2]))
            else:
                print('ERROR: {} contains either invalid name or exam score.'.format(line))

# main function , execution starts here
def main():
    records = []
    filename = 'customers.txt'
    while True:
        firstname = getName('Enter first name: ')
        lastname = getName('Enter last name: ')
        score = getScore()
        records.append([firstname, lastname, score])
        add_another = input('Do you want to add another record (Y/N): '.upper())
        if add_another == 'N':
            break

    save_to_file(records, filename)
    read_file(filename)


main()

====================================================================


Related Solutions

Python Write a program that loops, prompting the user for their full name, their exam result...
Python Write a program that loops, prompting the user for their full name, their exam result (an integer between 1 and 100), and then writes that data out to file called ‘customers.txt’. The program should check inputs for validity according to the following rules: First and last names must use only alphabetical characters. No spaces, hyphens or special characters. Names must be less than 20 characters long. Exam result (an integer between 1 and 100 inclusive) The file should record...
In.java Write down a program that asks the user for their full name given in the...
In.java Write down a program that asks the user for their full name given in the format first last. The program will do the necessary processing and print the name in a table with 3 columns: Last, First, Initials. Requirements/Specifications... Your program run must be identical with the one shown as an example (both in how it reads the input and it on what it prints). The table must have the top and bottom lines as shown. The columns for...
Write a C program that performs the following: Asks the user to enter his full name...
Write a C program that performs the following: Asks the user to enter his full name as one entry. Asks the user to enter his older brothers’ names each at a time (the user should be instructed by the program to enter NULL if he does not have any older brother). Asks the user to enter his younger brothers’ names each at a time (the user should be instructed by the program to enter NULL if he does not have...
Write a C program that loops and asks a user to enter a an alphanumeric phone...
Write a C program that loops and asks a user to enter a an alphanumeric phone number and converts it to a numeric one. No +1 at the beginning. You can put all code in one quiz1.c file or put all functions except main in phone.c and phone.h and include it in quiz1.c Submit your *.c and .h files or zipped project */ #pragma warning (disable: 4996) //windows #include <stdio.h> #include <string.h> #include <stdbool.h> #include <ctype.h> enum { MaxLine =...
Python: Write a program that asks the user for the name of a file. The program...
Python: Write a program that asks the user for the name of a file. The program should display the contents of the file line by line.
Write a program In python of Jupiter notebook (using loops) that prompts the user to enter...
Write a program In python of Jupiter notebook (using loops) that prompts the user to enter his/her favorite English saying, then counts the number of vowels in that (note that the user may type the saying using any combination of upper or lower case letters). Example: Enter your favorite English saying: Actions speak LOUDER than words. Number of wovels: 10
Write a program that asks the user to enter the name of a file, and then...
Write a program that asks the user to enter the name of a file, and then asks the user to enter a character. The program should count and display the number of times that the specified character appears in the file. Use Notepad or another text editor to create a sample file that can be used to test the program. Sample Run java FileLetterCounter Enter file name: wc4↵ Enter character to count: 0↵ The character '0' appears in the file...
Tail of a File, C++ Program. write a program that asks the user for the name...
Tail of a File, C++ Program. write a program that asks the user for the name of a text file. The program should display the last 10 lines, or all lines if less than 10. The program should do this using seekg Here is what I have so far. #include<iostream> #include<fstream> #include<string> using namespace std; class File { private:    fstream file;    string name; public:    int countlines();    void printlines(); }; int File::countlines() {    int total =...
Write a short program that asks the user for a sentence and prints the result of...
Write a short program that asks the user for a sentence and prints the result of removing all of the spaces. Do NOT use a built-in method to remove the spaces. You should programmatically loop through the sentence (one letter at a time) to remove the spaces.
Write a C program that loops and asks you every time to enter the name of...
Write a C program that loops and asks you every time to enter the name of a text file name, then it will read the file and perform statistics on its contents and display the results to the screen and to an output file called out.txt. The input files can be any text file. The program should calculate these integers as it reads character by character as we did in the last class example filecopy and make use of the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT