Issue
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
#! /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
Answered By - Diego Torres Milano
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.