Question

In: Computer Science

Program 3: Command Line Calculator Topics: Functions or methods, global variables Overview You will build a...

Program 3: Command Line Calculator

Topics: Functions or methods, global variables

Overview

You will build a simple command line calculator. It supports addition (add), subtraction (sub), multiplication (mul), division (div), and calculation of the absolute value (abs). You will use functions to support each type of calculation. You can assume that the numbers are float data types.

Software Specifications

The user interacts with program by entering a command, followed by some parameters at the command prompt “>”. For example, if the user wants to add 4 and 5, he/she enters “add 4 5” and hits the return key. The system then outputs the result of the addition command (in this case, 9).   See sample run output below for more examples.

Once the command’s operation is completed, the system goes back to the command prompt waiting for another command from the user.   The commands are “add”, “sub”, “mul”, “div”, and “abs”. All the commands take two arguments except for “abs” which takes one argument. Each command will call the corresponding function to perform the calculation. Name each function the same name as the command. The “quit” command calls the printStats function and ends the program. The printStats function prints the number of times each function were called (executed). To keep track of function call usage, you will need global variables which can be shared across functions.

Command

# of arguments

Behavior

add

2

Adds the two arguments.

sub

2

Subtracts the second argument from the first argument.

mul

2

Multiplies the two arguments.

div

2

Divides the first argument by the second argument.

If the second argument is 0, print “Error: Division by zero” and return 0.

abs

1

Computes the absolute value of the argument.

quit

0

Prints the function usage statistics, and ends the program.

Parsing the command line

Your program will read the command as a single line. It then splits it into several tokens. The first is the command. Any other tokens after the first are the parameters. To parse a command, simply use the split function on the string. Don’t forget to convert the parameters to floats so that you can perform arithmetic operations.

The code below shows you how to use the split function to extract the command and the parameters.

>>> userinput="add 1 2"
>>> tokens = userinput.split(" ")
>>> print(tokens[0])
add
>>> print(tokens[1])
1
>>> print(tokens[2])
2

Sample Outputs

Welcome to iCalculator.
>add 3 4.0
7.0
>mul 3 5
15.0
>abs 5
5.0
>abs -7
7.0
>abs 8
8.0
>quit
Function usage count
add function : 1
sub function : 0
mul function : 1
div function : 0
abs function : 3

Solutions

Expert Solution

Thanks for the question.
Below is the code you will be needing  Let me know if you have any doubts or if you need anything to change.
Thank You !!
===========================================================================

# check if the token are valid numbers
def valid_number(value):
    try:
        float(value)
        return True
    except:
        return False


def main():
    print('Welcome to iCalculator')
    add = sub = mul = div = absolute = 0
    while True:
        userinput = input('>').lower()
        if userinput == 'quit': break
        tokens = userinput.split(" ")
        if len(tokens) == 2:
            operation = tokens[0]
            if operation == 'abs' and valid_number(tokens[1]):
                print(abs(float(tokens[1].strip())))
                absolute += 1
            else:
                print('Invalid number.')
        elif len(tokens) == 3:
            operation = tokens[0]
            if operation == 'add' and valid_number(tokens[1]) and valid_number(tokens[2]):
                print(float(tokens[1].strip()) + float(tokens[2].strip()))
                add += 1
            elif operation == 'sub' and valid_number(tokens[1]) and valid_number(tokens[2]):
                print(float(tokens[1].strip()) - float(tokens[2].strip()))
                sub += 1
            elif operation == 'mul' and valid_number(tokens[1]) and valid_number(tokens[2]):
                print(float(tokens[1].strip()) * float(tokens[2].strip()))
                mul += 1
            elif operation == 'div' and valid_number(tokens[1]) and valid_number(tokens[2]):
                if float(tokens[2]) != 0:
                    print(float(tokens[1].strip()) / float(tokens[2].strip()))
                    div += 1
                else:
                    print('/0 undefined.')
            else:
                print('Invalid syntax')

        else:
            print('Command not found.')
    print('Function usage count')
    print('add function: {}'.format(add))
    print('sub function: {}'.format(sub))
    print('mul function: {}'.format(mul))
    print('div function: {}'.format(div))
    print('abs function: {}'.format(absolute))


