Question

In: Computer Science

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

1.

'''

Python version : 2.7

Python program to input the firstname, lastname and exam result of customers and output to file customers.txt

'''

# input of number of data to input

n = int(raw_input('Enter the number of records to input : '))

# open file in write mode

file = open('customers.txt','w')

i=0

# loop to input n customer data

while (i < n):

               print('Enter details for customer %d ' %(i+1))

               # input firstname

               fname = raw_input('Enter first name : ')

               # validate first name

               if(fname.isalpha() and len(fname) <= 20):

                              # input last name

                              lname = raw_input('Enter last name : ')

                              # validate last name

                              if(lname.isalpha() and len(lname) <= 20):

                                            

                                             try:

                                                            # input exam result

                                                            result = int(raw_input('Exam result (an integer between 1 and 100 inclusive) : '))

                                                           

                                                            # validate exam result's range

                                                            if(result > 0 and result <=100):

                                                                           # if all valid values write to file

                                                                           if(i == 0):

                                                                                          file.write(lname+' '+fname+' '+str(result))

                                                                           else:

                                                                                          file.write('\n'+lname+' '+fname+' '+str(result))

                                                                           i = i + 1

                                                            # invalid exam result

                                                            else:

                                                                           print('Value of result : '+str(result) +' is invalid')

                                             except ValueError as e: # invalid exam result

                                                            print('Value of result : '+str(e)+' is invalid')

                              else: # invalid last name

                                             print('Value of last name : '+lname +' is invalid')

               else: # invalid first name

                              print('Value of first name : '+fname +' is invalid')

#close the file

file.close()                         

              

#end of program             

Code Screenshot:

Output:

File:

2.

'''

Python version : 2.7

Python program to read firstname , lastname and exam result from customers.txt and validate the fields

and output valid customers and for invalid customers ,

output the reason for the record being invalid and the customer data

'''

# open the input file

file = open('customers.txt','r')

# read a line from file

line = file.readline()

# read till end of file

while(line):

              

               try:

                              # split the data read from file using space as the delimiter

                              # and strip is used to remove any trailing or leading whitespace present in line

                              data = line.strip().split()

                              # validate the number of fields read

                              if(len(data) == 3):

                                             # validate lastname

                                             if(data[0].isalpha() and len(data[0]) <= 20):

                                                            # validate firstname

                                                            if(data[1].isalpha() and len(data[1]) <= 20):

                                                                           result = int(data[2])

                                                                           # validate exam result

                                                                           if result > 0 and result <=100:

                                                                                          print(line.strip())

                                                                           else:

                                                                                          raise ValueError('Value of result : '+str(result)+' is invalid')

                                                            else:

                                                                           raise ValueError('Value of first name : '+data[1]+' is invalid')

                                             else:

                                                            raise ValueError('Value of last name : '+data[0]+' is invalid')

                              else:

                                             raise ValueError('There should be exactly 3 fields')

                              line = file.readline()

               except ValueError as e:

                              print(e)

                              print(line)

#close the file                   

file.close()                         

#end of program                                           

Code Screenshot:

Output:

Input file:

Output:


Related Solutions

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
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...
Python English algorithm explanation Write a program that asks the user for the name of a...
Python English algorithm explanation Write a program that asks the user for the name of a file in the current directory. Then, open the file and process the content of the file. 1)If the file contains words that appear more than once, print “We found duplicates.” 2)If the file does not contain duplicate words, print “There are no duplicates.”
Python English algorithm explanation Write a program that asks the user for the name of a...
Python English algorithm explanation Write a program that asks the user for the name of a file in the current directory. Then, open the file and process the content of the file. 1)If the file contains words that appear more than once, print “We found duplicates.” 2)If the file does not contain duplicate words, print “There are no duplicates.”
In Python write a program that prompts the user for a file name, make sure the...
In Python write a program that prompts the user for a file name, make sure the file exists and if it does reads through the file, count the number of times each word appears and then output the word count in a sorted order from high to low. The program should: Display a message stating its goal Prompt the user to enter a file name Check that the file can be opened and if not ask the user to try...
Write a Python program that has the user enter their name.   Using the user's name calculate...
Write a Python program that has the user enter their name.   Using the user's name calculate the following: 1. How many letters are in the user's name? 2. Print the user's name in REVERSE both in capital letters and lowercase letters 3. Print the ASCII value for each letter of the user's name. 4. Print the SUM of all of the letters of the user's name (add each letter from #3)
Python Code: Write a program to prompt the user to enter a first name, last name,...
Python Code: Write a program to prompt the user to enter a first name, last name, student ID, number of hours completed and GPA for 5 students. Use a loop to accept the data listed below. Save the records in a text file. Write a second program that reads the records from your new text file, then determines if the student qualifies for Dean’s list or probation. Display the records read from the file on screen with appropriate headings above...
Write a Python program that asks the user to enter a student's name and 8 numeric...
Write a Python program that asks the user to enter a student's name and 8 numeric tests scores (out of 100 for each test). The name will be a local variable. The program should display a letter grade for each score, and the average test score, along with the student's name. Write the following functions in the program: calc_average - this function should accept 8 test scores as arguments and return the average of the scores per student determine_grade -...
PYTHON Write a program that asks the user to enter a student's name and 8 numeric...
PYTHON Write a program that asks the user to enter a student's name and 8 numeric assignment scores (out of 100 for each assignment). The program should output the student's name, a letter grade for each assignment score, and a cumulative average for all the assignments. Please note, there are 12 students in the class so your program will need to be able to either accept data for 12 students or loop 12 times in order to process all the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT