[Tutor] Using try, except else inside function definition

Manprit Singh manpritsinghece at gmail.com
Wed Oct 20 14:29:46 EDT 2021


Dear Sir,

Kindly look at following examples:
1) This example consists of a function that is written to read a file and
print count of number of words in a file, and if the file not exists this
it should print "File  not exists"

def count_words(filename):
    try:
        with open(filename) as fileobj:
            content = fileobj.read()

    except FileNotFoundError:
        print(f'Sorry the file {filename} not exists')

    else:
        words = content.split()
        cntwd = len(words)
        print(f'The file {filename} has {cntwd} words')

file_name = "fileread.txt"
count_words(file_name)

This is working fine, my question is can we place try, except & else blocks
inside the function definition as done above.

In the second example I have written a function that takes a list and an
arbitrary object as an argument . The function must return the index of
first occurrence of that object in the list, if the object is not present
in the list the function should return -1

def indexofelement(seq, ele):
    try:
        if ele not in seq:
            raise ValueError

    except ValueError:
        return -1

    else:
        for ind, val in enumerate(seq):
            if val == ele:
                return ind



lst = [1, 3, 5, 7, 3, 5, 7]
num = 7
ans = indexofelement(lst, num)
print(ans)    # Gives the correct answer = 3

lst = [1, 3, 5, 7, 3, 5, 7]
num = 8
ans = indexofelement(lst, num)
print(ans)   # Gives the correct answer = -1

In this second example i am returning values from except block as well as
else block,  Except block will only work when exception occurs (when the
object is not present) it will return -1 else the function will return the
index of first occurence of the object in list due to esle block.

Returning values in this way from the function is ok ?

Need your guidance

Regards
Manprit Singh


More information about the Tutor mailing list