-3
I’m writing a multiplication calculator code that should use only arithmetic operators in the range of -10 >= x <= 10
and should always do the math under the best possible performance, ex.: 3x2 = 3 + 3
and not 3x2 = 2 + 2 + 2
. My problem is that I cannot use the commands in any way while
and for
, I can only use the operators +
and -
. My idea was to do it first using while
and for
and then remove them, but I’m not seeing how that would be possible. Also, I need to print out the account intermediaries, for example: 3 x 10
I would have to print something similar to: 10; 20; 30
and I have no idea how to do that, maybe it’s something that opens up the possibility to be able to do without while
and for
, but I don’t know. I appreciate any help, I’m pretty tied up with this.
def erro_numero():
print(' ')
print('O número deve ser igual ou estar entre -10 e 10.')
def erro_letra():
print(' ')
print('O valor deve ser um número inteiro.')
def erro_0():
print(' ')
print('Não é possível dividir por zero.')
def primeiro_numero():
try:
x = int(input('Digite o valor do primeiro número: '))
if x < -10 or x > 10:
erro_numero()
return primeiro_numero()
else:
return x
except:
erro_letra()
return primeiro_numero()
def segundo_numero():
try:
z = int(input('Digite o valor do segundo número: '))
if z < -10 or z > 10:
erro_numero()
return segundo_numero()
else:
return z
except:
erro_letra()
return segundo_numero()
def produto(p, s):
if p == 0 or s == 0:
return 0
else:
sinal = True
if (p < 0) != (s < 0):
sinal = False
if p < 0:
p = 0 - p
if s < 0:
s = 0 - s
resultado = 0
if p > s:
for i in range(s): #Aqui o for e a função range() precisam ser removidas
resultado = resultado + p
else:
for i in range(p): #Aqui o for e a função range() precisam ser removidas
resultado = resultado + s
if sinal == False:
return 0 - resultado
else:
return resultado
def print_do_valor(pro):
print('O valor do produto é:', pro)
while True: #Essa parte do código é só para fazer rodar
p = primeiro_numero()
s = segundo_numero()
pro = produto(p, s)
print_do_valor(pro)
it is possible to do "no while e for" - but it is not "healthy" - not if the intention of those who passed the exercise was to make you exercise a lot of "if" and "Elif" and copy paste code - but it is definitely not a good way to learn how to program - repetition structures are VERY fundamental in programming - and it is more important myth to master them than copy and paste code equal 10 times doing "if"s.
– jsbueno
has a way that Xercises yes a good "think about programming" without for nem while, which is to simulate the loop using recursion. - if that is the intention at least does not get a lot of repetitions. Your teacher spoke in function and calling itself function?
– jsbueno
He said yes, he said it should be done recursively, so much so that much of the code is written recursively. How, in this case, I would do to make the account and print the results using recursion?
– Matheus Esteves