Search code examples
pythonfor-loopoperators

Python: mathematical operations


I want to creat a programa that reads two input numbers and do mathematical operations on them: addition, multiplication, division and subtraction.

I have this code:

sum=0
multi=0
div=0
sub=0

for i in range(1,3):
    num = int(input(f'{i}º dígito: '))
    sum+=num
    multi*=num
    div/=num
    sub-=num

print(f'Soma: {sum}')
print(f'Multi: {multi}')
print(f'Div: {div}')
print(f'Sub: {sub}')

The sum works well, but the others don't and I don't understand why. If I input 3 as the first number and 2 as the second number the sum is 5 (all good), but the multi prints 0, the div 0.0 and the sub -5.

What am I doing wrong?


Solution

  • As mentioned in the comments, defining the variables as 0 from teh beginning and operating straightforward on them may cause problems because it will do things like 0 * num or 0 / num.

    For only two inputs you don't need a loop. But if you want to loop anyway (let's say that you're considering adding the possibility of working with more inputs in the future), I would consider that the inputted values that you want to store are 1) conceptually similar: they're all numbers inputted by the user that you'll use in the calculations; 2) they have an order. So, the data type you need is probably a list.

    num = []
    i = 1
    while i <= 2:
        num.append(int(input(f'{i}º dígito: ')))
        i += 1
        
    soma = num[0] + num[1]
    multi = num[0] * num[1]
    sub = num[0] - num[1]
    
    try:
        div = num[0] / num[1]
    except ZeroDivisionError:
        div = "You can't divide by zero!"
    
    print(f'Soma: {soma}')
    print(f'Multi: {multi}')
    print(f'Div: {div}')
    print(f'Sub: {sub}')
    

    Some other changes:

    • soma instead of sum since sum is a reserved word. One that you may want to use if dealing with many inputs :)

    • while i <= 2 instead of for for i in range(1,3) for readability. This will come handy if you need to adapt the code (e.g. you could ask the user to input the value for i).

    • try - except block to handle the case of division by zero.

    To see why the list is a good holder here, let's suppose you allow the user to input more than two numbers. They introduce three numbers x, y and z and you want the division to output (x/y)/z. Then you can just loop over the values in your list:

    div = num[0]
    for i in range(1, len(num)):
        try:
            div /= num[i]
        except ZeroDivisionError:
            div = "You can't divide by zero!"
            break