picturesque
picturesque

Reputation: 13

The code for a calculator I made doesn't act like I thought it would? (Python 3.x)

I'm actively learning Python at the moment. I've already had some experience with code, but not nearly enough that I would call myself a good coder (or even a competent one tbh).

I tried to create a (pretty) simple calculator script. I wanted to make sure the user could choose how many different values (s)he wanted to calculate together. To do that I created a while loop.

uArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

def divide():
    uAmount = int(input("How many different values do you want to add together? (max 10) "))
    if uAmount <= 10:
        for amount in range(0, uAmount):
            uArray[amount] = int(input("enter a number: "))
    else:
        print("ERROR\nMax 10 different values supported")
        return 1

    global uTotal
    uTotal = 1
    for amount1 in range(0, (uAmount - 1)):
        uTotal /= uArray[amount1]

    print("The result is: " + str(uTotal))

I know this code might look REAL ugly to a lot af you and I'm sure that the same process could be done way easier and simpler if I knew how.

I just can't figure out why my current method doesn't work, even after trying to google it.

EXAMPLE: If I choose to use 2 different values. And I make those values 50 and 2, it should give 25 of course. But it gives 0.02 instead.

Thanks in advance to anyone willing to help! (and sorry if this is a noob question ahaha)

Upvotes: 1

Views: 48

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230326

I just can't figure out why my current method doesn't work

Simple. You start with uTotal equal to 1. Then you divide by each of your numbers (except the last). Since you only have two numbers, 50 and 2 and you don't use the second one (due to range(0, uAmount - 1)), the whole calculation equals to this:

1 / 50 # => 0.02

How to fix?

Instead of setting uTotal to 1, set it to the value of the first element. Then apply your operation (division, in this case), using all other elements (except the first).

Array unpacking syntax may come in handy here:

total, *rest = uArray
for operand in rest:
  total /= operand

Upvotes: 2

David
David

Reputation: 23

Currently it's taking 1 and dividing it by your first input, which is 50.

Note that the for loop won't iterate like you were thinking. Need to remove the '- 1'

Here's a version:

uArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

def divide():
    uAmount = int(input("How many different values do you want to add together? (max 10) "))
    if uAmount <= 10:
        for amount in range(0, uAmount):
            uArray[amount] = int(input("enter a number: "))
    else:
        print("ERROR\nMax 10 different values supported")
        return 1

    global uTotal
    uTotal = uArray[0]
    for amount1 in range(1, (uAmount)):
        uTotal /= uArray[amount1]

    print("The result is: " + str(uTotal))

Upvotes: 0

Related Questions