-1

This program has to analyze student numbers and if they are correct write them to one list and if not write them to another list. They are correct if they have eight digits and contain only numbers.

I however have no idea what to type when it comes to the try and except part.

If anyone could help, I would greatly appreciate it!

Valid_file = "ValidNumbers.txt"
Invalid_file = "InvalidNumbers.txt"
Data_file = "Data.txt"

def analyse_students(Data_file):
    lenth = len(Data_file)
    total = 0
    try:
    
    except: 
    
    return 0
    
def read(Data_file):
    count = 0
    student_list = []
    try:
        open(Data_file)
    except:
        print("Couldn't append file", Valid_file)
    return count, student_list

def write(student, status):
    if status:
        try:
            open(Data_file)
        except:
            print("Couldn't append file", Invalid_file)
    
count, student_list = read(Data_file)

print("Number of lines read", count)

for student in student_list:

    print("See output files")
Anshika Singh
  • 994
  • 12
  • 20
  • Please upload a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – Cblopez May 28 '20 at 10:14
  • What do you mean `i however have no idea what to type when it comes to the try except part` – Ahmet May 28 '20 at 10:17
  • What error did you get? syntax error try-except or not getting the desired result? – Rebai Ahmed May 28 '20 at 10:26
  • I didn't get an error It just does nothing. I just have no idea what to type to make the program work. The data_file contains a lsit of numbers that I need to sort but I don't know how to test the so that the numbers can be sent to their respective lists. – Pieter Booysen May 28 '20 at 10:53
  • You need to use a context manager in order to write or open a file. – user1720740 May 28 '20 at 15:58
  • What is `total=0` here? Do you want to append the correct numbers into a list and return that list? – Anshika Singh Jul 11 '20 at 09:49

2 Answers2

1

Okey, so there a few things that need to be explained where.

What is try-except used for?

It is used for catching errors raised by the program. Any code susceptible of raising an exception is inserted inside a try statement, and below that statement, any number of except statements with any single error that you want to catch.

try:
    user_input = int(input('Give me a number: '))
except ValueError:
    print('That is not a number!')

When should i use try-except?

It is not a good practice to use a try-except on every single line of code that could raise an error, because that may be half of it, or more. So when shall you use it? Simple, ask this question: Do I want to do any custom action with that error being raised? If the answer is yes, you are good to go.

Catching Exception or empty except

As I see in your example, you are using an empty except. Using an empty except statement will catch every single error raised that the surrounded code, which is similar (but not the same) as catching Exception. The Exception class is the superclass of every single built-in exception in the Python environment that are non-system-exiting (read here) and its generally a bad practice to catch either all exceptions with except: or Exception with except Exception:. Why? Because you are not letting the user (or even you, the programmer) know what error you are handling. For example:

fruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except Exception:
    print('Error!')
    # But wait, are you catching ValueError because the user did not input a number, 
    # or are you catching IndexError because he selected an out of bound array index? 
    # You don't know  

Catching multiple exceptions

Based on the previous example, you can use multiple try-except statements to difference which errors are being raised.

fruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except ValueError:
    print('That is not a number')
except IndexError:
    print('That fruit number does not exist!')  

Grouping exceptions

If there are two particular exceptions that you want to use for a same purpose, you can group them in a tuple:

fruits = ['apple', 'pear', 'banana']
try: 
    selection = fruits[int(input('Select a fruit number (0-2): '))]  
except (ValueError, IndexError):
    print('Invalid selection!')  

Your case

Based on this information, add those try-except blocks to your code, and see what possible errors that could be raised during its execution, asking the previously recommended question Do I want to execute some custom action with this error?

Additionally

  • There are try-except-else statements. See here
  • There are try-except-finally statements. See here
  • You can combine them all in a try-except1-except2...exceptN-else-finally statement.
  • I recommend you get familiar with built-in errors why practicing this!
Cblopez
  • 446
  • 2
  • 12
0

Here is how I understand it:

You want to append the correct student's numbers to a list and if they are wrong, append them in another list. The way to check if the students' numbers are correct is if they are numerals containing 8 digits.

Assuming student in your code refers to the numbers of the students: (use the for loop to iterate through the list of students. I have tried to solve your primary problem: try and except)

def analyse_students(Data_file):
    lenth = len(Data_file)
    total = 0
    try:
        if len(str(student)) == 8 and student in "1234567890":
            #append to a list(correct ones)
        elif not(lenth == 8 and Data_file in "1234567890"):
            #append to another list(wrong ones)  
        else:
            raise ValueError

    except Exception:
        #print something

    return 0

The try catches all the errors and except catches them. Thus we can ourselves raise an error (say ValueError here) and the try will catch that too and send it to except block where the error message will be printed.

The raise keyword raises an exception.

You can define what kind of error to raise, and the text to print to the user.

Hope this was helpful!

Anshika Singh
  • 994
  • 12
  • 20