Exercise
Main Function Parameters And Summation
Objective
Develop a Python program named "sum" that takes two integer numbers from the command line and prints their sum. For example, if you run the program with the command sum 5 3, it should output 8.
Example Python Exercise
Show Python Code
import sys
# Define the sum function
def sum_numbers(a, b):
return a + b
# Main function to handle command line input
def main():
# Check if we have exactly two arguments (excluding the script name)
if len(sys.argv) != 3:
print("Please provide exactly two numbers.")
return
try:
# Parse the command line arguments as integers
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
# Calculate and print the sum
result = sum_numbers(num1, num2)
print(result)
except ValueError:
# Handle the case where the inputs are not valid integers
print("Please provide valid integer numbers.")
# Call the main function to execute the program
if __name__ == "__main__":
main()
Output
python sum.py 5 3
Share this Python Exercise