Code 0 1 in python

I am trying to add the return code and getting error message.

if os.stat(file).st.size == 0:
    return 0
    return 1

What error are you getting? The first thing I spot is that you are capitalizing If when it should be if, so that is probably one problem, but posting your actual error will allow others to help better.

Sorry that if is a typo error.

SyntaxError: 'return' outside function

Is this what you’re trying to do ?

def some_function(**args):
    if os.stat(args['file_name']).st_size == 0:
        return True
        return False

file = 'some_file_name'

… the point being that you should be using .st_size not .st.size, unless that’s OS specific, but don’t think it is.

Also, I prefer to use True and False, rather than 1 and 0 for this kind of operation, as it’s more ‘human friendly’.

Are you trying to get return code like in C main function?
If so you should replace return 0 with sys.exit(0)
See more about here

Are you trying to issue an exit status upon terminating execution of the program? If so, does this accomplish what you need?:

sys.exit(os.stat(file).st_size and 1)

That line would replace the if and else blocks from your original post. However, some might regard the meaning of that line as cryptic. If you feel it would be clearer to use the conditional blocks, this might serve the purpose:

if os.stat(file).st_size == 0:

I have tried the below example and i have executed as below but still 0 or 1 is not returned.

Rc= python3 progname input
echo $rc

But none of the value is not recieved.

if os.stat(file).st_size == 0:

Return codes are stored in $? and (AFAIK) have to be extracted from that:

dev-311 ❯ python -c "import sys; sys.exit(1)"

dev-311 ❯ echo $?

The testing described below was performed on a MacBook Air with the Ventura operating system.

The following code was stored in

import os
import sys
filename = input("Name of file: ")
if os.stat(filename).st_size == 0:

Two additional files were used. One was named laden_swallow.txt, and contained the following single line of text, so its size was 3:


The other file was named unladen_swallow.txt, and was empty, so its size was 0.

With those files in place, the following interactive session was performed on the terminal:

% python
Name of file: laden_swallow.txt
% echo $?
% python
Name of file: unladen_swallow.txt
% echo $?

As we see, the program did return the desired codes to the system.

It works now.