Create successive sum multiplication program in Python

Asked

Viewed 1,037 times

0

The requirements are: solve positive and negative numbers; Do twice the one million, never a million times the 2, ie always the fewest sums; use the Try and ask for new execution.

Like I’m trying to do:

import math
L=('s')
while (L=='s'):
 while True:
   try:
    a=int(input('Digite um número: '))
    break
   except: print ('Número inválido. Use um número inteiro.')
 while True:
   try:
    b=int(input('Digite outro número: '))
    break
   except: print ('Número inválido. Use um número inteiro.')

 if (a>0 and b>0) or (a<0 and b<0):
   if abs(a)>=abs(b):
     x=0
     y=0
     for x in range(x,abs(b),1): 
      y=y+a
     print ('O produto entre',a,'e',b,'é igual:',abs(y))
   else:
     x=0
     y=0
     for x in range(x,abs(a),1):
      y=y+b   
     print ('O produto entre',a,'e',b,'é igual:',abs(y))
 else:
   if abs(a)>=abs(b):
     x=0
     y=0
     for x in range(x,abs(b),1): 
      y=y+a
     print ('O produto entre',a,'e',b,'é igual:',-abs(y))
   else:
     x=0
     y=0
     for x in range(x,abs(a),1):
      y=y+b   
     print ('O produto entre',a,'e',b,'é igual:',-abs(y))

 L = input('Se deseja continuar digite s:')
  • This is no place to ask you to solve your homework

1 answer

1

The problem is that you made the process too complicated trying to solve all the items at once. The result of this is dirty code, with a lot of repetition of logic that has all the potential not to work; instead, why not reduce your problem to smaller problems and solve them properly? By the way, this is what we call code units, in case you want to research more.

1) You will need to read an integer from the user and ask again until it enters a valid value. Create a function for this:

def read_int_until_valid(message: str) -> int:
    while True:
        try:
            return int(input(message))
        except ValueError:
            print('Valor inválido, por favor insira um número inteiro')

2) You will need to multiply between two numbers by performing only the sum, so do a function for this:

def multiply_with_sum(a: int, b: int) -> int:
    a_positive = (a >= 0)
    b_positive = (b >= 0)
    result_positive = (a_positive == b_positive)

    a = abs(a)
    b = abs(b)

    lowest = min([a, b])
    biggest = max([a, b])

    multiply = sum(biggest for _ in range(lowest))

    return multiply if result_positive else -multiply

3) You will need a function that reads user inputs and passes them to the function that calculates multiplication then:

def read_input_and_multiply():
    a = read_int_until_valid('Valor de a:')
    b = read_int_until_valid('Valor de b:')

    result = multiply_with_sum(a, b)

    print(f'O produto {a}x{b} vale {result}')

4) Finally, you want to perform this in an infinite loop, then:

def loop():
    while True:
        read_input_and_multiply()

        answer = input('Digite [s] se deseja continuar: ')

        if answer != 's':
            break

And so just call the function loop() for the magic to happen. See working on https://python-multiplicando-atraves-da-soma.acwoss.repl.run.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.