Joseph Lastname
Joseph Lastname

Reputation: 1

Reading a file function only returns first line in file after applying try/except, but program worked as intended without it

Okay so my problem is that i need to define a function that reads a file of numbers (assume everything in the file is a number) and then print any odd number that isn't divisible by 3. My professor asked specifically for try/except in this program. my code is

import sys

def threething(name):
    try:
        file = open(name, 'r')
    except:
        sys.exit("Bad file name for some odd reason idk.")
    data = file.readlines()
    for line in data:
        o = int(line)
        if o % 2 == 1:
            if o % 3 != 0:
                return o
    file.close()
filename = input("file name pls: ")
print(threething(filename))

and the text file im using just has

1
2
3
4
5
6
7
8
9

in it. Before my code worked fine without the try/except and printed 1, 5 and 7 like it's supposed to but I can't seem to figure out how to make it work with try/except.

Upvotes: 1

Views: 42

Answers (1)

brandizzi
brandizzi

Reputation: 27060

I doubt the try/except statement has anything to do with the change of behavior. My bet is that, as @theausome noted, you replaced print(o) with return o without noticing.

The problem is, the return statement interrupts the execution of a function. As a simplified example, consider the code below:

def f():
    print("returning 1")
    return 1
    print("returning 2")
    return 2
    print("returning 3")
    return 3

print(f())

If you call it, you will get this output:

returning 1
1

Why it only executed the first print() of the function? Because after a return, a function stops executing. So, when you returned, the other values were not checked, only the first one was given to the print function.

Try to use print(o) instead of return o. In this case, you will not need to print the return of threething():

import sys

def threething(name):
    try:
        file = open(name, 'r')
    except:
        sys.exit("Bad file name for some odd reason idk.")
    data = file.readlines()
    for line in data:
        o = int(line)
        if o % 2 == 1:
            if o % 3 != 0:
                print(o)
    file.close()
filename = input("file name pls: ")
threething(filename)

Upvotes: 1

Related Questions