1

I usually run Python on Google Colab, however I need to run a script in the terminal in Ubuntu.

I have the following script test.py:

#!/usr/bin/env python

# testing a func

def hello(x):
  if x > 5:
    return "good"
  else:
    return "bad"

hello(2)

When executed it fails to return anything. Now I could just replace the return statements with a print statement. However, for other scripts I have, a return statement is needed.

I tried:

python test.py

You see, on Google Colab, I can simply call the function (hello(2)) and it will execute.

Desired output:

> python test.py
> bad
 
1
  • In Unix (or MacOS or Windows), a child process can't return anything to the parent process (except an exit code, if you count this as return value). Therefore, a program (this includes Python programs) can not return a string. They can print a string to stdout, of course, but you have to tell them to do so. Commented Nov 30, 2022 at 10:52

2 Answers 2

2

You don't print anything to STDOUT so you won't see the good/bad in your terminal.

You should change hello(2) line to print(hello(2)) in your code (In this case the return value of hello(2) function call will be printed to STDOUT file descriptor) then you will see your result in your terminal.

Sign up to request clarification or add additional context in comments.

1 Comment

Just a note that OP should probably also return proper exit code (be it 0 for "good" and non-zero for "bad")
0

In case you want to sent the argument when calling the script you could do it like this:

#!/usr/bin/env python
import sys

def hello(x):
    if x > 5:
        return "good"
    else:
        return "bad"

 print(hello(int(sys.argv[1])))

And so you could call the function like so:

python test.py 6

Then the output would be:

> python test.py 6
> good

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.