main()

================================================================


Related Solutions

JAVA Overview This program implements a simple, interactive calculator. Major topics writing a program from scratch...
JAVA Overview This program implements a simple, interactive calculator. Major topics writing a program from scratch multiple methods testing In this document program logic & program structure (class, methods, variables) input / output assumptions and limitations documentation & style suggested schedule cover letter discussion questions grading, submission, and due date additional notes challenges sample output test plan Program Logic The program prompts the user to select a type of math problem (addition, subtraction, multiplication, or division), enter the two operands,...
Write a decision-making program with command-line interface to implement a housing-score calculator (inspired by the 2020...
Write a decision-making program with command-line interface to implement a housing-score calculator (inspired by the 2020 Nifty Decision Makers by Evan Peck) Your program will consist of two functions: main() Asks the user 5 questions and stores the answers: year (int), age (int), probation (string), full-time (int), gpa (float) (see sample run below) Calls computeScore(answers), where answers is a list containing the variables in which the answers are stored in the order in which they are received (python lists may...
Overview: You will write a python program that will work with lists and their methods allowing...
Overview: You will write a python program that will work with lists and their methods allowing you to manipulate the data in the list. Additionally you will get to work with randomization. Instructions: Please carefully read the Instructions and Grading Criteria. Write a python program that will use looping constructs as noted in the assignment requirements. Name your program yourlastname_asgn5.py Assignment Requirements IMPORTANT: Follow the instructions below explicitly. Your program must be structured as I describe below. Write a Python...
*****For C++ Program***** Overview For this assignment, write a program that uses functions to simulate a...
*****For C++ Program***** Overview For this assignment, write a program that uses functions to simulate a game of Craps. Craps is a game of chance where a player (the shooter) will roll 2 six-sided dice. The sum of the dice will determine whether the player (and anyone that has placed a bet) wins immediately, loses immediately, or if the game continues. If the sum of the first roll of the dice (known as the come-out roll) is equal to 7...
Design a complete JAVA program with the following methods:- In the main method : 3 variables...
Design a complete JAVA program with the following methods:- In the main method : 3 variables are declared :- employee id, salary and status. A method that will allow user to input employee id and salary. A method that will assign status to “Taxable’ if employee’s salary is more than 2500RM or “Not Taxable” if salary is less and equal to 2500RM. A method that will display the employee’s id , salary and its status. Write the above Using Java.
Write a script that represents a simple command line calculator. It will accept two numbers from...
Write a script that represents a simple command line calculator. It will accept two numbers from command line, and then display sum, difference and product of these two numbers. Provide script code and screenshot of output. Using Linux Ubuntu bash
Write a C program that runs on ocelot for a mini calculator using only the command...
Write a C program that runs on ocelot for a mini calculator using only the command line options. You must use getopt to parse the command line. Usage: minicalc [-a num] [-d num] [-m num] [-s num] [-e] value • The variable value is the starting value. • Value should be validated to be an integer between 1 and 99. Error message and usage shown if not. • -a adds num to value. • -d divides value by num. •...
C PROGRAM In Stage 1, you will be implementing the Draw Line command to draw horizontal...
C PROGRAM In Stage 1, you will be implementing the Draw Line command to draw horizontal and vertical lines. The Draw Line command is given four additional integers, which describe two pixels: the start and end pixels of the line. Each pixel consists of two numbers: the index of the row, and the index of the column. For example, the command 1 10 3 10 10 tells your program to draw a line (1), starting at the pixel at row...
Write a program that takes two command line arguments at the time the program is executed....
Write a program that takes two command line arguments at the time the program is executed. You may assume the user enters only decimal numeric characters. The input must be fully qualified, and the user should be notified of any value out of range for a 23-bit unsigned integer. The first argument is to be considered a data field. This data field is to be is operated upon by a mask defined by the second argument. The program should display...
Write a program that takes two command line arguments at the time the program is executed....
Write a program that takes two command line arguments at the time the program is executed. Both arguments are to be numerical values restricted to 22-bit unsigned integers. The input must be fully qualified, and the user should be notified of any errors with the input provided by the user. The first argument is to be considered a data field. This data field is to be is operated upon by a mask defined by the second argument. The program should...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT