Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calculator
#1
Hi all,

I am trying to code a calculator but I afraid that I don't know how to do the mathematical operation (+, -, *, /) of two numbers by using arrays and for loops in Python.

This is what I've tried so far:

print("Python Calculator ")

symbols = []
items = []

while True:

    operator = (input("Enter your operator >> "))
    numberOne, numberTwo = (input("Enter two numbers >> ")).split()
    proceed = str(input("Another run? "))

    symbols.append([operator])
    items.append([numberOne, numberTwo])

    if proceed.upper != "Y":

        break;

for numberOne, numberTwo in items:
    if operator == "+":
        print(numberOne + numberTwo)

print("Thank you for using my Calculator")
As you all can see there're two different arrays, the first one will store the operators (+, -, *, /) and the second one the numbers (1, 2, 3, 4...), so what I need to do is to set up a condition to get the final result of the operation between two numbers.

Kind regards,

Azure
Reply
#2
What are you trying to do? If all equations will be an operator with two operands there is no need for list
Reply
#3
(Apr-27-2020, 02:56 AM)deanhystad Wrote: What are you trying to do? If all equations will be an operator with two operands there is no need for list

I am trying to do a mathematical operation (*, /, +, -) for two different numbers(inputs). So, I tried to store the two numbers in an array to do the mathematical operation later but I am not sure how can add, divide, multiply or subtract the inputs.

I need to use the loop to keep asking for the operator and numbers until the user input N to stop the program and get the result of the operation. However, the problem is the second part.... the operation itself.

Hope it makes things more clear for you deanhystad!!

Kind regards,

Azure
Reply
#4
(Apr-27-2020, 03:07 AM)azure Wrote:
(Apr-27-2020, 02:56 AM)deanhystad Wrote: What are you trying to do? If all equations will be an operator with two operands there is no need for list

I am trying to do a mathematical operation (*, /, +, -) for two different numbers(inputs). So, I tried to store the two numbers in an array to do the mathematical operation later but I am not sure how can add, divide, multiply or subtract the inputs.

I need to use the loop to keep asking for the operator and numbers until the user input N to stop the program and get the result of the operation. However, the problem is the second part.... the operation itself.

Hope it makes things more clear for you deanhystad!!

Kind regards,

Azure

Update:

I found the way to do the mathematical operation. However, I don't know how print out the result like the example shown below:

Enter your operator ? *

Enter two numbers ? 5 9

5.0000 * 9.0000 = 45.0000

This is my new code:

import operator

def getOperator(op):
    return {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv,
        '%': operator.mod,
        '^': operator.xor,
    }[op]

print("Python Calculator")

while True:

    symbol = input("Enter your operator >> ").strip()
    numbers = list(map(int, input("Enter two numbers >> ").split()))

    print(getOperator(symbol)(numbers[0], numbers[1]))

    proceed = str(input("Do you wish to introduce another number >> "))

    if proceed.upper() != "Y":
        break;

print("Thank you for using my calculator")
What I got so far is:

Python Calculator
Enter your operator >> +
Enter two numbers >> 2 2
4
Do you wish to introduce another number >> n
Thank you for using my calculator

Kind regards,

Azure
Reply
#5
Use % operator for string formatting

print("%10.4f" %(getOperator(symbol)(numbers[0], numbers[1])))
Reply
#6
import operator

def evaluate(v1, op, v2):
    x = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv,
        '%': operator.mod,
        '^': operator.pow,  # <- was bitwise or
    }[op]
    return x(int(v1), int(v2))

print("Python Calculator")

proceed = "Y"
while proceed.upper()[0] == "Y":
    v1, op, v2 = input("Enter your equation >> ").strip().split()
    print(v1, op, v2, '=', evaluate(v1, op, v2))
    proceed = str(input("Do you wish to solve another equation >> "))
 
print("Thank you for using my calculator")
Do you understand what evaluate(), or in your case, getOperator() is doing?
Reply
#7
(Apr-27-2020, 06:58 AM)anbu23 Wrote: Use % operator for string formatting

print("%10.4f" %(getOperator(symbol)(numbers[0], numbers[1])))

Thank you anbu23!

Kind regards,

Azure

(Apr-27-2020, 09:10 AM)deanhystad Wrote:
import operator

def evaluate(v1, op, v2):
    x = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv,
        '%': operator.mod,
        '^': operator.pow,  # <- was bitwise or
    }[op]
    return x(int(v1), int(v2))

print("Python Calculator")

proceed = "Y"
while proceed.upper()[0] == "Y":
    v1, op, v2 = input("Enter your equation >> ").strip().split()
    print(v1, op, v2, '=', evaluate(v1, op, v2))
    proceed = str(input("Do you wish to solve another equation >> "))
 
print("Thank you for using my calculator")
Do you understand what evaluate(), or in your case, getOperator() is doing?

No, I don't.

I got some questions for you deanhystad.

def evaluate(v1, op, v2): --> What are you doing in this line? Are you creating three different variables to store evaluate?

[op] --> What does this line exactly do?

