'How to display the final returned value from a Python program in terminal?
I'm simply writing a Python program that takes in 2 integers and returns the sum. The problem I encounter is that the terminal never displays the returned value, so I have to resort to making a print statement. Is there any way to have the terminal display the returned value of the program?
The code is as follows:
import argparse
def simple_addition():
parser = argparse.ArgumentParser(description = "Simple Addition Program to Test CLI")
# each line add AN argument to our terminal inout
parser.add_argument("first_number", type = int, help = "enter the first integer")
parser.add_argument("second_number", type = int, help = "enter the second integer")
args = parser.parse_args()
# storing the entered argument internally within our code for ease of access
first = args.first_number
second = args.second_number
# calculate and return the sum
sum = first + second
print("A PRINT CALL (not return): ", sum)
return sum
simple_addition()
Following is a screenshot of the terminal when I run this program.
Solution 1:[1]
#! /usr/bin/env python3
import argparse
def simple_addition():
parser = argparse.ArgumentParser(description = "Simple Addition Program to Test CLI")
# each line add AN argument to our terminal inout
parser.add_argument("first_number", type = int, help = "enter the first integer")
parser.add_argument("second_number", type = int, help = "enter the second integer")
args = parser.parse_args()
# storing the entered argument internally within our code for ease of access
first = args.first_number
second = args.second_number
# calculate and return the sum
sum = first + second
#print("A PRINT CALL (not return): ", sum)
return sum
if __name__ == '__main__':
print(simple_addition())
- add shebang on first line and
chmod +x - do not print inside the function
- do it only if it's main (so you can import the module if needed)
then you can invoke it directly
./"CLI Testing.py" 35 45
Solution 2:[2]
Is there any way to have the terminal display the returned value of the program?
Yes, by using print. That's what it's for.
so I have to resort to making a print statement
You do not "resort" to it in the same way as you do not "resort" to the + operator in order to add two numbers. It's just what it's there for.
It's true, however, that printing and returning the result from a function is not good design (for example, it prevents you from reusing the function in cases where you don't want to print the result).
Instead of printing the result from inside the function it would be better to print the returned value in the calling code:
print(simple_addition())
or
result = simple_addition()
print(result)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Diego Torres Milano |
| Solution 2 | mkrieger1 |