return x(int(v1), int(v2)) --> Why are you calling the variables v1 and v2 with a return?

while proceed.upper()[0] == "Y": --> What does [0] in this case mean? Are you starting the index position from zero?

Kind regards,

Azure
Reply
#8
Asking questions is a poor way to learn. Questions are great, but you will learn much faster if you try to answer questions for yourself.

Wondering what proceed.upper()[] does? Why not try something like this:
proceed = "Y"
while proceed.upper()[0] == "Y":
    v1, op, v2 = input("Enter your equation >> ").strip().split()
    print(v1, op, v2, '=', evaluate(v1, op, v2))
    proceed = str(input("Do you wish to solve another equation >> "))
    print(proceed, proceed.upper(), proceed.upper()[0])
Wondering what return x(int(v1), int(v2) does? Try this
def evaluate(v1, op, v2):
    print('evaluate', v1, op, v2)
    x = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv,
        '%': operator.mod,
        '^': operator.pow,  # <- was bitwise or
    }[op]
    print('return', x, v1, v2, x(int(v1), int(v2)))
    return x(int(v1), int(v2))
You can learn a lot using a few print statements.

as for the [op] think, first answer this question.

What does this code do?
person = {'name': 'Sam', 'age': 25, 'address': '123 4th Street NE'}
What kind of think is 'person'? What is person['name']?
Reply
#9
(Apr-28-2020, 01:22 AM)deanhystad Wrote: Asking questions is a poor way to learn. Questions are great, but you will learn much faster if you try to answer questions for yourself.

Wondering what proceed.upper()[] does? Why not try something like this:
proceed = "Y"
while proceed.upper()[0] == "Y":
    v1, op, v2 = input("Enter your equation >> ").strip().split()
    print(v1, op, v2, '=', evaluate(v1, op, v2))
    proceed = str(input("Do you wish to solve another equation >> "))
    print(proceed, proceed.upper(), proceed.upper()[0])
Wondering what return x(int(v1), int(v2) does? Try this
def evaluate(v1, op, v2):
    print('evaluate', v1, op, v2)
    x = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv,
        '%': operator.mod,
        '^': operator.pow,  # <- was bitwise or
    }[op]
    print('return', x, v1, v2, x(int(v1), int(v2)))
    return x(int(v1), int(v2))
You can learn a lot using a few print statements.

as for the [op] think, first answer this question.

What does this code do?
person = {'name': 'Sam', 'age': 25, 'address': '123 4th Street NE'}
What kind of think is 'person'? What is person['name']?

I am gonna try my best to answer your questions. Please, correct me if I am wrong.

Wondering what proceed.upper()[] does? Why not try something like this:
proceed = "Y"
while proceed.upper()[0] == "Y":
    v1, op, v2 = input("Enter your equation >> ").strip().split()
    print(v1, op, v2, '=', evaluate(v1, op, v2))
    proceed = str(input("Do you wish to solve another equation >> "))
    print(proceed, proceed.upper(), proceed.upper()[0])
In the block of code shown above, based on what I've learnt so far about Python, I can say that in that line we are saying to the program to check out if the input introduces by the user is true, if so the program is gonna keep running. In this case, the .upper() will convert the str in a capital letter as long as the input introduced by the user be "y". Furthermore, you're checking the index/position of the input with [0].

proceed.upper()[0]
Wondering what return x(int(v1), int(v2) does? Try this
def evaluate(v1, op, v2):
    print('evaluate', v1, op, v2)
    x = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv,
        '%': operator.mod,
        '^': operator.pow,  # <- was bitwise or
    }[op]
    print('return', x, v1, v2, x(int(v1), int(v2)))
    return x(int(v1), int(v2))
In the second code of block, you are calling the function "evaluate" that has three different variables, v1, op and v2.
Furthermore, you have created another variable called "x" to store the dictionary that contains the operations.

In the line shown below, you are printing the values already stored in the variables x, v1, v2 within the function and converting the variables v1 and v2 into strings.
Finally, you're calling the value stored in the variables v1 and v2 with return. However, there is a small thing that I cannot understand, why are you calling the variables x in this line? x(int(v1), int(v2)

print('return', x, v1, v2, x(int(v1), int(v2)))
What does this code do?

In the line above the variable "person" is storing a dictionary, since you have a key and a value the information is stored in a different index.

person = {'name': 'Sam', 'age': 25, 'address': '123 4th Street NE'}
What kind of thing is 'person'? What is person['name']?

So, person is a variable that is storing different keys such as, name, age and address, and their respective values such as, Sam, 25 and 123 4th Street NE.

I hope my answers are right!

Kind regards,

Alexis
Reply
#10
Question 1. Looking at only the first letter of proceed allows for typing Y or Yes. Of course it also allows typing Yellowstone or Yippee. A bit of a toss up as to if it is better than comparing the entire proceed string.

Question 3. Person is a dictionary. If you don't really understand dictionaries you need to read up on them now because they are the heart of python.

If you understand dictionaries, Question 2 should be easy. There is a dictionary in evaluate(). What is the dictionary and what key is used to get a value from the dictionary?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020